From 588e7a51f62967dcb8c92abc1a80c30d5c460fb7 Mon Sep 17 00:00:00 2001 From: XIGE <710062962@qq.com> Date: Thu, 26 Nov 2026 15:04:45 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=8F=92=E4=BB=B6=E6=BA=90?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=B9=B6=E8=A1=A5=E9=BD=90=E6=A0=87=E5=87=86?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 29 + CHANGELOG.md | 7 + CONTRIBUTING.md | 19 + LICENSE | 21 + README.md | 35 +- locales/en.json | 217 +++++ locales/zh.json | 217 +++++ main.ts | 250 ++++++ manifest.json | 9 + setting/plugin_settings.ts | 54 ++ setting/setting_tab.ts | 376 +++++++++ styles.css | 1288 +++++++++++++++++++++++++++++ utils/datetime.ts | 41 + utils/frontmatter.ts | 366 +++++++++ utils/i18n.ts | 21 + utils/post_import.ts | 247 ++++++ utils/request.ts | 223 +++++ utils/response_type.ts | 5 + utils/util.ts | 276 +++++++ view/add_metasl.ts | 81 ++ view/article_preview.ts | 38 + view/article_type.ts | 878 ++++++++++++++++++++ view/browse_articles.ts | 192 +++++ view/category_tree.ts | 520 ++++++++++++ view/comment_modal.ts | 133 +++ view/meta_edit_modal.ts | 182 +++++ view/push.ts | 943 ++++++++++++++++++++++ view/site_manager.ts | 1562 ++++++++++++++++++++++++++++++++++++ 28 files changed, 8229 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 locales/en.json create mode 100644 locales/zh.json create mode 100644 main.ts create mode 100644 manifest.json create mode 100644 setting/plugin_settings.ts create mode 100644 setting/setting_tab.ts create mode 100644 styles.css create mode 100644 utils/datetime.ts create mode 100644 utils/frontmatter.ts create mode 100644 utils/i18n.ts create mode 100644 utils/post_import.ts create mode 100644 utils/request.ts create mode 100644 utils/response_type.ts create mode 100644 utils/util.ts create mode 100644 view/add_metasl.ts create mode 100644 view/article_preview.ts create mode 100644 view/article_type.ts create mode 100644 view/browse_articles.ts create mode 100644 view/category_tree.ts create mode 100644 view/comment_modal.ts create mode 100644 view/meta_edit_modal.ts create mode 100644 view/push.ts create mode 100644 view/site_manager.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40fbae9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a90ef58 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 变更记录 + +## 2026-11-26 · 初始同步 + +- 同步插件源代码到新 Gitea 仓库。 +- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。 +- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6ed8c08 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本插件提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。 +- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。 +- 涉及对外服务或凭据的配置不要写入代码或文档。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要功能变更请同步更新 `CHANGELOG.md`。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..828853f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 TypechoToObsidian + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 3539028..dce117d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,35 @@ -# Obsidian-To-Typecho +# Obsidian to Typecho +> 仓库:`Obsidian-To-Typecho` · 类型:Obsidian 插件 · 版本:`2.0.13` · 作者:TypechoToObsidian + +把 Obsidian 笔记发布到 Typecho,支持分类标签、图片上传、多站点切换与文章浏览。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `locales/` +- `main.ts` +- `manifest.json` +- `setting/` +- `styles.css` +- `utils/` +- `view/` + +## 安装与使用 + +1. 本仓库仅包含插件源代码,未包含依赖与构建工具;请先按 Obsidian 插件标准流程构建生成 `main.js`。 +2. 将 `manifest.json`、构建后的 `main.js`、`styles.css` 及源码目录放入 `/.obsidian/plugins/<插件 id>/`。 +3. 在 Obsidian「设置 → 第三方插件」中启用该插件。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/locales/en.json b/locales/en.json new file mode 100644 index 0000000..4846fc3 --- /dev/null +++ b/locales/en.json @@ -0,0 +1,217 @@ +{ + "common": { + "success": "success", + "failed": "failed", + "add": "add", + "get": "get", + "empty": "Cannot be empty", + "input": "Please input", + "enter": "(Press Enter to add)", + "loading": "Loading...", + "previousPage": "Previous", + "nextPage": "Next", + "pageOf": "Page {page} / {total}", + "noDataFound": "No data found", + "errorOccurred": "An error occurred" + }, + "sync": { + "title": "Sync to Typecho", + "publish": "publish", + "publishing": "Publishing...", + "created": "published", + "updated": "updated", + "adding": "adding", + "addSuccess": "add success", + "advancedOptions": "Advanced Options", + "alias": "Alias", + "selectSite": "Select site:", + "switchedTo": "Switched to: {name}", + "noCategories": "No categories", + "noTags": "No tags", + "tagSearchPlaceholder": "Search tags (fuzzy match)", + "tagSearchNoMatch": "No matching tag. Try another keyword or click Add", + "tagSearchMore": "{count} more tags, keep typing to narrow down", + "tagSelectedCount": "{selected} / {total} selected", + "permalinkMissing": "Published, but no article link was returned (cid: {cid})" + }, + "setting": { + "siteManagement": "Sites", + "addSite": "Add site", + "addSiteDesc": "Add a new Typecho site", + "add": "+ Add", + "noSite": "No site yet, click the button above to add one", + "unnamedSite": "Unnamed site", + "notConfigured": "Not configured", + "inUse": " (in use)", + "setDefault": "Set default", + "edit": "Edit", + "test": "Test", + "delete": "Delete", + "keepAtLeastOne": "At least one site must be kept", + "globalSettings": "Global settings", + "enableSignature": "Add Obsidian signature", + "enableSignatureDesc": "Insert an \"published from Obsidian\" block at the beginning of the article (requires theme CSS support)", + "openAfterPublish": "Open article after publishing", + "openAfterPublishDesc": "Open the published article in your browser right after a successful publish", + "addSiteTitle": "Add site", + "editSiteTitle": "Edit site", + "siteName": "Site name", + "siteNameDesc": "Used to distinguish multiple sites", + "siteNamePlaceholder": "e.g. My Blog", + "host": "Host", + "hostDesc": "Typecho API address, e.g. https://example.com/index.php/api", + "token": "Token", + "tokenDesc": "API Token", + "tokenPlaceholder": "Enter your API Token", + "importFolder": "Local import folder", + "importFolderDesc": "Downloaded posts are saved under \"this folder / category slug / post title.md\". Each site can use a different folder. Leave empty to use Typecho.", + "importFolderPreview": "Posts will be saved to: {folder}/category-slug/post-title.md", + "importFolderShort": "Import folder: {folder}", + "save": "Save", + "saveSuccess": "Saved", + "fillAllFields": "Please fill in all fields", + "cannotFetchUser": "Cannot fetch user info, please check Host and Token", + "connectFailed": "Connection failed, please check Host and Token", + "connectOk": "Connected! User: {name}", + "connectFailNoUser": "Connection failed: cannot fetch user info", + "connectFailDetail": "Connection failed: {message}", + "defaultSiteName": "Default site", + "managerSection": "Sidebar", + "managerPageSize": "Items per page", + "managerPageSizeDesc": "How many posts and comments to show per page in the sidebar (5-200). The sidebar reloads right after the change.", + "refreshOnStartup": "Refresh on startup", + "refreshOnStartupDesc": "Fetch posts, categories, tags and comments again after Obsidian starts, so you don't have to refresh manually.", + "autoRefreshInterval": "Auto-refresh interval (minutes)", + "autoRefreshIntervalDesc": "How often to refresh the sidebar posts, categories, tags and comments. 0 = disabled (manual refresh only). Refreshing keeps your current page, search term and filters." + }, + "notice": { + "imageUploading": "📥 Uploading image: {fileName}", + "imageUploadFailed": "❌ Image upload failed", + "imageUploaded": "✅ Image uploaded and inserted", + "pasteUploadFailed": "❌ Failed to upload pasted image, please retry" + }, + "error": { + "requestFailed": "Request failed, please check the network or API configuration", + "noFileSelected": "No file selected", + "titleOrContentCannotBeEmpty": "Title or content cannot be empty", + "readFileError": "Read file error, please check the file content", + "noTypechoUser": "No Typecho user, please input the user who uses the operation", + "failedToFetchArticles": "Failed to fetch articles", + "failedToFetchPostDetails": "Failed to fetch post details", + "noFiles": "No files found", + "noEditor": "❌ No editor found, please open a Markdown file first", + "inserted": "✅ Inserted: {title}", + "insertFailed": "❌ Insert failed: {message}", + "unknownError": "Unknown error" + }, + "field": { + "title": "title", + "tag": "tag", + "file": "file", + "domainName": "domain name", + "category": "category", + "typechoUser": "Typecho user, the user who uses the operation", + "article": "article", + "allArticle": "all article", + "type": "Type", + "size": "Size", + "time": "Time" + }, + "file": { + "uploadFile": "Upload File", + "deleteFile": "Delete File", + "copyUrl": "Copy URL to Clipboard", + "uploadingFile": "Uploading file...", + "uploadSuccess": "File uploaded successfully", + "uploadFailed": "File upload failed", + "uploadError": "Error occurred during file upload", + "deleteSuccess": "File deleted successfully", + "deleteFailed": "File deletion failed", + "deleteError": "Error occurred during file deletion", + "deleteConfirm": "Are you sure you want to delete the file {fileName}?", + "copySuccess": "URL for {fileName} has been copied to clipboard", + "copyFailed": "Copy failed: URL is empty", + "itemsPerPage": "Items per page", + "fileType": "Type", + "fileSize": "Size", + "enablePasteUpload": "Auto Upload Pasted Images", + "enablePasteUploadDesc": "Enable automatic upload and Markdown link insertion when pasting images with Ctrl+V", + "removeMetadata": "Remove Metadata", + "removeMetadataDesc": "Automatically remove YAML metadata (--- ... ---) from the top of the article during publication", + "insertToEditor": "Insert into editor", + "cancelUpload": "Cancel upload", + "uploadCancelled": "Upload cancelled", + "preparingUpload": "Preparing upload...", + "preparing": "Preparing...", + "uploadingProgress": "Uploading ({current}/{total})", + "uploadItemFailed": "⚠️ {fileName} failed, skipped", + "uploadAllDone": "✅ All uploads finished!", + "uploadProcessError": "❌ Error occurred during upload", + "uploadPanelTitle": "📎 File upload" + }, + "manager": { + "title": "Site manager", + "open": "Open site manager panel", + "refresh": "Refresh", + "refreshed": "Refreshed", + "switchSite": "Switch site", + "noSites": "No site configured yet. Add one in settings first.", + "pendingComments": "{count} pending", + "pendingCommentsTitle": "{count} pending comments, click to review", + "posts": "Posts", + "newPost": "New post", + "draftName": "Untitled post", + "draftCreated": "Created note: {name}", + "loadMore": "Load more", + "totalItems": "{count} items", + "commentCount": "{count} comments", + "edit": "Edit", + "delete": "Delete", + "reply": "Reply", + "approve": "Approve", + "cancel": "Cancel", + "confirm": "Confirm", + "save": "Save", + "textRequired": "Content cannot be empty", + "nameRequired": "Name cannot be empty", + "actionDone": "Done", + "replyNoMail": "Replied, but no comment-notification plugin hook was found (reply saved)", + "saved": "Saved", + "noComments": "No comments", + "untitled": "Untitled post", + "imported": "Downloaded to: {name}", + "alreadyExists": "Already exists, opening: {name}", + "categories": "Categories", + "newCategory": "New category", + "editCategoryTitle": "Edit category", + "newCategoryTitle": "New category", + "tags": "Tags", + "newTag": "New tag", + "editTagTitle": "Edit tag", + "newTagTitle": "New tag", + "metaName": "Name", + "metaSlug": "Slug", + "metaSlugDesc": "English slug used in the URL, leave empty to keep the current value", + "metaDescription": "Description", + "metaParent": "Parent category", + "metaParentNone": "(none)", + "comments": "Comments", + "commentAll": "All", + "commentPending": "Pending", + "commentUnreplied": "Unreplied", + "replyTo": "Reply to {name}", + "replySubmit": "Send reply", + "replyPlaceholder": "Write your reply", + "editCommentTitle": "Edit comment", + "editCommentSubmit": "Save changes", + "deleteCommentTitle": "Delete comment", + "deleteCommentMessage": "Delete this comment and its replies? This cannot be undone.", + "searchPostsPlaceholder": "Search title / ID (fuzzy)", + "clearSearch": "Clear search", + "searchNoMatch": "No matching post", + "searchCount": "{count} found", + "copyId": "ID: {id} (click to copy)", + "idCopied": "ID copied: {id}", + "openPost": "Open post: {title}" + } +} diff --git a/locales/zh.json b/locales/zh.json new file mode 100644 index 0000000..734b4ce --- /dev/null +++ b/locales/zh.json @@ -0,0 +1,217 @@ +{ + "common": { + "success": "成功", + "failed": "失败", + "add": "添加", + "get": "获取", + "empty": "不能为空", + "input": "请输入", + "enter": "(按回车添加)", + "loading": "加载中...", + "previousPage": "上一页", + "nextPage": "下一页", + "pageOf": "第 {page} 页 / 共 {total} 页", + "noDataFound": "没有找到数据", + "errorOccurred": "发生错误" + }, + "sync": { + "title": "同步到Typecho", + "publish": "发布", + "publishing": "发布中...", + "created": "已发布", + "updated": "已更新", + "adding": "添加中", + "addSuccess": "添加成功", + "advancedOptions": "高级选项", + "alias": "别名", + "selectSite": "选择网站:", + "switchedTo": "已切换到:{name}", + "noCategories": "暂无分类", + "noTags": "暂无标签", + "tagSearchPlaceholder": "搜索标签(支持模糊匹配,输几个字即可)", + "tagSearchNoMatch": "没有匹配的标签,换个关键词或点右上角「添加」新建", + "tagSearchMore": "还有 {count} 个标签,继续输入关键词可缩小范围", + "tagSelectedCount": "已选 {selected} / 共 {total}", + "permalinkMissing": "已发布,但没取到文章链接(cid: {cid}),可到站点后台打开" + }, + "setting": { + "siteManagement": "网站管理", + "addSite": "添加网站", + "addSiteDesc": "添加新的 Typecho 站点", + "add": "+ 添加", + "noSite": "暂无网站,请点击上方按钮添加", + "unnamedSite": "未命名网站", + "notConfigured": "未配置地址", + "inUse": " (当前使用)", + "setDefault": "设为默认", + "edit": "编辑", + "test": "测试", + "delete": "删除", + "keepAtLeastOne": "至少需要保留一个网站", + "globalSettings": "全局设置", + "enableSignature": "自动添加 Obsidian 标识", + "enableSignatureDesc": "在文章开头自动插入「本文从 Obsidian 发布」标识(需 Typecho 主题支持 CSS 样式)", + "openAfterPublish": "发布后打开文章页", + "openAfterPublishDesc": "发布成功后自动在浏览器打开网站上的文章页面,方便立即查看文章", + "addSiteTitle": "添加网站", + "editSiteTitle": "编辑网站", + "siteName": "网站名称", + "siteNameDesc": "用于区分多个网站", + "siteNamePlaceholder": "例如:我的博客", + "host": "Host", + "hostDesc": "Typecho API 地址,如 https://example.com/index.php/api", + "token": "Token", + "tokenDesc": "API Token", + "tokenPlaceholder": "输入您的 API Token", + "importFolder": "本地导入目录", + "importFolderDesc": "下载的文章会存到「该目录 / 分类 slug / 文章标题.md」,不同网站可以指向不同目录。留空则用 Typecho。", + "importFolderPreview": "文章会存到:{folder}/分类slug/文章标题.md", + "importFolderShort": "导入目录:{folder}", + "save": "保存", + "saveSuccess": "保存成功", + "fillAllFields": "请填写完整信息", + "cannotFetchUser": "无法获取用户信息,请检查 Host 和 Token", + "connectFailed": "连接失败,请检查 Host 和 Token", + "connectOk": "连接成功!用户:{name}", + "connectFailNoUser": "连接失败:无法获取用户信息", + "connectFailDetail": "连接失败:{message}", + "defaultSiteName": "默认网站", + "managerSection": "侧边栏", + "managerPageSize": "列表每页条数", + "managerPageSizeDesc": "侧边栏文章、评论列表每页显示的条数(5-200),修改后侧边栏立即重新加载", + "refreshOnStartup": "启动时自动刷新", + "refreshOnStartupDesc": "打开 Obsidian 后自动重新拉取侧边栏的文章、分类、标签与评论数据,不用手动点刷新", + "autoRefreshInterval": "自动刷新间隔(分钟)", + "autoRefreshIntervalDesc": "每隔多少分钟自动刷新侧边栏的文章、分类、标签与评论数据。0 = 关闭自动刷新,只手动刷新;刷新不会重置当前分页、搜索词或筛选条件。" + }, + "notice": { + "imageUploading": "📥 正在上传图片:{fileName}", + "imageUploadFailed": "❌ 图片上传失败", + "imageUploaded": "✅ 图片已上传并插入", + "pasteUploadFailed": "❌ 粘贴上传图片失败,请重试" + }, + "error": { + "requestFailed": "请求失败,请检查网络或 API 配置", + "noFileSelected": "未选择文件", + "titleOrContentCannotBeEmpty": "标题或内容不能为空", + "readFileError": "读取文件错误,请检查文件内容", + "noTypechoUser": "未设置 Typecho 用户", + "failedToFetchArticles": "获取文章列表失败", + "failedToFetchPostDetails": "获取文章详情失败", + "noFiles": "没有找到文件", + "noEditor": "❌ 没有找到编辑器,请先打开一个 Markdown 文件", + "inserted": "✅ 已插入: {title}", + "insertFailed": "❌ 插入失败: {message}", + "unknownError": "未知错误" + }, + "field": { + "title": "标题", + "tag": "标签", + "file": "文件", + "domainName": "域名", + "category": "分类", + "typechoUser": "Typecho 用户,操作时使用的用户", + "article": "文章", + "allArticle": "全部文章", + "type": "类型", + "size": "大小", + "time": "时间" + }, + "file": { + "uploadFile": "上传文件", + "deleteFile": "删除文件", + "copyUrl": "复制URL到剪贴板", + "uploadingFile": "文件上传中...", + "uploadSuccess": "文件上传成功", + "uploadFailed": "文件上传失败", + "uploadError": "文件上传出错", + "deleteSuccess": "文件删除成功", + "deleteFailed": "文件删除失败", + "deleteError": "文件删除出错", + "deleteConfirm": "确定要删除文件 {fileName} 吗?", + "copySuccess": "已复制 {fileName} 的URL到剪贴板", + "copyFailed": "复制失败:URL为空", + "itemsPerPage": "每页显示", + "fileType": "类型", + "fileSize": "大小", + "enablePasteUpload": "粘贴图片自动上传", + "enablePasteUploadDesc": "启用后,Ctrl+V 粘贴图片将自动上传并插入 Markdown 链接", + "removeMetadata": "去除元数据", + "removeMetadataDesc": "发布时自动去除文章顶部的 YAML 元数据 (--- ... ---)", + "insertToEditor": "插入到编辑器", + "cancelUpload": "取消上传", + "uploadCancelled": "已取消上传", + "preparingUpload": "准备上传...", + "preparing": "准备中...", + "uploadingProgress": "正在上传 ({current}/{total})", + "uploadItemFailed": "⚠️ {fileName} 失败,跳过", + "uploadAllDone": "✅ 全部上传完成!", + "uploadProcessError": "❌ 上传过程异常", + "uploadPanelTitle": "📎 文件上传" + }, + "manager": { + "title": "站点管理", + "open": "打开站点管理面板", + "refresh": "刷新", + "refreshed": "已刷新", + "switchSite": "切换网站", + "noSites": "还没有配置网站,请先在设置里添加", + "pendingComments": "待审核评论 {count}", + "pendingCommentsTitle": "待审核评论 {count} 条,点击查看", + "posts": "文章", + "newPost": "新增文章", + "draftName": "未命名文章", + "draftCreated": "已新建笔记:{name}", + "loadMore": "加载更多", + "totalItems": "共 {count} 项", + "commentCount": "{count} 条评论", + "edit": "编辑", + "delete": "删除", + "reply": "回复", + "approve": "通过", + "cancel": "取消", + "confirm": "确定", + "save": "保存", + "textRequired": "内容不能为空", + "nameRequired": "名称不能为空", + "actionDone": "操作成功", + "replyNoMail": "已回复,但没检测到评论通知插件(回复已保存)", + "saved": "已保存", + "noComments": "暂无评论", + "untitled": "未命名文章", + "imported": "已下载到:{name}", + "alreadyExists": "已存在,直接打开:{name}", + "categories": "分类", + "newCategory": "新增分类", + "editCategoryTitle": "编辑分类", + "newCategoryTitle": "新增分类", + "tags": "标签", + "newTag": "新增标签", + "editTagTitle": "编辑标签", + "newTagTitle": "新增标签", + "metaName": "名称", + "metaSlug": "别名", + "metaSlugDesc": "用于 URL 的英文别名,留空则保持原值", + "metaDescription": "描述", + "metaParent": "父分类", + "metaParentNone": "(无)", + "comments": "评论", + "commentAll": "全部", + "commentPending": "待审核", + "commentUnreplied": "待回复", + "replyTo": "回复 {name}", + "replySubmit": "发送回复", + "replyPlaceholder": "输入回复内容", + "editCommentTitle": "编辑评论", + "editCommentSubmit": "保存修改", + "deleteCommentTitle": "删除评论", + "deleteCommentMessage": "确定要删除这条评论及其回复吗?此操作不可恢复。", + "searchPostsPlaceholder": "搜索文章标题 / ID,模糊匹配", + "clearSearch": "清除搜索", + "searchNoMatch": "没有匹配的文章", + "searchCount": "找到 {count} 篇", + "copyId": "ID:{id}(点击复制)", + "idCopied": "已复制 ID:{id}", + "openPost": "打开文章:{title}" + } +} diff --git a/main.ts b/main.ts new file mode 100644 index 0000000..d6aae8a --- /dev/null +++ b/main.ts @@ -0,0 +1,250 @@ +import { MarkdownView, Notice, Plugin, addIcon } from "obsidian"; +import { settingTab } from "./setting/setting_tab"; +import { PushModal } from "./view/push"; +import { SiteConfig, generateSiteId } from "./setting/plugin_settings"; +import { EditorView } from "@codemirror/view"; +import { Extension } from "@codemirror/state"; +import { + CategoryView, + VIEW_TYPE as ArticleViewType, +} from "./view/article_type"; +import { + SiteManagerView, + VIEW_TYPE as ManagerViewType, +} from "./view/site_manager"; +import { + ObsidianToTypechoSettings, + DEFAULT_SETTINGS, +} from "./setting/plugin_settings"; +import i18n from "./utils/i18n"; +import { Util } from "./utils/util"; + +let settings: ObsidianToTypechoSettings; +let pluginInstance: ObsidianToTypechoPlugin; + +export default class ObsidianToTypechoPlugin extends Plugin { + /** 侧边栏自动刷新定时器(分钟制,0 = 不启动) */ + private autoRefreshTimer: number | null = null; + + async onload() { + pluginInstance = this; + addIcon( + "obsidian-to-typecho", + `` + ); + + await this.loadSettings(); + this.addSettingTab(new settingTab(this.app, this, settings)); + + this.addRibbonIcon( + "obsidian-to-typecho", + i18n.t("sync.title"), + (evt: MouseEvent) => { + new PushModal(this.app).open(); + } + ); + + this.registerView(ArticleViewType, (leaf) => new CategoryView(leaf)); + this.registerView(ManagerViewType, (leaf) => new SiteManagerView(leaf)); + this.registerPasteListener(); + + this.addRibbonIcon("list", i18n.t("manager.title"), () => { + this.activateManagerView(); + }); + + this.addCommand({ + id: "open-site-manager", + name: i18n.t("manager.open"), + callback: () => this.activateManagerView(), + }); + + // 启动时把侧边栏的数据重新拉一遍:上次会话留在面板里的列表可能是旧的, + // 也不该指望用户手动点刷新 + // + // 恢复右侧栏视图必须等布局就绪:onload 阶段 workspace 还没建好, + // 此时 getRightLeaf() 会返回 null,直接 setViewState 会抛 + // 「Cannot read properties of null (reading 'children')」并让插件加载失败 + this.app.workspace.onLayoutReady(() => { + void this.openPluginView(); + if (settings?.refreshOnStartup !== false) { + this.refreshManagerViews(); + } + this.restartAutoRefresh(); + }); + } + + /** + * 重新加载已打开的站点管理侧边栏(数据 + 数量统计) + * gentle=true 用于定时自动刷新:只更新数据,不重置分页/搜索/筛选,避免打断阅读 + */ + refreshManagerViews(gentle = false) { + for (const leaf of this.app.workspace.getLeavesOfType(ManagerViewType)) { + const view = leaf.view as unknown as { + reloadWithSettings?: () => Promise; + autoRefresh?: () => Promise; + }; + if (gentle) { + void view.autoRefresh?.(); + } else { + void view.reloadWithSettings?.(); + } + } + } + + /** 按当前设置重建自动刷新定时器;间隔 <= 0 则关闭 */ + restartAutoRefresh() { + if (this.autoRefreshTimer !== null) { + window.clearInterval(this.autoRefreshTimer); + this.autoRefreshTimer = null; + } + const minutes = Number(settings?.autoRefreshInterval); + if (!Number.isFinite(minutes) || minutes <= 0) return; + this.autoRefreshTimer = window.setInterval(() => { + this.refreshManagerViews(true); + }, minutes * 60 * 1000); + } + + onunload() { + if (this.autoRefreshTimer !== null) { + window.clearInterval(this.autoRefreshTimer); + this.autoRefreshTimer = null; + } + } + + async loadSettings() { + let loadedData = await this.loadData(); + // 数据迁移:兼容旧版本单网站配置 + if (loadedData && loadedData.Host && !loadedData.sites) { + loadedData.sites = [{ + id: generateSiteId(), + name: loadedData.User?.screenName || i18n.t("setting.defaultSiteName"), + Host: loadedData.Host, + Token: loadedData.Token, + User: loadedData.User || { uid: "", url: "", screenName: "", mail: "" }, + }]; + loadedData.activeSiteId = loadedData.sites[0].id; + } + settings = Object.assign({}, DEFAULT_SETTINGS, loadedData); + return settings; + } + + async saveSettings() { + await this.saveData(settings); + } + + private async openPluginView() { + const { workspace } = this.app; + // 已经打开过就直接复用,避免每次加载都重复创建右侧栏视图 + if (workspace.getLeavesOfType(ArticleViewType).length > 0) { + return; + } + try { + const newLeaf = workspace.getRightLeaf(false); + if (newLeaf) { + await newLeaf.setViewState({ + type: ArticleViewType, + active: false, + }); + } + } catch (error) { + // 启动早期布局还没建立时可能拿不到 leaf,交给用户手动打开即可 + console.warn("恢复侧边栏视图失败", error); + } + } + + /** + * 打开(或复用已打开的)站点管理侧边栏 + */ + async activateManagerView() { + const { workspace } = this.app; + const existing = workspace.getLeavesOfType(ManagerViewType)[0]; + if (existing) { + workspace.revealLeaf(existing); + return; + } + const leaf = workspace.getRightLeaf(false); + if (!leaf) return; + await leaf.setViewState({ type: ManagerViewType, active: true }); + workspace.revealLeaf(leaf); + } + + private registerPasteListener() { + this.registerEvent( + this.app.workspace.on("editor-paste", async (evt, editor) => { + await Util.upload.handleImagePaste( + this.app, + editor, + evt.clipboardData! + ); + }) + ); + } +} + +export function getSettings() { + return settings; +} + +export async function saveSettings() { + if (pluginInstance) { + await pluginInstance.saveSettings(); + } +} + +// ========== 多站点管理函数 ========== + +export function getSites(): SiteConfig[] { + return settings?.sites || []; +} + +export function getActiveSite(): SiteConfig | undefined { + if (!settings?.sites || !settings.activeSiteId) return undefined; + return settings.sites.find(site => site.id === settings.activeSiteId); +} + +export function getSite(siteId: string): SiteConfig | undefined { + return settings?.sites?.find(site => site.id === siteId); +} + +export async function setActiveSite(siteId: string): Promise { + const site = getSite(siteId); + if (site) { + settings.activeSiteId = siteId; + await saveSettings(); + new Notice(i18n.t("sync.switchedTo", { name: site.name })); + return true; + } + return false; +} + +export async function addSite(site: SiteConfig): Promise { + if (!site.id) site.id = generateSiteId(); + settings.sites.push(site); + if (!settings.activeSiteId && settings.sites.length === 1) { + settings.activeSiteId = site.id; + } + await saveSettings(); +} + +export async function updateSite(siteId: string, updates: Partial): Promise { + const index = settings.sites.findIndex(s => s.id === siteId); + if (index !== -1) { + settings.sites[index] = { ...settings.sites[index], ...updates }; + await saveSettings(); + return true; + } + return false; +} + +export async function deleteSite(siteId: string): Promise { + const index = settings.sites.findIndex(s => s.id === siteId); + if (index !== -1) { + settings.sites.splice(index, 1); + if (settings.activeSiteId === siteId) { + settings.activeSiteId = settings.sites[0]?.id || ""; + } + await saveSettings(); + return true; + } + return false; +} diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..6941985 --- /dev/null +++ b/manifest.json @@ -0,0 +1,9 @@ +{ + "id": "obsidian-to-typecho", + "name": "Obsidian to Typecho", + "version": "2.0.13", + "minAppVersion": "0.15.0", + "description": "把 Obsidian 笔记发布到 Typecho,支持分类标签、图片上传、多站点切换与文章浏览。", + "author": "TypechoToObsidian", + "isDesktopOnly": false +} \ No newline at end of file diff --git a/setting/plugin_settings.ts b/setting/plugin_settings.ts new file mode 100644 index 0000000..173762d --- /dev/null +++ b/setting/plugin_settings.ts @@ -0,0 +1,54 @@ +// 单个网站配置 +export interface SiteConfig { + id: string; + name: string; + Host: string; + Token: string; + importFolder: string; // 该网站下载文章时使用的本地目录(每个站可以不一样) + User: { uid: string; url: string; screenName: string; mail: string; }; +} + +export interface ObsidianToTypechoSettings { + sites: SiteConfig[]; // 多个网站 + activeSiteId: string; // 当前激活的网站ID + enablePasteUpload: boolean; // 启用粘贴上传 + removeMetadata: boolean; // 移除元数据 + slugMapping: Record; // slug 映射 + enableSignature: boolean; // 启用文章标识 + openAfterPublish: boolean; // 发布后打开文章页 + importFolder: string; // 旧版全局导入目录,仅作站点未单独配置时的回退值 + managerPageSize: number; // 侧边栏文章/评论列表每页条数 + refreshOnStartup: boolean; // 启动 Obsidian 时自动刷新侧边栏数据 + autoRefreshInterval: number; // 自动刷新侧边栏间隔(分钟),0 = 关闭 +} + +export const DEFAULT_SETTINGS: ObsidianToTypechoSettings = { + sites: [], + activeSiteId: "", + enablePasteUpload: false, + removeMetadata: false, + slugMapping: {}, + enableSignature: true, // 默认开启 + openAfterPublish: true, // 默认开启 + importFolder: "Typecho", // 站点没填目录时的回退值 + managerPageSize: 20, // 侧边栏每页 20 条 + refreshOnStartup: true, // 启动时自动刷新侧边栏 + autoRefreshInterval: 5, // 每 5 分钟自动刷新一次侧边栏,0 = 关闭 +}; + +// 辅助函数 +export function generateSiteId(): string { + return `site_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`; +} + +// 创建空网站配置 +export function createEmptySite(): SiteConfig { + return { + id: generateSiteId(), + name: "", + Host: "", + Token: "", + importFolder: "", + User: { uid: "", url: "", screenName: "", mail: "" }, + }; +} \ No newline at end of file diff --git a/setting/setting_tab.ts b/setting/setting_tab.ts new file mode 100644 index 0000000..5397b17 --- /dev/null +++ b/setting/setting_tab.ts @@ -0,0 +1,376 @@ +import plugin from "../main"; +import { App, PluginSettingTab, Setting, Modal, Notice } from "obsidian"; +import { ObsidianToTypechoSettings, SiteConfig, createEmptySite } from "./plugin_settings"; +import { HttpUtils } from "../utils/request"; +import i18n from "../utils/i18n"; +import { resolveImportFolder } from "../utils/post_import"; +import { getSites, addSite, updateSite, deleteSite, setActiveSite, getActiveSite } from "../main"; + +export class settingTab extends PluginSettingTab { + plugin: plugin; + settings: ObsidianToTypechoSettings; + private reloadTimer = 0; + + constructor(app: App, plugin: plugin, settings: ObsidianToTypechoSettings) { + super(app, plugin); + this.plugin = plugin; + this.settings = settings; + } + + async display() { + const { containerEl } = this; + containerEl.empty(); + + // ========== 网站管理区域 ========== + containerEl.createEl("h3", { text: i18n.t("setting.siteManagement") }); + + new Setting(containerEl) + .setName(i18n.t("setting.addSite")) + .setDesc(i18n.t("setting.addSiteDesc")) + .addButton((btn) => + btn + .setButtonText(i18n.t("setting.add")) + .setCta() + .onClick(() => { + new SiteEditModal(this.app, null, async (site) => { + await addSite(site); + this.display(); + }).open(); + }) + ); + + const sites = getSites(); + if (sites.length === 0) { + containerEl.createDiv({ + text: i18n.t("setting.noSite"), + cls: "setting-item-description", + }); + } else { + for (const site of sites) { + const isActive = getActiveSite()?.id === site.id; + const siteSetting = new Setting(containerEl) + .setName(site.name || i18n.t("setting.unnamedSite")) + .setDesc( + `${site.Host || i18n.t("setting.notConfigured")}${ + isActive ? i18n.t("setting.inUse") : "" + } · ${i18n.t("setting.importFolderShort", { + folder: resolveImportFolder(site), + })}` + ); + + if (!isActive) { + siteSetting.addButton((btn) => + btn + .setButtonText(i18n.t("setting.setDefault")) + .onClick(async () => { + await setActiveSite(site.id); + // 同步请求地址,否则后续请求仍打到原站点 + HttpUtils.setCurrentSite(site.Host, site.Token); + this.display(); + }) + ); + } + + siteSetting.addButton((btn) => + btn.setButtonText(i18n.t("setting.edit")).onClick(() => { + new SiteEditModal(this.app, site, async (updatedSite) => { + await updateSite(site.id, updatedSite); + this.display(); + }).open(); + }) + ); + + siteSetting.addButton((btn) => + btn.setButtonText(i18n.t("setting.test")).onClick(async () => { + await testSiteConnection(site); + }) + ); + + siteSetting.addButton((btn) => + btn + .setButtonText(i18n.t("setting.delete")) + .setWarning() + .onClick(async () => { + if (sites.length === 1) { + new Notice(i18n.t("setting.keepAtLeastOne")); + return; + } + await deleteSite(site.id); + this.display(); + }) + ); + } + } + + containerEl.createEl("hr"); + containerEl.createEl("h3", { text: i18n.t("setting.globalSettings") }); + + // ========== 全局设置 ========== + new Setting(containerEl) + .setName(i18n.t("file.enablePasteUpload")) + .setDesc(i18n.t("file.enablePasteUploadDesc")) + .addToggle((toggle) => + toggle + .setValue(this.settings.enablePasteUpload) + .onChange(async (value) => { + this.settings.enablePasteUpload = value; + await this.plugin.saveSettings(); + }) + ); + + new Setting(containerEl) + .setName(i18n.t("file.removeMetadata")) + .setDesc(i18n.t("file.removeMetadataDesc")) + .addToggle((toggle) => + toggle + .setValue(this.settings.removeMetadata) + .onChange(async (value) => { + this.settings.removeMetadata = value; + await this.plugin.saveSettings(); + }) + ); + + new Setting(containerEl) + .setName(i18n.t("setting.enableSignature")) + .setDesc(i18n.t("setting.enableSignatureDesc")) + .addToggle((toggle) => + toggle + .setValue(this.settings.enableSignature) + .onChange(async (value) => { + this.settings.enableSignature = value; + await this.plugin.saveSettings(); + }) + ); + + new Setting(containerEl) + .setName(i18n.t("setting.openAfterPublish")) + .setDesc(i18n.t("setting.openAfterPublishDesc")) + .addToggle((toggle) => + toggle + .setValue(this.settings.openAfterPublish) + .onChange(async (value) => { + this.settings.openAfterPublish = value; + await this.plugin.saveSettings(); + }) + ); + + // ========== 侧边栏 ========== + containerEl.createEl("hr"); + containerEl.createEl("h3", { text: i18n.t("setting.managerSection") }); + + new Setting(containerEl) + .setName(i18n.t("setting.managerPageSize")) + .setDesc(i18n.t("setting.managerPageSizeDesc")) + .addText((text) => { + text.inputEl.type = "number"; + text.inputEl.min = "5"; + text.inputEl.max = "200"; + text.inputEl.step = "5"; + text.setValue(String(this.pageSize())) + .setPlaceholder("20") + .onChange(async (value) => { + const parsed = Number.parseInt(value, 10); + if (!Number.isFinite(parsed)) return; + // 夹在 5~200,避免填 0 或超大值把接口打爆 + const clamped = Math.min(200, Math.max(5, parsed)); + this.settings.managerPageSize = clamped; + await this.plugin.saveSettings(); + this.refreshManagerViews(); + }); + }); + + new Setting(containerEl) + .setName(i18n.t("setting.refreshOnStartup")) + .setDesc(i18n.t("setting.refreshOnStartupDesc")) + .addToggle((toggle) => + toggle + .setValue(this.settings.refreshOnStartup !== false) + .onChange(async (value) => { + this.settings.refreshOnStartup = value; + await this.plugin.saveSettings(); + }) + ); + + new Setting(containerEl) + .setName(i18n.t("setting.autoRefreshInterval")) + .setDesc(i18n.t("setting.autoRefreshIntervalDesc")) + .addSlider((slider) => + slider + .setLimits(0, 60, 1) + .setValue(this.autoRefreshInterval()) + .setDynamicTooltip() + .onChange(async (value) => { + this.settings.autoRefreshInterval = value; + await this.plugin.saveSettings(); + this.plugin.restartAutoRefresh(); + }) + ); + } + + /** 读当前每页条数,脏数据回落到 20 */ + private pageSize(): number { + const value = Number(this.settings.managerPageSize); + if (!Number.isFinite(value) || value < 5) return 20; + return Math.min(200, Math.round(value)); + } + + /** 读自动刷新间隔(分钟),脏数据回落到默认 5;0 = 关闭 */ + private autoRefreshInterval(): number { + const value = Number(this.settings.autoRefreshInterval); + if (!Number.isFinite(value) || value < 0) return 5; + return Math.min(60, Math.round(value)); + } + + /** 已打开的侧边栏跟着改,不用手动关开 */ + private refreshManagerViews() { + // 输入框逐字触发,防抖一下,避免每敲一位就打一次接口 + if (this.reloadTimer) window.clearTimeout(this.reloadTimer); + this.reloadTimer = window.setTimeout(() => { + this.reloadTimer = 0; + for (const leaf of this.app.workspace.getLeavesOfType( + "obsidian-to-typecho-manager" + )) { + const view = leaf.view as unknown as { + reloadWithSettings?: () => Promise; + }; + void view.reloadWithSettings?.(); + } + }, 500); + } +} + +// ========== 网站编辑弹窗 ========== +class SiteEditModal extends Modal { + private site: SiteConfig; + private onSave: (site: SiteConfig) => void; + private isEdit: boolean; + + constructor(app: App, site: SiteConfig | null, onSave: (site: SiteConfig) => void) { + super(app); + this.site = site ? { ...site } : createEmptySite(); + this.onSave = onSave; + this.isEdit = !!site; + } + + async onOpen() { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { + text: i18n.t(this.isEdit ? "setting.editSiteTitle" : "setting.addSiteTitle"), + }); + + new Setting(contentEl) + .setName(i18n.t("setting.siteName")) + .setDesc(i18n.t("setting.siteNameDesc")) + .addText((text) => + text + .setValue(this.site.name) + .setPlaceholder(i18n.t("setting.siteNamePlaceholder")) + .onChange((value) => (this.site.name = value)) + ); + + new Setting(contentEl) + .setName(i18n.t("setting.host")) + .setDesc(i18n.t("setting.hostDesc")) + .addText((text) => + text + .setValue(this.site.Host) + .setPlaceholder("https://example.com/index.php/api") + .onChange((value) => (this.site.Host = value)) + ); + + new Setting(contentEl) + .setName(i18n.t("setting.token")) + .setDesc(i18n.t("setting.tokenDesc")) + .addText((text) => + text + .setValue(this.site.Token) + .setPlaceholder(i18n.t("setting.tokenPlaceholder")) + .onChange((value) => (this.site.Token = value)) + ); + + // 每个站点自己的下载目录,不同网站可以落到不同的文件夹 + const folderSetting = new Setting(contentEl) + .setName(i18n.t("setting.importFolder")) + .setDesc(i18n.t("setting.importFolderDesc")); + + folderSetting.addText((text) => + text + .setValue(this.site.importFolder ?? "") + .setPlaceholder("Typecho") + .onChange((value) => { + this.site.importFolder = value.trim(); + // 实时把最终路径显示出来,免得只填了目录猜不到落在哪 + folderSetting.setDesc( + i18n.t("setting.importFolderPreview", { + folder: resolveImportFolder(this.site), + }) + ); + }) + ); + + new Setting(contentEl).addButton((btn) => + btn + .setButtonText(i18n.t("setting.save")) + .setCta() + .onClick(async () => { + if (!this.site.name || !this.site.Host || !this.site.Token) { + new Notice(i18n.t("setting.fillAllFields")); + return; + } + + const oldHost = HttpUtils.getCurrentHost(); + const oldToken = HttpUtils.getCurrentToken(); + + HttpUtils.setCurrentSite(this.site.Host, this.site.Token); + + try { + const res = await HttpUtils.get("/userList"); + if (res?.data?.[0]) { + this.site.User = res.data[0]; + this.onSave(this.site); + new Notice(i18n.t("setting.saveSuccess")); + this.close(); + } else { + new Notice(i18n.t("setting.cannotFetchUser")); + } + } catch (e) { + // 真实原因(Token 不对、接口不存在、服务器报错)HttpUtils + // 已经弹过,这里只在它没弹时补一句 + HttpUtils.notifyError(e, i18n.t("setting.connectFailed")); + HttpUtils.setCurrentSite(oldHost, oldToken); + } + }) + ); + } + + onClose() { + this.contentEl.empty(); + } +} + +// ========== 测试网站连接 ========== +async function testSiteConnection(site: SiteConfig): Promise { + const oldHost = HttpUtils.getCurrentHost(); + const oldToken = HttpUtils.getCurrentToken(); + + HttpUtils.setCurrentSite(site.Host, site.Token); + + try { + const res = await HttpUtils.get("/userList"); + if (res?.data?.[0]) { + new Notice(i18n.t("setting.connectOk", { name: res.data[0].screenName })); + } else { + new Notice(i18n.t("setting.connectFailNoUser")); + } + } catch (e) { + HttpUtils.notifyError( + e, + i18n.t("setting.connectFailDetail", { + message: (e as any)?.message || i18n.t("error.unknownError"), + }) + ); + } finally { + HttpUtils.setCurrentSite(oldHost, oldToken); + } +} diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..ee672b8 --- /dev/null +++ b/styles.css @@ -0,0 +1,1288 @@ +/* ========================================================================== + 配色一律走 Obsidian 语义变量,深浅色主题切换时自动适配。 + 本文件里唯一保留的硬编码颜色是图片预览浮层上的白色文字 + (它铺在 85% 黑色遮罩上,与主题无关)。 + ========================================================================== */ + +/* ---------------- 文章树(右侧栏) ---------------- */ + +.tree-container { + color: var(--text-normal); + font-family: var(--font-interface); + padding: 8px; +} + +.tree-node-list, +.tree-container ul.tree-node-list { + list-style: none; + list-style-type: none; + margin: 0; + padding-left: 0; +} + +.tree-node-list ul { + padding-left: 16px; + position: relative; +} + +.tree-node-list ul::before { + background: transparent; + border-left: 1px dashed var(--background-modifier-border); + bottom: 0; + content: ""; + left: 8px; + position: absolute; + top: 0; + width: 1px; +} + +.tree-node-item { + margin-bottom: 4px; + position: relative; +} + +.tree-children { + margin-top: 4px; + transition: all 0.2s ease-in-out; +} + +.tree-node-wrapper { + align-items: center; + border-radius: 6px; + cursor: pointer; + display: flex; + padding: 6px 8px; + transition: background-color 0.15s ease-in-out; + user-select: none; +} + +.tree-node-wrapper:hover { + background-color: var(--background-modifier-hover); +} + +.tree-toggle-icon { + color: var(--text-muted); + cursor: pointer; + font-size: 12px; + margin-right: 8px; + transition: transform 0.2s ease-in-out, color 0.15s ease-in-out; + user-select: none; +} + +.tree-toggle-icon.expanded { + color: var(--text-normal); + transform: rotate(90deg); +} + +.tree-article-icon, +.tree-link-icon { + font-size: 14px; + margin-right: 6px; + transition: color 0.15s ease-in-out; +} + +.tree-article-icon { + color: var(--text-accent); +} + +.tree-link-icon { + color: var(--text-accent); +} + +.tree-node-wrapper:hover .tree-article-icon, +.tree-node-wrapper:hover .tree-link-icon { + color: var(--text-accent-hover); +} + +.tree-node-label { + flex: 1; + font-size: 14px; + color: var(--text-normal); + transition: color 0.15s ease-in-out; +} + +.tree-link-icon svg, +.tree-article-icon.inline-icon svg { + cursor: pointer; + height: 12px; + margin-left: 4px; + vertical-align: middle; + width: 12px; +} + +/* ---------------- 文件列表 ---------------- */ + +.file-list-container { + padding: 8px; +} + +.file-list { + list-style: none; + margin: 0; + padding: 0; +} + +.file-item { + align-items: center; + background-color: var(--background-primary-alt); + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + display: flex; + justify-content: space-between; + margin-bottom: 8px; + padding: 10px 12px; + transition: background-color 0.15s ease-in-out; +} + +.file-item:hover { + background-color: var(--background-modifier-hover); +} + +.file-info-container { + display: flex; + align-items: center; + flex: 1; +} + +.file-preview-container { + margin-right: 12px; + width: 40px; + height: 40px; + overflow: hidden; + border-radius: 4px; + flex-shrink: 0; +} + +.file-preview-img { + width: 100%; + height: 100%; + object-fit: cover; + cursor: pointer; + transition: transform 0.2s ease-in-out; +} + +.file-preview-img:hover { + transform: scale(1.1); +} + +.file-text-container { + display: flex; + flex-direction: column; + flex: 1; +} + +.file-title { + color: var(--text-normal); + font-size: 14px; + margin-bottom: 4px; +} + +.file-type { + color: var(--text-muted); + font-size: 12px; +} + +.file-meta-container { + display: flex; + flex-direction: column; + align-items: flex-end; + margin-left: 12px; +} + +.file-time { + color: var(--text-muted); + font-size: 12px; + margin-bottom: 8px; +} + +.file-action-container { + display: flex; + gap: 8px; +} + +.file-action-button { + background-color: transparent; + border: none; + border-radius: 4px; + color: var(--text-muted); + cursor: pointer; + font-size: 14px; + padding: 4px; + box-shadow: none; + transition: all 0.15s ease-in-out; +} + +.file-action-button:hover { + background-color: var(--background-modifier-hover); + color: var(--text-normal); +} + +.delete-button:hover { + color: var(--text-error); +} + +/* ---------------- 上传区 ---------------- */ + +.upload-container { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 16px; + padding: 0 8px; +} + +.page-size-container { + display: flex; + align-items: center; + gap: 8px; +} + +.page-size-label { + color: var(--text-muted); + font-size: 14px; +} + +.page-size-select { + background-color: var(--interactive-normal); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + color: var(--text-normal); + cursor: pointer; + font-size: 14px; + padding: 4px 8px; + transition: all 0.15s ease-in-out; +} + +.page-size-select:hover, +.page-size-select:focus { + border-color: var(--background-modifier-border-hover); + outline: none; +} + +.upload-button { + align-items: center; + background-color: var(--interactive-normal); + border: none; + border-radius: 4px; + color: var(--text-normal); + cursor: pointer; + display: flex; + font-size: 14px; + gap: 8px; + padding: 8px 12px; + box-shadow: none; + transition: background-color 0.15s ease-in-out; +} + +.upload-button:hover { + background-color: var(--interactive-hover); +} + +/* ---------------- 图片预览浮层(铺在黑色遮罩上,白字固定) ---------------- */ + +.image-preview-modal { + background-color: rgba(0, 0, 0, 0.85); +} + +.image-preview-container { + display: flex; + flex-direction: column; + align-items: center; + padding: 20px; + max-width: 90vw; +} + +.image-preview-title { + color: #fff; + font-size: 18px; + margin-bottom: 12px; + text-align: center; +} + +.image-preview-info { + display: flex; + flex-wrap: wrap; + justify-content: center; + margin-bottom: 16px; + width: 100%; +} + +.image-info-item { + background-color: rgba(255, 255, 255, 0.12); + border-radius: 4px; + color: #eaeaea; + font-size: 12px; + margin: 0 6px 6px 0; + padding: 4px 8px; +} + +.image-preview-img { + border-radius: 4px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5); + max-height: 80vh; + max-width: 100%; + object-fit: contain; +} + +/* ---------------- 分页控件 ---------------- */ + +.pagination-container { + align-items: center; + display: flex; + justify-content: center; + margin-top: 16px; +} + +.pagination-button { + background-color: var(--interactive-normal); + border: none; + border-radius: 4px; + color: var(--text-normal); + cursor: pointer; + margin: 0 8px; + padding: 6px 12px; + box-shadow: none; + transition: background-color 0.15s ease-in-out; +} + +.pagination-button:hover { + background-color: var(--interactive-hover); +} + +.pagination-info { + color: var(--text-muted); + font-size: 14px; +} + +/* ---------------- 文章浏览弹窗 ---------------- */ + +.browse-articles-modal { + margin: 0 auto; + max-width: 800px; +} + +.browse-articles-modal .browse-article-item { + border-bottom: 1px solid var(--background-modifier-border); + padding: 1rem; + transition: background-color 0.15s; +} + +.browse-articles-modal .browse-article-item:hover { + background-color: var(--background-modifier-hover); +} + +.browse-articles-modal .article-title { + font-size: 1.1rem; + margin-bottom: 0.5rem; +} + +.browse-articles-modal .article-title .download-icon { + color: var(--text-muted); + cursor: pointer; + font-size: 0.9rem; + margin-left: 1rem; +} + +.browse-articles-modal .article-title a { + color: var(--text-link); + text-decoration: none; +} + +.browse-articles-modal .article-date { + color: var(--text-muted); + font-size: 0.9em; +} + +.browse-articles-modal .pagination { + align-items: center; + display: flex; + gap: 1rem; + justify-content: center; + margin-top: 1.5rem; +} + +.browse-articles-modal .pagination button { + background-color: var(--interactive-normal); + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + color: var(--text-normal); + cursor: pointer; + padding: 0.4rem 0.8rem; + transition: all 0.15s; +} + +.browse-articles-modal .pagination button:hover:not(:disabled) { + background-color: var(--interactive-accent); + border-color: var(--interactive-accent); + color: var(--text-on-accent); +} + +.browse-articles-modal .pagination button:disabled { + cursor: not-allowed; + opacity: 0.5; +} + +.browse-articles-modal .no-articles { + color: var(--text-muted); + padding: 2rem; + text-align: center; +} + +/* ---------------- 预览小浮窗 ---------------- */ + +.preview-popup { + background-color: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + box-shadow: var(--shadow-s); + color: var(--text-normal); + font-size: 0.9em; + max-width: 300px; + padding: 0.75rem 1rem; + position: absolute; + transition: opacity 0.2s ease-in-out; + word-break: break-word; + z-index: 9999; +} + +.preview-popup::after { + border-color: transparent transparent var(--background-secondary) transparent; + border-style: solid; + border-width: 0 6px 6px 6px; + content: ""; + left: 16px; + position: absolute; + top: -6px; +} + +/* ---------------- 文章预览弹窗 ---------------- */ + +.article-preview-modal { + max-height: 80vh; + max-width: 80vw; + opacity: 1; + overflow: auto; + transform: scale(1); + transition: opacity 0.3s ease, transform 0.3s ease; +} + +.article-preview-modal.fade-enter { + opacity: 0; + transform: scale(0.95); +} + +.article-preview-modal.fade-enter-active { + opacity: 1; + transform: scale(1); +} + +.article-preview-modal.fade-exit { + opacity: 1; + transform: scale(1); +} + +.article-preview-modal.fade-exit-active { + opacity: 0; + transform: scale(0.95); +} + +/* ---------------- 发布弹窗里的分类/标签选择 ---------------- */ + +.tab-container { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 10px; +} + +.tab-container .selected { + background: var(--background-modifier-hover); +} + +.tab-span { + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: 999px; + color: var(--text-muted); + cursor: pointer; + padding: 3px 10px; + font-size: 12px; + transition: all 0.15s ease-in-out; +} + +.tab-span:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} + +.tab-span.active { + background: var(--interactive-accent); + border-color: var(--interactive-accent); + color: var(--text-on-accent); +} + +/* ========================================================================== + 站点管理侧边栏 + 结构:工具栏 → 主 tab → 面板(头 / 滚动列表 / 分页) + 所有颜色走 Obsidian 变量,深浅色主题切换不用改样式 + ========================================================================== */ + +.otm-container { + /* 内容左右基准边距 */ + --otm-pad: 10px; + /* 滚动条实际占宽,JS 会按真实值覆盖;面板头/工具栏/列表右内边距都按它算 */ + --otm-gutter: 8px; + height: 100%; + /* 左右上内边距清零,底部留给 JS 按状态栏实际遮挡高度覆盖 */ + padding: 0; + padding-left: 0 !important; + padding-right: 0 !important; + padding-top: 0 !important; + padding-bottom: 8px !important; + display: flex; + flex-direction: column; + gap: 0; + overflow: hidden; + font-size: 13px; + color: var(--text-normal); +} + +/* ---------------- 工具栏 ---------------- */ + +/* 工具栏:三列网格,左右等宽,中间那格自然居中 */ +.otm-toolbar { + flex: 0 0 auto; + display: grid; + grid-template-columns: 1fr auto 1fr; + align-items: center; + gap: 8px; + /* 右侧多让出滚动条宽度:刷新按钮、面板头的新增、列表里的编辑同一条竖线 */ + padding: 6px calc(var(--otm-pad) + var(--otm-gutter)) 6px var(--otm-pad); +} + +.otm-toolbar-site { + min-width: 0; + display: flex; + align-items: center; + justify-content: flex-start; +} + +.otm-toolbar-right { + min-width: 0; + display: flex; + align-items: center; + justify-content: flex-end; +} + +/* 站点名 + 箭头是一个整体,整块可点 */ +.otm-site-switcher { + display: inline-flex; + align-items: center; + gap: 3px; + min-width: 0; + max-width: 100%; + padding: 3px 6px; + margin-left: -6px; + border-radius: 6px; + cursor: pointer; + color: var(--text-normal); + transition: background-color 0.15s ease; +} + +.otm-site-switcher:hover { + background: var(--background-modifier-hover); +} + +.otm-site-name { + min-width: 0; + font-size: 13px; + font-weight: 600; + line-height: 1.3; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.otm-site-chevron { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + color: var(--text-muted); +} + +.otm-site-switcher:hover .otm-site-chevron { + color: var(--text-normal); +} + +.otm-site-chevron svg { + width: 13px; + height: 13px; +} + +/* 待审核评论:带文案,文字左右居中,位置固定在工具栏正中 + * + * 这里刻意不用 --background-modifier-error:不少主题把它定义成实心红, + * 而 --text-error 也是红,叠在一起就是红字压红底,什么都看不清。 + * 改成自己的「淡红底 + 高对比红字 + 淡红描边」,深浅色各一套变量。 + */ +.otm-pending-badge { + --otm-danger-fg: #b42318; + --otm-danger-bg: rgba(217, 45, 32, 0.1); + --otm-danger-bg-hover: rgba(217, 45, 32, 0.18); + --otm-danger-border: rgba(217, 45, 32, 0.22); + justify-self: center; + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + max-width: 100%; + height: 20px; + padding: 0 9px; + font-size: 11px; + font-weight: 600; + line-height: 1; + text-align: center; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: var(--otm-danger-fg); + background: var(--otm-danger-bg); + border: 1px solid var(--otm-danger-border); + border-radius: 999px; + cursor: pointer; + user-select: none; + transition: background-color 0.15s ease, border-color 0.15s ease; +} + +.otm-pending-badge:hover { + background: var(--otm-danger-bg-hover); + border-color: var(--otm-danger-fg); +} + +/* 深色:同一套变量换个值,只动变量不动 color/background, + * 这样下面的 .is-empty 仍然能盖住 */ +body.theme-dark .otm-pending-badge, +body.theme-dark .otm-badge-waiting { + --otm-danger-fg: #ff9d9d; + --otm-danger-bg: rgba(255, 106, 106, 0.16); + --otm-danger-bg-hover: rgba(255, 106, 106, 0.26); + --otm-danger-border: rgba(255, 106, 106, 0.3); +} + +/* 0 条时退成中性色,位置不动,不抢视线 */ +.otm-pending-badge.is-empty { + color: var(--text-muted); + background: var(--background-modifier-hover); + border-color: transparent; + font-weight: 500; +} + +.otm-pending-badge.is-empty:hover { + background: var(--background-modifier-active-hover, var(--background-modifier-hover)); +} + +/* ---------------- 主 tab ---------------- */ + +.otm-main-tabs { + flex: 0 0 auto; + display: flex; + gap: 2px; + padding: 0 6px; + border-bottom: 1px solid var(--background-modifier-border); +} + +.otm-main-tab { + flex: 1 1 0; + min-width: 0; + display: flex; + align-items: center; + justify-content: center; + gap: 4px; + margin-bottom: -1px; + padding: 7px 4px 6px; + font-size: 12px; + color: var(--text-muted); + border-bottom: 2px solid transparent; + cursor: pointer; + user-select: none; + white-space: nowrap; + overflow: hidden; + transition: color 0.15s ease, background-color 0.15s ease; +} + +.otm-main-tab:hover { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +.otm-main-tab.is-active { + color: var(--text-accent); + border-bottom-color: var(--interactive-accent); + font-weight: 600; +} + +.otm-tab-label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +/* tab 标题后的数量:浅底 + 常规文字色,深浅主题都读得清 */ +.otm-tab-count { + flex: 0 0 auto; + min-width: 16px; + padding: 0 5px; + font-size: 10px; + font-weight: 600; + line-height: 16px; + text-align: center; + color: var(--text-muted); + background: var(--background-modifier-hover); + border-radius: 999px; +} + +.otm-main-tab.is-active .otm-tab-count { + color: var(--text-on-accent); + background: var(--interactive-accent); +} + +.otm-tab-count.is-hidden { + display: none; +} + +/* ---------------- 面板 ---------------- */ + +.otm-panels { + flex: 1 1 auto; + min-height: 0; + display: flex; +} + +.otm-panel { + display: none; + flex: 1 1 auto; + min-width: 0; + min-height: 0; + flex-direction: column; +} + +.otm-panel.is-active { + display: flex; +} + +.otm-panel-header { + flex: 0 0 auto; + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + /* 右侧多让出滚动条宽度,新增/编辑按钮和列表里的编辑按钮同一条竖线 */ + padding: 5px calc(var(--otm-pad) + var(--otm-gutter)) 5px var(--otm-pad); + border-bottom: 1px solid var(--background-modifier-border); +} + +/* 评论面板头部只有统计,统计挪到筛选行后整行隐藏 */ +.otm-panel-header.is-hidden { + display: none; +} + +.otm-panel-count { + font-size: 11px; + color: var(--text-muted); + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.otm-panel-actions { + display: flex; + flex-shrink: 0; + gap: 2px; +} + +/* ---------------- 文章搜索行 ---------------- */ + +/* 夹在「统计 + 新增」与列表之间,不随列表滚动 */ +.otm-search { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 4px; + padding: 5px calc(var(--otm-pad) + var(--otm-gutter)) 5px var(--otm-pad); + border-bottom: 1px solid var(--background-modifier-border); +} + +.otm-search-input { + flex: 1 1 auto; + min-width: 0; + padding: 3px 6px; + font-size: 12px; + color: var(--text-normal); + background: var(--background-modifier-form-field); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + box-shadow: none; +} + +.otm-search-input:focus { + border-color: var(--interactive-accent); + outline: none; + box-shadow: none; +} + +.otm-search-input::placeholder { + color: var(--text-faint); +} + +.otm-search-clear { + flex: 0 0 auto; + width: 20px; + height: 20px; +} + +.otm-search-clear svg { + width: 12px; + height: 12px; +} + +.otm-search-clear.is-hidden { + display: none; +} + +/* 标题里命中搜索词的那截 */ +.otm-search-hit { + color: var(--text-accent); + background: var(--text-highlight-bg, rgba(255, 208, 0, 0.22)); + border-radius: 2px; +} + +/* ---------------- ID(文章 cid / 评论 coid) ---------------- */ + +.otm-id { + display: inline-flex; + align-items: center; + gap: 3px; + flex: 0 0 auto; + font-family: var(--font-monospace); + font-size: 11px; + line-height: 1.3; + /* 与左侧日期、评论数同一档颜色(--text-muted),不再是更淡的 faint */ + color: var(--text-muted); + cursor: pointer; + user-select: none; +} + +.otm-id:hover { + color: var(--text-accent); + text-decoration: underline; +} + +.otm-post-id.has-separator::before { + content: "·"; + margin-right: 1px; + color: var(--text-faint); +} + +.otm-comment-dot { + flex: 0 0 auto; + color: var(--text-faint); +} + +/* 滚动区:整个侧栏只有这里出现滚动条 */ +.otm-scroll { + flex: 1 1 auto; + min-height: 0; + /* 用 scroll 而不是 auto:滚动条位置恒定占用 8px, + 列表右边界不会因为滚动条出现/消失而跳动,也不用猜平台差异 */ + overflow-y: scroll; + overflow-x: hidden; + scrollbar-gutter: stable; + overscroll-behavior: contain; + padding: 2px 0 6px; +} + +/* 滚动条宽度写死 8px:--otm-gutter 的默认值就是按它算的, + JS 会实测一次,若主题改了这个宽度就同步改 --otm-gutter */ +.otm-scroll::-webkit-scrollbar { + width: 8px; +} + +.otm-scroll::-webkit-scrollbar-track { + background: transparent; +} + +.otm-scroll::-webkit-scrollbar-thumb { + background: var(--background-modifier-border-hover); + border-radius: 4px; +} + +.otm-scroll::-webkit-scrollbar-thumb:hover { + background: var(--text-muted); +} + +/* ---------------- 分页 ---------------- */ + +.otm-panel-footer { + flex: 0 0 auto; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + /* 左右内边距同为 pad,右侧再加滚动条宽度,分页内容在可视区里真居中 */ + padding: 4px calc(var(--otm-pad) + var(--otm-gutter)) 4px var(--otm-pad); + border-top: 1px solid var(--background-modifier-border); +} + +.otm-panel-footer.is-hidden { + display: none; +} + +.otm-pager-info { + font-size: 11px; + color: var(--text-muted); + white-space: nowrap; +} + +/* ---------------- 图标按钮 ---------------- */ + +.otm-icon-button { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: none; + border-radius: 5px; + background: transparent; + color: var(--text-muted); + cursor: pointer; + box-shadow: none; + transition: background-color 0.15s ease, color 0.15s ease; +} + +.otm-icon-button:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} + +.otm-icon-button:disabled { + opacity: 0.35; + cursor: default; + background: transparent; +} + +.otm-icon-button svg { + width: 14px; + height: 14px; +} + +/* ---------------- 列表 ---------------- */ + +.otm-list { + display: flex; + flex-direction: column; +} + +.otm-post-item, +.otm-comment-item { + display: flex; + align-items: flex-start; + gap: 6px; + padding: 7px var(--otm-pad); + border-bottom: 1px solid var(--background-modifier-border); + transition: background-color 0.15s ease; +} + +.otm-post-item:last-child, +.otm-comment-item:last-child { + border-bottom: none; +} + +.otm-post-item:hover, +.otm-comment-item:hover { + background: var(--background-modifier-hover); +} + +.otm-post-main, +.otm-comment-main { + flex: 1; + min-width: 0; +} + +.otm-post-title { + font-size: 13px; + line-height: 1.4; + color: var(--text-normal); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.otm-post-title a { + color: var(--text-normal); + text-decoration: none; +} + +.otm-post-title a:hover { + color: var(--text-accent); +} + +/* 标题下面一行:📅 日期 · 💬 评论数(两段都带图标,尺寸统一) */ +.otm-post-meta { + display: flex; + align-items: center; + gap: 6px; + margin-top: 2px; + min-width: 0; +} + +.otm-post-date { + display: inline-flex; + align-items: center; + gap: 3px; + flex: 0 0 auto; + font-size: 11px; + line-height: 1.3; + color: var(--text-muted); + white-space: nowrap; +} + +/* 评论数:后端只在 commentsNum > 0 时才有这个节点,这里只管排版 */ +.otm-post-comments { + display: inline-flex; + align-items: center; + gap: 3px; + flex: 0 0 auto; + font-size: 11px; + line-height: 1.3; + color: var(--text-muted); +} + +.otm-post-comments.has-separator::before { + content: "·"; + margin-right: 1px; + color: var(--text-faint); +} + +/* 日期与评论数前面的图标 + 文字是 11px,但数字的实际墨迹只有 8px 高; + 图标若给 11px,日历形状在 24 格里占 20 格(墨迹 9.2px),会比文字高出一截。 + 这里统一按 10px 画(墨迹 7.5~8.3px),与文字视觉等高。 */ +.otm-post-meta .otm-post-meta-icon { + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + line-height: 0; +} + +.otm-post-meta .otm-post-meta-icon svg { + display: block; + width: 10px; + height: 10px; + stroke-width: 2; +} + +.otm-item-actions, +.otm-comment-actions { + display: flex; + flex-shrink: 0; + gap: 2px; +} + +.otm-meta-item { + display: flex; + align-items: center; + gap: 6px; + padding: 5px var(--otm-pad); + font-size: 13px; + cursor: pointer; + transition: background-color 0.15s ease; +} + +.otm-meta-item:hover { + background: var(--background-modifier-hover); +} + +.otm-meta-name { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + gap: 6px; + color: var(--text-normal); + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +/* 小徽章(分类/标签后的文章数、待审核标记) */ +.otm-badge { + flex-shrink: 0; + padding: 0 6px; + font-size: 10px; + font-weight: 600; + line-height: 16px; + color: var(--text-muted); + background: var(--background-modifier-hover); + border-radius: 999px; +} + +/* 待审核标记:和顶部徽章同一套颜色变量(深色值在上面的 body.theme-dark 里) */ +.otm-badge-waiting { + --otm-danger-fg: #b42318; + --otm-danger-bg: rgba(217, 45, 32, 0.1); + color: var(--otm-danger-fg); + background: var(--otm-danger-bg); +} + +/* ---------------- 评论筛选子 tab ---------------- */ + +/* 一行:左边三个筛选项,最右侧是当前筛选的统计 */ +.otm-tabs { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 8px; + padding: 6px calc(var(--otm-pad) + var(--otm-gutter)) 6px var(--otm-pad); + border-bottom: 1px solid var(--background-modifier-border); +} + +.otm-tabs-list { + flex: 1 1 auto; + min-width: 0; + display: flex; + align-items: center; + gap: 4px; + overflow: hidden; +} + +.otm-tabs-count { + flex: 0 0 auto; + font-size: 11px; + color: var(--text-muted); + white-space: nowrap; +} + +.otm-tab { + flex: 0 0 auto; + padding: 3px 10px; + font-size: 12px; + color: var(--text-muted); + border-radius: 999px; + white-space: nowrap; + cursor: pointer; + user-select: none; + transition: background-color 0.15s ease, color 0.15s ease; +} + +.otm-tab:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} + +.otm-tab.is-active { + background: var(--background-modifier-hover); + color: var(--text-accent); + font-weight: 600; +} + +.otm-comment-text { + font-size: 12px; + line-height: 1.45; + color: var(--text-normal); + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; + word-break: break-word; +} + +/* 第二行:评论人 · 时间 · ID */ +.otm-comment-meta { + display: flex; + align-items: center; + gap: 4px; + margin-top: 3px; + font-size: 11px; + color: var(--text-muted); + overflow: hidden; + white-space: nowrap; +} + +.otm-comment-author { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + color: var(--text-muted); +} + +.otm-comment-time { + flex: 0 0 auto; +} + +.otm-comment-meta .otm-badge { + flex: 0 0 auto; + margin-left: 6px; + vertical-align: middle; +} + +/* 第三行:所属文章标题,单独占一行,长了就省略 */ +.otm-comment-post { + margin-top: 3px; + font-size: 11px; + line-height: 1.3; + color: var(--text-faint); +} + +/* 省略号放在标题元素自己身上(父级不再 overflow:hidden), + 否则链接的下划线/装饰线会被父级裁掉 */ +.otm-comment-post-title { + display: block; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + color: inherit; +} + +/* 能跳转时:不加任何下划线,平时与整行同色, + 只用鼠标指针 + 悬停变色提示可点,避免每条评论都挂一条链接显得吵 */ +.otm-comment-post-title.is-link { + cursor: pointer; + text-decoration: none; +} + +.otm-comment-post-title.is-link:hover, +.otm-comment-post-title.is-link:focus-visible { + color: var(--text-accent); + text-decoration: none; +} + +.otm-comment-actions .mod-warning:hover { + color: var(--text-error); +} + +/* ---------------- 空态 / 加载 / 弹窗 ---------------- */ + +.otm-empty, +.otm-loading { + padding: 24px 8px; + font-size: 12px; + color: var(--text-muted); + text-align: center; +} + +.otm-textarea { + width: 100%; + min-height: 120px; + resize: vertical; +} + +.otm-modal-actions { + display: flex; + justify-content: flex-end; + gap: 8px; + margin-top: 12px; +} diff --git a/utils/datetime.ts b/utils/datetime.ts new file mode 100644 index 0000000..142ebeb --- /dev/null +++ b/utils/datetime.ts @@ -0,0 +1,41 @@ +/** + * 时间格式化 + * + * 以前属性里写的是 `new Date().toISOString()`,也就是 + * `2026-11-11T06:09:43.465Z` 这种 UTC 串:中国香港 / 北京都在东八区, + * 本地时间其实是 14:09,看属性面板会以为时间差了 8 小时。 + * + * 这里固定按 UTC+8 换算,不依赖本机时区——换一台时区不同的电脑、 + * 或者在服务器上跑,输出都还是北京时间。 + */ +const BEIJING_OFFSET_MS = 8 * 60 * 60 * 1000; + +/** + * 把时间转成北京时间的 `YYYY-MM-DD HH:mm:ss` + * + * @param input Date / 时间戳 / 可解析的时间字符串,默认当前时刻 + */ +export function formatBeijingTime( + input: Date | number | string = new Date() +): string { + const date = input instanceof Date ? input : new Date(input); + if (Number.isNaN(date.getTime())) return ""; + + // 先整体加 8 小时,再用 getUTC* 取值,得到的偏移量只由常量决定 + const shifted = new Date(date.getTime() + BEIJING_OFFSET_MS); + const pad = (value: number) => String(value).padStart(2, "0"); + + const ymd = [ + shifted.getUTCFullYear(), + pad(shifted.getUTCMonth() + 1), + pad(shifted.getUTCDate()), + ].join("-"); + + const hms = [ + pad(shifted.getUTCHours()), + pad(shifted.getUTCMinutes()), + pad(shifted.getUTCSeconds()), + ].join(":"); + + return `${ymd} ${hms}`; +} diff --git a/utils/frontmatter.ts b/utils/frontmatter.ts new file mode 100644 index 0000000..dd05b9c --- /dev/null +++ b/utils/frontmatter.ts @@ -0,0 +1,366 @@ +import { App, TFile } from "obsidian"; +import { formatBeijingTime } from "./datetime"; + +/** + * 笔记属性里使用的字段名。 + * + * 旧版本把元数据写成嵌套的 `typecho:` 对象,Obsidian 属性面板里会折叠成一行, + * 看不出具体内容。现在改为平铺的独立属性,逐条展开显示。 + * + * 统一加 `ty-` 短前缀:既比 `typecho-` 简洁,又能和笔记自己的 + * `tags` / `categories` / `updated` 等同名属性区分开,不会互相覆盖。 + */ +export const FM_KEYS = { + cid: "ty-cid", + slug: "ty-slug", + url: "ty-url", + categories: "ty-categories", + tags: "ty-tags", + title: "ty-title", + created: "ty-created", + updated: "ty-updated", +}; + +/** + * 更早几版用过的键名 → 当前字段,只用于读取兼容和写入时清理, + * 保证老笔记下次发布会自动迁移成新键名。 + */ +const LEGACY_FLAT_KEYS: Record = { + "typecho-cid": "cid", + "typecho-slug": "slug", + "typecho-url": "url", + "typecho-categories": "categories", + "typecho-tags": "tags", + "typecho-original-title": "original-title", + "typecho-updated": "updated", + "ty-original-title": "original-title", +}; + +/** + * 已废弃的键,读取时不认、写入时直接清掉。 + * `ty-site` 和 `ty-url` 内容重复(都是站点 API / 文章地址),已弃用。 + */ +const OBSOLETE_KEYS = ["ty-site"]; + +/** + * 中间一版用过的无前缀键名。只做读取兜底,写入时也会清理, + * 因为这些是插件自己写坏的残留,不清掉属性面板会出现两套。 + */ +const PLAIN_KEYS = [ + "cid", + "slug", + "url", + "categories", + "tags", + "original-title", + "updated", +]; + +export interface TypechoMeta { + cid: number | null; + slug: string | null; + url: string | null; + categories: string[]; + tags: string[]; + title: string | null; + created: string | null; + updated: string | null; +} + +export function emptyMeta(): TypechoMeta { + return { + cid: null, + slug: null, + url: null, + categories: [], + tags: [], + title: null, + created: null, + updated: null, + }; +} + +function toCid(value: unknown): number | null { + const n = typeof value === "number" ? value : parseInt(String(value ?? ""), 10); + return Number.isFinite(n) && n > 0 ? n : null; +} + +function toText(value: unknown): string | null { + if (value === null || value === undefined) return null; + const s = String(value).trim(); + return s === "" ? null : s; +} + +function toList(value: unknown): string[] { + if (Array.isArray(value)) { + return value.map((v) => String(v).trim()).filter((v) => v !== ""); + } + const s = toText(value); + if (!s) return []; + return s + .split(/[,,]/) + .map((v) => v.trim()) + .filter((v) => v !== ""); +} + +/** + * 把任意来源的字段表转成 TypechoMeta(统一兼容几代旧写法)。 + */ +function metaFromFields(fm: any): TypechoMeta { + const meta = emptyMeta(); + if (!fm) return meta; + + // 最早:typecho: { cid, slug, ... } 嵌套写法 + const legacy: any = + fm.typecho && typeof fm.typecho === "object" ? fm.typecho : {}; + + // 带前缀的平铺写法(typecho-* 与 ty-original-title) + const legacyFlat: any = {}; + for (const [key, field] of Object.entries(LEGACY_FLAT_KEYS)) { + if (fm[key] !== undefined) legacyFlat[field] = fm[key]; + } + + // 无前缀的平铺写法 + const plain: any = {}; + for (const key of PLAIN_KEYS) { + if (fm[key] !== undefined) plain[key] = fm[key]; + } + + meta.cid = toCid(fm[FM_KEYS.cid] ?? plain.cid ?? legacyFlat.cid ?? legacy.cid); + meta.slug = toText( + fm[FM_KEYS.slug] ?? plain.slug ?? legacyFlat.slug ?? legacy.slug + ); + meta.url = toText(fm[FM_KEYS.url] ?? plain.url ?? legacyFlat.url ?? legacy.url); + meta.categories = toList( + fm[FM_KEYS.categories] ?? + plain.categories ?? + legacyFlat.categories ?? + legacy.categories + ); + meta.tags = toList( + fm[FM_KEYS.tags] ?? plain.tags ?? legacyFlat.tags ?? legacy.tags + ); + meta.title = toText( + fm[FM_KEYS.title] ?? + plain["original-title"] ?? + legacyFlat["original-title"] ?? + legacy.original_title ?? + fm.original_title + ); + meta.created = toText(fm[FM_KEYS.created]); + meta.updated = toText( + fm[FM_KEYS.updated] ?? + plain.updated ?? + legacyFlat.updated ?? + legacy.updated + ); + + return meta; +} + +/** + * 读取笔记里的 Typecho 元数据,同时兼容几代旧写法。 + */ +export function readTypechoMeta(app: App, filePath: string): TypechoMeta { + if (!filePath) return emptyMeta(); + const file = app.vault.getFileByPath(filePath); + if (!file) return emptyMeta(); + return metaFromFields(app.metadataCache.getFileCache(file)?.frontmatter); +} + +/** 去掉 YAML 标量两端多余引号 */ +function unquote(value: string): string { + const s = value.trim(); + if (/^".*"$/.test(s) || /^'.*'$/.test(s)) return s.slice(1, -1); + return s; +} + +/** 解析 `[a, b, "c"]` 形式的 flow 数组;不是数组则返回 null */ +function parseFlowList(value: string): string[] | null { + const s = value.trim(); + if (!s.startsWith("[") || !s.endsWith("]")) return null; + return s + .slice(1, -1) + .split(",") + .map((part) => unquote(part)) + .filter((part) => part !== ""); +} + +/** + * 直接从笔记文本解析顶层 frontmatter 字段。 + * + * 不依赖 metadataCache——发布回写后 metadataCache 可能还是旧值, + * 导致「属性面板明明有 ty-categories / ty-tags,发布框却读不到」。 + * 只解析插件自己写的平铺键(含 flow 数组和块状数组),够用且不会误伤正文。 + */ +export function parseFrontmatterFields(content: string): Record { + const fields: Record = {}; + const match = content.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/); + if (!match) return fields; + + const lines = match[1].split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + // 顶层键(无缩进);缩进行只作为上一个键的块状数组元素处理 + const head = line.match(/^([A-Za-z][\w-]*):[ \t]*(.*)$/); + if (!head) continue; + const key = head[1]; + const raw = head[2].trim(); + if (raw !== "") { + const list = parseFlowList(raw); + fields[key] = list === null ? unquote(raw) : list; + continue; + } + // 块状数组:`key:\n - item` + const items: string[] = []; + while (i + 1 < lines.length) { + const item = lines[i + 1].match(/^[ \t]+-[ \t]?(.*)$/); + if (!item) break; + i++; + const value = unquote(item[1]); + if (value !== "") items.push(value); + } + fields[key] = items; + } + return fields; +} + +/** + * 读元数据的最新版本:先读文件文本(权威),再与 metadataCache 结果合并, + * 兼容旧笔记里 metadataCache 才有、文本解析不覆盖的嵌套写法。 + */ +export async function readTypechoMetaFresh( + app: App, + filePath: string +): Promise { + const cached = readTypechoMeta(app, filePath); + const file = app.vault.getFileByPath(filePath); + if (!file) return cached; + try { + // 必须用 read() 直接读磁盘,不能用 cachedRead(): + // 发布回写 frontmatter 后 vault 的内容缓存可能还是旧值,cachedRead + // 会拿到还没有 ty-categories/ty-tags 的旧文本,导致回填时属性为空。 + // 这正是「slug 有(走 slugMapping 兜底)、分类标签却勾不上」的根因之一。 + const fields = parseFrontmatterFields(await app.vault.read(file)); + const fresh = metaFromFields(fields); + const merged = emptyMeta(); + merged.cid = fresh.cid ?? cached.cid; + merged.slug = fresh.slug ?? cached.slug; + merged.url = fresh.url ?? cached.url; + merged.categories = fresh.categories.length ? fresh.categories : cached.categories; + merged.tags = fresh.tags.length ? fresh.tags : cached.tags; + merged.title = fresh.title ?? cached.title; + merged.created = fresh.created ?? cached.created; + merged.updated = fresh.updated ?? cached.updated; + return merged; + } catch (error) { + console.error("read fresh frontmatter failed:", error); + return cached; + } +} + +export interface TypechoMetaWrite { + cid: number; + slug?: string | null; + url?: string | null; + categories?: string[]; + tags?: string[]; + title?: string | null; + created?: string | null; +} + +/** flow 数组里需要加引号的字符(YAML 特殊符号或会破坏方括号结构) */ +const NEEDS_QUOTE = /[,[\]{}:#&*!|>'"%@`]|^\s|\s$/; + +/** 把单个值转成 YAML flow 数组里的安全标量 */ +function yamlScalar(raw: string): string { + const v = raw.trim(); + if (v === "") return '""'; + if (/^".*"$/.test(v) || /^'.*'$/.test(v)) return v; + if (NEEDS_QUOTE.test(v)) return JSON.stringify(v); + return v; +} + +/** + * 把指定字段的块状数组压成单行 flow 写法: + * + * ty-categories: → ty-categories: [插件, 随笔] + * - 插件 + * - 随笔 + * + * processFrontMatter 内部固定用块状风格序列化,没有开关可调, + * 所以写完之后只针对这两个字段做一次文本级压缩,其余属性一字不动。 + */ +export function compactArrayFields(content: string): string { + const keys = [FM_KEYS.categories, FM_KEYS.tags].map((k) => + k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ); + const re = new RegExp( + `^(${keys.join("|")}):[ \\t]*\\r?\\n((?:[ \\t]*-[ \\t]?[^\\r\\n]*\\r?\\n?)+)`, + "gm" + ); + + return content.replace(re, (_match, key: string, block: string) => { + const items = block + .split(/\r?\n/) + .map((line) => line.replace(/^[ \t]*-[ \t]?/, "").trim()) + .filter((line) => line !== ""); + if (items.length === 0) return `${key}: []\n`; + return `${key}: [${items.map(yamlScalar).join(", ")}]\n`; + }); +} + +/** + * 把发布结果写回笔记属性(平铺,方便在属性面板逐条查看)。 + * + * 使用 Obsidian 官方的 processFrontMatter,避免手写 YAML 时把用户 + * 自己的其他属性(数组、嵌套对象)解析坏掉。 + */ +export async function writeTypechoMeta( + app: App, + file: TFile, + data: TypechoMetaWrite +): Promise { + await app.fileManager.processFrontMatter(file, (fm: any) => { + // 迁移旧写法:删掉空壳 `typecho:`、各代旧键、废弃键, + // 避免属性面板里出现两套重复属性 + if (fm.typecho !== undefined) delete fm.typecho; + for (const key of Object.keys(LEGACY_FLAT_KEYS)) delete fm[key]; + for (const key of OBSOLETE_KEYS) delete fm[key]; + for (const key of PLAIN_KEYS) delete fm[key]; + + fm[FM_KEYS.cid] = Number(data.cid); + + const apply = (key: string, value: any) => { + const isEmpty = + value === null || + value === undefined || + value === "" || + (Array.isArray(value) && value.length === 0); + if (isEmpty) { + delete fm[key]; + } else { + fm[key] = value; + } + }; + + apply(FM_KEYS.slug, data.slug); + apply(FM_KEYS.url, data.url); + apply(FM_KEYS.categories, data.categories); + apply(FM_KEYS.tags, data.tags); + apply(FM_KEYS.title, data.title); + + // 发布时间要排在更新时间上面。已有属性直接改值是改不动顺序的, + // js-yaml 会把新加的 key 追加到末尾,所以先删后按顺序重写。 + const previousCreated = toText(fm[FM_KEYS.created]); + delete fm[FM_KEYS.created]; + delete fm[FM_KEYS.updated]; + + const created = toText(data.created) || previousCreated; + if (created) fm[FM_KEYS.created] = created; + fm[FM_KEYS.updated] = formatBeijingTime(); + }); + + // 分类、标签压成单行,方便一眼看完 + await app.vault.process(file, (content) => compactArrayFields(content)); +} diff --git a/utils/i18n.ts b/utils/i18n.ts new file mode 100644 index 0000000..2426f2b --- /dev/null +++ b/utils/i18n.ts @@ -0,0 +1,21 @@ +import i18next from "i18next"; +import { getLanguage } from "obsidian"; + +const resources = { + en: { translation: require("../locales/en.json") }, + zh: { translation: require("../locales/zh.json") }, +}; + +i18next.init({ + lng: getLanguage(), + fallbackLng: "en", + resources, + interpolation: { + escapeValue: false, + prefix: "{", + suffix: "}", + }, + keySeparator: "." +}); + +export default i18next; diff --git a/utils/post_import.ts b/utils/post_import.ts new file mode 100644 index 0000000..36a8eaf --- /dev/null +++ b/utils/post_import.ts @@ -0,0 +1,247 @@ +import { App, Notice, TFile, normalizePath } from "obsidian"; +import { HttpUtils } from "./request"; +import { getActiveSite, getSettings } from "../main"; +import i18n from "./i18n"; +import { FM_KEYS } from "./frontmatter"; +import { formatBeijingTime } from "./datetime"; + +/** 文件名里不允许出现的字符 */ +const INVALID_FILE_CHARS = /[\\/:*?"<>|#^[\]]/g; + +/** + * 把标题转成合法的文件名 + */ +export function sanitizeFileName(name: string): string { + const cleaned = (name || "") + .replace(INVALID_FILE_CHARS, "-") + .replace(/\s+/g, " ") + .trim() + .slice(0, 100); + return cleaned || "untitled"; +} + +/** + * 目录名净化:和文件名同一套规则,另外去掉首尾的点和空格 + */ +function sanitizeFolderName(name: string): string { + return (name || "") + .replace(INVALID_FILE_CHARS, "-") + .replace(/\s+/g, " ") + .replace(/^[.\s]+|[.\s]+$/g, "") + .trim() + .slice(0, 60); +} + +/** + * 本次下载 / 新建使用的基础目录:站点自己配置的导入目录 + * + * 站点没单独配置时回退到旧版全局目录,再回退到 Typecho。 + */ +export function resolveImportFolder( + site: { importFolder?: string } | undefined = getActiveSite(), + categorySegment?: string +): string { + const base = (site?.importFolder || getSettings()?.importFolder || "Typecho") + .replace(/\\/g, "/") + .replace(/^\/+|\/+$/g, ""); + + const sub = sanitizeFolderName(categorySegment || ""); + return [base, sub].filter(Boolean).join("/"); +} + +/** + * 文章在本地所属的分类目录名 + * + * 取文章的分类 slug;一篇文章挂多个分类时固定取 mid 最小的那个, + * 保证同一个分类的文章每次都落在同一个目录,不会因为接口返回顺序变化而漂移。 + * 没有分类(或分类没有 slug)时退回分类名,两者都没有就落在站点目录根下。 + */ +export function categoryFolderOf(post: any): string { + const categories: any[] = Array.isArray(post?.categories) + ? [...post.categories] + : Array.isArray(post?.categorySlugs) + ? post.categorySlugs.map((slug: string) => ({ slug })) + : []; + + categories.sort( + (a, b) => Number(a?.mid ?? 0) - Number(b?.mid ?? 0) + ); + + const first = categories[0]; + const raw = first?.slug + ? String(first.slug) + : first?.name + ? String(first.name) + : String(post?.categoryNames?.[0] ?? ""); + + return sanitizeFolderName(raw); +} + +/** + * YAML 标量:遇到容易歧义的字符就加双引号 + */ +function yamlScalar(value: string): string { + if (value === "") return '""'; + if ( + /[:#\[\]{}&*!|>'"%@`,]/.test(value) || + /^\s|\s$/.test(value) || + /^(true|false|null|~)$/i.test(value) || + /^-?\d+(\.\d+)?$/.test(value) + ) { + return JSON.stringify(value); + } + return value; +} + +/** + * 行内数组,和插件发布时写回的风格保持一致 + */ +function yamlList(values: string[]): string { + if (!values || values.length === 0) return "[]"; + return `[${values.map((v) => yamlScalar(String(v))).join(", ")}]`; +} + +/** + * 逐级创建目录 + */ +async function ensureFolder(app: App, folder: string): Promise { + if (!folder) return; + const parts = folder.split("/"); + let current = ""; + for (const part of parts) { + current = current ? `${current}/${part}` : part; + if (!app.vault.getAbstractFileByPath(current)) { + try { + await app.vault.createFolder(current); + } catch (error) { + // 并发创建时可能已存在,忽略 + } + } + } +} + +/** + * 组装本地笔记内容:属性 + 正文 + */ +function buildContent(post: any, title: string): string { + const lines: string[] = ["---"]; + lines.push(`title: ${yamlScalar(title)}`); + lines.push(`${FM_KEYS.cid}: ${Number(post.cid)}`); + if (post.slug) { + lines.push(`${FM_KEYS.slug}: ${yamlScalar(String(post.slug))}`); + } + lines.push(`${FM_KEYS.title}: ${yamlScalar(title)}`); + lines.push(`${FM_KEYS.categories}: ${yamlList(post.categoryNames || [])}`); + lines.push(`${FM_KEYS.tags}: ${yamlList(post.tagNames || [])}`); + if (post.permalink) { + lines.push(`${FM_KEYS.url}: ${yamlScalar(String(post.permalink))}`); + } + + // 发布时间取接口给的 created(Unix 秒),排在更新时间上面; + // 老文章没有这个字段时就只写更新时间 + const created = Number(post.created); + if (Number.isFinite(created) && created > 0) { + lines.push( + `${FM_KEYS.created}: ${formatBeijingTime(created * 1000)}` + ); + } + + lines.push(`${FM_KEYS.updated}: ${formatBeijingTime()}`); + lines.push("---"); + lines.push(""); + + const body = post.markdown ?? post.text ?? ""; + lines.push(String(body)); + + return lines.join("\n"); +} + +/** + * 新建一篇空笔记并打开,用于在本地起草新文章 + * + * 草稿还没有分类,先落在站点导入目录的根下; + * 发布时选了分类,正文和属性写回线上即可。 + * 同名文件已存在时自动追加序号,不会覆盖。 + */ +export async function createPostDraft(app: App): Promise { + const rawFolder = resolveImportFolder(); + + try { + await ensureFolder(app, rawFolder); + + const baseName = i18n.t("manager.draftName"); + let path = ""; + let index = 0; + + do { + const fileName = + index === 0 ? `${baseName}.md` : `${baseName} ${index}.md`; + path = normalizePath( + rawFolder ? `${rawFolder}/${fileName}` : fileName + ); + index++; + } while (app.vault.getAbstractFileByPath(path) && index < 1000); + + const file = await app.vault.create(path, ""); + await app.workspace.getLeaf(true).openFile(file); + new Notice(i18n.t("manager.draftCreated", { name: file.path })); + + return file; + } catch (error) { + console.error("新建笔记失败", error); + // 失败原因多半是目录无写权限或路径非法,把真实原因带出来才查得动 + const detail = (error as any)?.message; + new Notice( + detail + ? `${i18n.t("common.errorOccurred")}:${detail}` + : i18n.t("common.errorOccurred") + ); + return null; + } +} + +/** + * 把线上文章下载成本地 Markdown 并打开编辑 + * + * 存放位置:<站点导入目录>/<分类 slug>/<文章标题>.md + * 没有分类的文章直接放在 <站点导入目录> 下。 + * 同目录下已有同名笔记时不会覆盖,直接打开已有文件。 + */ +export async function importPostAsMarkdown( + app: App, + cid: number +): Promise { + if (!cid || Number.isNaN(cid)) { + new Notice(i18n.t("error.failedToFetchPostDetails")); + return null; + } + + const response = await HttpUtils.get(`/postDetail?cid=${cid}`); + const post = response?.data; + if (!post) { + new Notice(i18n.t("error.failedToFetchPostDetails")); + return null; + } + + const title = String(post.title || i18n.t("manager.untitled")); + // 分类 slug 作为二级目录,和线上分类结构对齐 + const rawFolder = resolveImportFolder(undefined, categoryFolderOf(post)); + + await ensureFolder(app, rawFolder); + + const fileName = `${sanitizeFileName(title)}.md`; + const path = normalizePath(rawFolder ? `${rawFolder}/${fileName}` : fileName); + + const existing = app.vault.getAbstractFileByPath(path); + if (existing instanceof TFile) { + new Notice(i18n.t("manager.alreadyExists", { name: existing.path })); + await app.workspace.getLeaf(true).openFile(existing); + return existing; + } + + const file = await app.vault.create(path, buildContent(post, title)); + await app.workspace.getLeaf(true).openFile(file); + new Notice(i18n.t("manager.imported", { name: file.path })); + + return file; +} diff --git a/utils/request.ts b/utils/request.ts new file mode 100644 index 0000000..d55e0bf --- /dev/null +++ b/utils/request.ts @@ -0,0 +1,223 @@ +import { requestUrl, RequestUrlResponse, Notice } from "obsidian"; +import { getSettings, getActiveSite, getSites } from "../main"; +import { ResponseType } from "./response_type"; + +export class HttpUtils { + // 动态配置(优先使用) + private static currentHost: string = ""; + private static currentToken: string = ""; + + // 设置当前使用的网站(切换时调用) + public static setCurrentSite(host: string, token: string) { + this.currentHost = host; + this.currentToken = token; + } + + // 获取当前有效的 Host(公开方法,供外部使用) + public static getCurrentHost(): string { + if (this.currentHost) return this.currentHost; + const activeSite = getActiveSite(); + if (activeSite?.Host) return activeSite.Host; + // 降级:从第一个网站获取 + const sites = getSites(); + return sites[0]?.Host || ""; + } + + // 获取当前有效的 Token(公开方法,供外部使用) + public static getCurrentToken(): string { + if (this.currentToken) return this.currentToken; + const activeSite = getActiveSite(); + if (activeSite?.Token) return activeSite.Token; + // 降级:从第一个网站获取 + const sites = getSites(); + return sites[0]?.Token || ""; + } + + // 获取当前激活网站的用户UID + public static getCurrentUserUid(): string { + const activeSite = getActiveSite(); + if (activeSite?.User?.uid) return activeSite.User.uid; + // 降级:从第一个网站获取 + const sites = getSites(); + return sites[0]?.User?.uid || ""; + } + + private static getHeaders() { + return { + "Content-Type": "application/json", + token: this.getCurrentToken(), + Origin: this.getCurrentHost(), + }; + } + + private static getHost() { + return this.getCurrentHost(); + } + + /** + * 发起 GET 请求 + * + * @param silent 为 true 时失败不弹提示,用于可有可无的辅助查询 + */ + public static async get( + url: string, + headers?: Record, + silent = false + ): Promise { + return this.request("GET", url, undefined, headers, silent); + } + + /** + * 发起 POST 请求 + */ + public static async post( + url: string, + body: any, + headers?: Record + ): Promise { + return this.request("POST", url, body, headers); + } + + /** + * 发起通用 HTTP 请求 + */ + private static async request( + method: string, + url: string, + body?: any, + headers?: Record, + silent = false + ): Promise { + headers = { + ...this.getHeaders(), + ...headers, + }; + + const shouldHaveBody = !["GET", "HEAD", "DELETE"].includes( + method.toUpperCase() + ); + const requestOptions = { + method: method, + url: this.getHost() + url, + headers: headers || {}, + }; + + // 只有需要时才添加 body + if (shouldHaveBody && body !== undefined && body !== null) { + (requestOptions as any).body = + typeof body === "string" ? body : JSON.stringify(body); + if (!headers?.["Content-Type"]) { + requestOptions.headers = { + ...requestOptions.headers, + "Content-Type": "application/json", + }; + } + } + + try { + const response: RequestUrlResponse = await requestUrl( + requestOptions + ); + + // 正常接口一定回 JSON。返回 HTML 一般是 URL 落到了主题页或错误页 + // (插件没启用、新接口没注册、Host 没填到 /index.php/api), + // 直接把 "
" 丢给 JSON.parse 只会得到看不懂的语法错误
+			if (!this.looksLikeJson(response)) {
+				throw new Error(this.describeNonJson(response, url));
+			}
+
+			const res: ResponseType = response.json;
+			if (res.status === "success") {
+				return res;
+			} else {
+				if (!silent) new Notice(res.message);
+				// 标记「提示已经弹过」:本方法末尾的 catch 与调用方都不再重复弹,
+				// 否则一次失败会连出两三条提示,用户根本看不清哪句是真的原因
+				const apiError: any = new Error(
+					`HTTP Error: - ${response.json.message}`
+				);
+				apiError.__notified = !silent;
+				throw apiError;
+			}
+		} catch (error) {
+			console.error(`Request failed: ${url}`, error);
+			if (!silent && !(error as any)?.__notified) {
+				new Notice(this.messageOf(error, url));
+				if (error && typeof error === "object") {
+					(error as any).__notified = true;
+				}
+			}
+			throw error;
+		}
+	}
+
+	/**
+	 * 统一错误提示
+	 *
+	 * request() 失败时已经弹过最具体的那条原因(HTTP 状态 + 服务器原文),
+	 * 并在错误对象上打了 __notified 标记。调用方用它兜底,就不会出现
+	 * 「真实原因」和「请求失败」两条提示互相覆盖的情况。
+	 *
+	 * @param fallback 拿不到有效信息时退而显示的文案(一般是「XX 失败」)
+	 */
+	public static notifyError(error: any, fallback = "") {
+		if (error && typeof error === "object" && (error as any).__notified) {
+			return;
+		}
+
+		const detail = this.messageOf(error);
+		const message = detail && detail !== "undefined" ? detail : fallback;
+		if (message) new Notice(message);
+		if (error && typeof error === "object") {
+			(error as any).__notified = true;
+		}
+	}
+
+	private static looksLikeJson(response: RequestUrlResponse): boolean {
+		const contentType = String(
+			response.headers?.["content-type"] || ""
+		).toLowerCase();
+		if (contentType.includes("json")) return true;
+
+		const body = String(response.text || "").trimStart();
+		return body.startsWith("{") || body.startsWith("[");
+	}
+
+	/** 把 HTML 错误页压成一句话,方便直接弹给用户看 */
+	private static describeNonJson(
+		response: { status?: number; text?: string },
+		path?: string
+	): string {
+		const raw = String(response.text || "");
+		const shortPath = path ? path.split("?")[0] : "";
+
+		// Typecho 路由没注册时会直接抛出这一行,是最常见的「接口不存在」
+		if (/Path\s+'[^']*'\s+not found/i.test(raw)) {
+			return `该网站没有这个接口${
+				shortPath ? `(${shortPath})` : ""
+			}:服务器上的 TypechoToObsidian 插件是旧版本。把最新的 Action.php、Plugin.php 上传到 usr/plugins/TypechoToObsidian/ 后,在后台停用再启用插件即可`;
+		}
+
+		const snippet = raw
+			.replace(//gi, " ")
+			.replace(//gi, " ")
+			.replace(/<[^>]+>/g, " ")
+			.replace(/\s+/g, " ")
+			.trim()
+			.slice(0, 100);
+
+		const status = response.status ? `HTTP ${response.status}` : "非 JSON";
+		return `服务器返回的不是 JSON(${status})${
+			snippet ? ":" + snippet : ""
+		}。请确认 Host 填到了 /index.php/api,且 Typecho 端插件已重新启用`;
+	}
+
+	private static messageOf(error: any, path?: string): string {
+		if (typeof error === "string") return error;
+		// requestUrl 遇到 4xx/5xx 会抛出带回包的对象,HTML 错误页也走这里
+		if (error?.status && error?.text) {
+			return this.describeNonJson(error, path);
+		}
+		return String(error?.message ?? error);
+	}
+}
diff --git a/utils/response_type.ts b/utils/response_type.ts
new file mode 100644
index 0000000..84a827c
--- /dev/null
+++ b/utils/response_type.ts
@@ -0,0 +1,5 @@
+export interface ResponseType {
+	status: string;
+	message: string;
+	data: any;
+}
diff --git a/utils/util.ts b/utils/util.ts
new file mode 100644
index 0000000..149b21d
--- /dev/null
+++ b/utils/util.ts
@@ -0,0 +1,276 @@
+import { getSettings } from "main";
+import { Notice, Editor, TFolder, App } from "obsidian";
+import { HttpUtils } from "./request";
+import i18n from "./i18n";
+
+// 定义树节点接口
+export interface TreeNode {
+	id?: number;
+	[key: string]: any;
+	children: TreeNode[];
+	parent?: TreeNode;
+}
+
+export const Util = {
+	// tree
+	treeUtil: {
+		generateTreeData: function >(
+			data: T[],
+			nodeId: keyof T,
+			parentNodeKey: keyof T
+		): TreeNode[] {
+			// 将数据存储为以 nodeId 为 KEY 的 map 索引数据列
+			const map: Record = {};
+			data.forEach((item) => {
+				(item as unknown as TreeNode).children = [];
+				map[item[nodeId] as string | number] =
+					item as unknown as TreeNode;
+			});
+
+			// 遍历数据,构建树形结构
+			const rootNodes: TreeNode[] = [];
+			data.forEach((item) => {
+				const parent = map[item[parentNodeKey] as string | number];
+				if (parent) {
+					parent.children.push(item as unknown as TreeNode);
+					(item as unknown as TreeNode).parent = parent;
+				} else {
+					rootNodes.push(item as unknown as TreeNode);
+				}
+			});
+
+			return rootNodes;
+		},
+		// 在树形结构中查找指定id节点
+		findNodeInTree: function (
+			tree: TreeNode[],
+			id: number
+		): TreeNode | undefined {
+			for (let i = 0; i < tree.length; i++) {
+				if (tree[i].id === id) {
+					return tree[i];
+				} else {
+					if (tree[i].children) {
+						const node = this.findNodeInTree(tree[i].children, id);
+						if (node) {
+							return node;
+						}
+					}
+				}
+			}
+			return undefined;
+		},
+		// 在树形结构中查找指定id节点的上一个父节点
+		findParentNodeInTree: function (
+			tree: TreeNode[],
+			id: number
+		): TreeNode | null {
+			// Id等于0的节点为根节点,没有父节点
+			// id找到了的话,往上找一层父节点返回
+			if (id === 0) {
+				return null;
+			}
+			for (let i = 0; i < tree.length; i++) {
+				if (tree[i].id === id) {
+					return tree[i].parent || null;
+				} else {
+					if (tree[i].children) {
+						const node = this.findParentNodeInTree(
+							tree[i].children,
+							id
+						);
+						if (node) {
+							return node;
+						}
+					}
+				}
+			}
+			return null;
+		},
+	},
+	hash: {
+		simpleHash(str: string) {
+			let hash = 0;
+			for (let i = 0; i < str.length; i++) {
+				const char = str.charCodeAt(i);
+				hash = (hash << 5) - hash + char;
+				hash |= 0; // Convert to 32bit integer
+			}
+			// 转成16进制并取最后6位
+			return (hash >>> 0).toString(16).padStart(8, "0").slice(-6);
+		},
+	},
+	file: {
+		// 将file转换成Uint8Array
+		async fileToUint8Array(file: File | Blob) {
+			return new Promise((resolve, reject) => {
+				const reader = new FileReader();
+				reader.onload = () => {
+					const arrayBuffer = reader.result as ArrayBuffer;
+					resolve(new Uint8Array(arrayBuffer));
+				};
+				reader.onerror = reject;
+				reader.readAsArrayBuffer(file);
+			});
+		},
+	},
+	url: {
+		extractDomain(url: string) {
+			const domain = url.match(/https?:\/\/(www\.)?([^\s/]+)/);
+			if (domain) {
+				return domain[0];
+			}
+			return "";
+		},
+	},
+	upload: {
+		async handleImagePaste(
+			app: App,
+			editor: Editor,
+			clipboardData: DataTransfer
+		): Promise {
+			if (!getSettings().enablePasteUpload) {
+				return false;
+			}
+
+			const items = Array.from(clipboardData.items || []);
+			const imageItem = items.find((item) =>
+				item.type.startsWith("image/")
+			);
+			if (!imageItem) return false;
+
+			console.log("📥 Detected image paste, handling...", imageItem.type);
+
+			try {
+				const blob = imageItem.getAsFile();
+				if (!blob) return false;
+
+				const ext =
+					blob.type.split("/")[1]?.replace(/;.*/, "") || "png";
+				const fileName = `paste-${Date.now()}.${ext}`; // 👈 记住这个 fileName
+
+				const notice = new Notice(
+					i18n.t("notice.imageUploading", { fileName }),
+					0
+				);
+
+				const buffer = await Util.file.fileToUint8Array(blob);
+
+				const response = await HttpUtils.post(
+					"/upload?authorId=" + HttpUtils.getCurrentUserUid(),
+					{
+						file: buffer,
+						fileName: fileName,
+					}
+				);
+
+				notice.hide();
+
+				if (!response?.data?.url) {
+					new Notice(i18n.t("notice.imageUploadFailed"), 3000);
+					return true;
+				}
+
+				// ✅ 新增:删除 Obsidian 原生粘贴产生的 ![[fileName]] 或 ![](fileName)
+				try {
+					const cursor = editor.getCursor();
+					const line = editor.getLine(cursor.line);
+					// 构造可能的原生粘贴内容(Obsidian 偏好双括号)
+					const nativeEmbed1 = `![[${blob.name}]]`;
+					const nativeEmbed2 = `![](${blob.name})`;
+					const nativeEmbed3 = `![image](${blob.name})`; // 少数情况
+
+					// 从光标位置往前找(原生粘贴通常在当前光标处插入)
+					const startPos = Math.max(
+						0,
+						cursor.ch - nativeEmbed1.length - 20
+					);
+					const segment = line.substring(startPos, cursor.ch + 20);
+
+					let toDelete = null;
+					if (segment.includes(nativeEmbed1)) {
+						toDelete = nativeEmbed1;
+					} else if (segment.includes(nativeEmbed2)) {
+						toDelete = nativeEmbed2;
+					} else if (segment.includes(nativeEmbed3)) {
+						toDelete = nativeEmbed3;
+					}
+
+					if (toDelete) {
+						// 找到匹配项,计算其在行内的位置
+						const idx = line.indexOf(toDelete, startPos);
+						if (idx !== -1) {
+							editor.replaceRange(
+								"",
+								{ line: cursor.line, ch: idx },
+								{ line: cursor.line, ch: idx + toDelete.length }
+							);
+							// 修正光标位置(恢复到删除后的位置)
+							editor.setCursor({ line: cursor.line, ch: idx });
+							console.log(`🧹 已删除原生粘贴占位符: ${toDelete}`);
+						}
+					}
+				} catch (e) {
+					console.warn(
+						"Failed to remove native paste placeholder:",
+						e
+					);
+					// 不中断主流程
+				}
+
+				const domain = Util.url.extractDomain(HttpUtils.getCurrentHost());
+				const imageUrl =
+					(domain.endsWith("/") ? domain : domain + "/") +
+					response.data.url;
+
+				const markdownImage = `![](${imageUrl})`;
+				editor.replaceSelection(markdownImage);
+
+				// 上传成功后,检查并删除当前目录下的同名本地文件
+				try {
+					const activeFile = app.workspace.getActiveFile();
+					if (activeFile) {
+						const parentDir = app.vault.getAbstractFileByPath(
+							activeFile.parent?.path || "/"
+						);
+
+						if (parentDir && parentDir instanceof TFolder) {
+							const attachmentPath =
+								(app.vault as any).config
+									?.attachmentFolderPath || "";
+							let delFilepath = blob.name;
+							if (attachmentPath) {
+								delFilepath = attachmentPath + "/" + blob.name;
+								delFilepath = delFilepath.substring(1);
+							}
+							console.log(delFilepath);
+							let existingFile =
+								app.vault.getAbstractFileByPath(delFilepath);
+							console.log(existingFile);
+							if (existingFile) {
+								await app.vault.delete(existingFile);
+								console.log(
+									`🗑️ 已删除本地重复文件: ${delFilepath}`
+								);
+							}
+						}
+					}
+				} catch (delErr) {
+					console.warn(
+						"Cleanup local duplicate file failed:",
+						delErr
+					);
+					// 不中断主流程,静默失败
+				}
+
+				new Notice(i18n.t("notice.imageUploaded"), 2000);
+				return true;
+			} catch (err) {
+				console.error("Paste image upload failed:", err);
+				// 上传失败的具体原因 HttpUtils 已经弹过,别再盖一条笼统的
+				HttpUtils.notifyError(err, i18n.t("notice.pasteUploadFailed"));
+				return true;
+			}
+		},
+	},
+};
diff --git a/view/add_metasl.ts b/view/add_metasl.ts
new file mode 100644
index 0000000..9af9007
--- /dev/null
+++ b/view/add_metasl.ts
@@ -0,0 +1,81 @@
+import { App, Modal, Notice } from "obsidian";
+import { HttpUtils } from "../utils/request";
+import i18n from "../utils/i18n";
+export class addMetas extends Modal {
+	notice: Notice;
+	type: string;
+	type_name: string;
+	name: string;
+	fun: () => Promise;
+	/** 正在提交:防止连按回车重复新建同名分类/标签 */
+	private submitting = false;
+	constructor(app: App, type: string, fun: () => Promise) {
+		super(app);
+		this.type = type; // "tag" | "category"
+		this.type_name = type === "tag" ? i18n.t("field.tag") : i18n.t("field.category");
+		this.fun = fun;
+	}
+
+	async onOpen() {
+		const { contentEl } = this;
+		contentEl.createEl("h2", {
+			text: i18n.t("common.add") + ` ${this.type_name}`,
+		});
+
+		const titleInput = contentEl.createEl("input", {
+			attr: {
+				type: "text",
+				placeholder:
+					i18n.t("common.input") + `${this.type_name} ` + i18n.t("common.enter"),
+				style: "width: 100%; margin-top: 15px; margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);",
+			},
+		});
+		titleInput.addEventListener("input", (event) => {
+			const inputValue = (event.target as HTMLInputElement).value;
+			this.name = inputValue;
+		});
+
+		titleInput.addEventListener("keydown", async (event) => {
+			if (event.key !== "Enter") return;
+			if (this.submitting) return;
+
+			// 直接读输入框,别用 this.name:它只在 input 事件里赋值,
+			// 打开弹窗直接敲回车时还是 undefined,会把空名字发到服务器
+			const name = titleInput.value.trim();
+			if (name === "") {
+				new Notice(`${this.type_name}` + i18n.t("common.empty"));
+				return;
+			}
+
+			this.submitting = true;
+			const pending = new Notice(i18n.t("sync.adding") + "...");
+			try {
+				const response = await HttpUtils.post("/addMetas", {
+					name,
+					type: this.type,
+				});
+				if (response.status === "success") {
+					new Notice(`${this.type_name}` + i18n.t("sync.addSuccess"));
+					await this.fun();
+					this.close();
+				}
+			} catch (error) {
+				// 具体原因 HttpUtils 已经弹过(重复名称、未登录、接口不存在…),
+				// 这里只在它没弹过时补一句,避免两条提示叠在一起
+				HttpUtils.notifyError(
+					error,
+					`${this.type_name} ` + i18n.t("error.requestFailed")
+				);
+				console.error("add meta failed:", error);
+			} finally {
+				pending.hide();
+				this.submitting = false;
+			}
+		});
+	}
+
+	onClose() {
+		const { contentEl } = this;
+		contentEl.empty();
+	}
+}
diff --git a/view/article_preview.ts b/view/article_preview.ts
new file mode 100644
index 0000000..2db17e5
--- /dev/null
+++ b/view/article_preview.ts
@@ -0,0 +1,38 @@
+import { App, Modal } from "obsidian";
+
+export class ArticlePreview extends Modal {
+	private animationTimeout: number | null = null;
+    private htmlContent: string;
+
+	constructor(app: App, htmlContent: string) {
+		super(app);
+		this.htmlContent = htmlContent;
+	}
+
+	onOpen() {
+		const { contentEl } = this;
+		contentEl.empty();
+		contentEl.addClass("article-preview-modal");
+
+		// 初始状态:透明 + 缩小
+		contentEl.addClass("fade-enter");
+		contentEl.innerHTML = this.htmlContent;
+
+		// 延迟触发进入动画,确保浏览器能识别初始状态
+		requestAnimationFrame(() => {
+			contentEl.removeClass("fade-enter");
+			contentEl.addClass("fade-enter-active");
+		});
+	}
+
+	onClose() {
+		const { contentEl } = this;
+		contentEl.addClass("fade-exit");
+		contentEl.removeClass("fade-enter-active");
+
+		// 设置动画持续时间,确保动画完成后再清空内容
+		this.animationTimeout = window.setTimeout(() => {
+			contentEl.empty();
+		}, 300); // 与 CSS 中的 transition 时间匹配
+	}
+}
diff --git a/view/article_type.ts b/view/article_type.ts
new file mode 100644
index 0000000..37de6bb
--- /dev/null
+++ b/view/article_type.ts
@@ -0,0 +1,878 @@
+// main.ts
+import { ItemView, setIcon, Modal, App, Notice, MarkdownView } from "obsidian";
+import i18n from "../utils/i18n";
+import { getSettings } from "../main";
+import { HttpUtils } from "../utils/request";
+import { Util } from "../utils/util";
+import { BrowseArticles } from "./browse_articles";
+
+// 图片预览模态框
+class ImageModal extends Modal {
+	file: any;
+
+	constructor(app: App, file: any) {
+		super(app);
+		this.file = file;
+	}
+
+	onOpen() {
+		const { contentEl } = this;
+		contentEl.empty();
+		contentEl.addClass("image-preview-modal");
+
+		// 创建图片容器
+		const imageContainer = contentEl.createDiv({
+			cls: "image-preview-container",
+		});
+
+		// 创建图片标题
+		imageContainer.createEl("h2", {
+			text: this.file.title,
+			cls: "image-preview-title",
+		});
+
+		// 创建图片信息
+		const infoContainer = imageContainer.createDiv({
+			cls: "image-preview-info",
+		});
+		infoContainer.createEl("span", {
+			text: `${i18n.t("field.type")}: ${this.file.type.toUpperCase()}`,
+			cls: "image-info-item",
+		});
+		infoContainer.createEl("span", {
+			text: `${i18n.t("field.size")}: ${this.formatFileSize(this.file.size)}`,
+			cls: "image-info-item",
+		});
+		infoContainer.createEl("span", {
+			text: `${i18n.t("field.time")}: ${this.file.createdAt}`,
+			cls: "image-info-item",
+		});
+
+		// 创建图片元素
+		const img = imageContainer.createEl("img", {
+			cls: "image-preview-img",
+			attr: { src: this.file.url },
+		});
+	}
+
+	// 格式化文件大小
+	formatFileSize(size: number): string {
+		if (size < 1024) {
+			return size + " B";
+		} else if (size < 1024 * 1024) {
+			return (size / 1024).toFixed(2) + " KB";
+		} else {
+			return (size / (1024 * 1024)).toFixed(2) + " MB";
+		}
+	}
+
+	onClose() {
+		const { contentEl } = this;
+		contentEl.empty();
+	}
+}
+
+const VIEW_TYPE = "obsidian-to-typecho-view";
+
+class CategoryView extends ItemView {
+	pageSize = 15; // 默认每页显示15条
+
+	getViewType(): string {
+		return VIEW_TYPE;
+	}
+
+	getDisplayText() {
+		return i18n.t("field.category");
+	}
+
+	getIcon(): string {
+		return "typecho";
+	}
+
+	async onOpen() {
+		const container = this.containerEl.children[1];
+		container.empty();
+
+		// 创建选项卡导航
+		const tabContainer = container.createDiv({ cls: "tab-container" });
+		const tabs = [
+			{ key: "all", label: i18n.t("field.allArticle") },
+			{ key: "category", label: i18n.t("field.category") },
+			{ key: "tag", label: i18n.t("field.tag") },
+			{ key: "file", label: i18n.t("field.file") },
+		];
+		// 初始化加载第一个 tab
+		this.currentTab = "category";
+
+		tabs.forEach((tab) => {
+			const tabEl = tabContainer.createEl("span", {
+				text: tab.label,
+				cls:
+					"tab-span " +
+					(tab.key === this.currentTab ? "selected" : ""),
+			});
+			tabEl.addEventListener("click", async () => {
+				if (tab.key == "all") {
+					new BrowseArticles(
+						this.app,
+						{ name: i18n.t("field.allArticle") },
+						"all"
+					).open();
+					return;
+				}
+				this.switchTab(tab.key, tabContainer, tabEl);
+			});
+		});
+
+		// 内容容器
+		this.contentContainer = container.createDiv({ cls: "tab-content" });
+
+		// 刷新按钮
+		const refreshButton = tabContainer.createEl("button", {
+			cls: "refresh-button",
+		});
+		setIcon(refreshButton, "rotate-ccw");
+		refreshButton.addEventListener("click", () => {
+			this.loadData(this.currentTab, this.contentContainer);
+		});
+
+		this.loadData("category", this.contentContainer);
+	}
+
+	switchTab(tabKey: string, tabContainer: HTMLElement, tabEl: HTMLElement) {
+		const selectedTabs =
+			tabContainer.querySelectorAll(".tab-span.selected");
+		selectedTabs.forEach((tab: HTMLElement) => {
+			tab.classList.remove("selected");
+		});
+		tabEl.classList.add("selected");
+		this.currentTab = tabKey;
+		this.contentContainer.empty();
+		this.loadData(tabKey, this.contentContainer);
+	}
+
+	currentTab: string;
+	contentContainer: HTMLElement;
+
+	async loadData(tabKey: string, container: Element) {
+		container.empty();
+
+		// 修改:使用 HttpUtils.getCurrentUserUid() 判断
+		if (!HttpUtils.getCurrentUserUid()) {
+			container.createEl("p", {
+				text: i18n.t("error.noTypechoUser"),
+			});
+			return;
+		}
+
+		let data: any[] = [];
+
+		if (tabKey === "category") {
+			const response = await HttpUtils.get("/categories", {});
+			data = Util.treeUtil.generateTreeData(
+				response.data,
+				"mid",
+				"parent"
+			);
+			const treeContainer = container.createDiv({
+				cls: "tree-container",
+			});
+			this.renderTree(treeContainer, data);
+		} else if (tabKey === "tag") {
+			const response = await HttpUtils.get("/tags", {});
+			data = Util.treeUtil.generateTreeData(
+				response.data,
+				"mid",
+				"parent"
+			);
+			const treeContainer = container.createDiv({
+				cls: "tree-container",
+			});
+			this.renderTree(treeContainer, data);
+		} else if (tabKey === "file") {
+			await this.loadFileList(container, 1);
+		}
+	}
+
+	async loadFileList(container: Element, page = 1) {
+		container.empty();
+
+		// 创建上传按钮和分页设置区域
+		const uploadContainer = container.createDiv({
+			cls: "upload-container",
+		});
+
+		// 创建分页设置区域
+		const pageSizeContainer = uploadContainer.createDiv({
+			cls: "page-size-container",
+		});
+
+		// 添加分页大小标签
+		pageSizeContainer.createEl("span", {
+			text: i18n.t("file.itemsPerPage") + ": ",
+			cls: "page-size-label",
+		});
+
+		// 创建分页大小选择器
+		const pageSizeSelect = pageSizeContainer.createEl("select", {
+			cls: "page-size-select",
+		});
+
+		// 添加选项
+		[10, 15, 20, 30, 50].forEach((size) => {
+			const option = pageSizeSelect.createEl("option", {
+				text: size.toString(),
+				value: size.toString(),
+			});
+
+			if (size === this.pageSize) {
+				option.selected = true;
+			}
+		});
+
+		// 添加选择事件
+		pageSizeSelect.addEventListener("change", () => {
+			this.pageSize = parseInt(pageSizeSelect.value);
+			this.loadFileList(container, 1); // 重新加载第一页
+		});
+
+		// 上传按钮
+		const uploadButton = uploadContainer.createEl("button", {
+			text: i18n.t("file.uploadFile"),
+			cls: "upload-button",
+		});
+		setIcon(uploadButton, "upload");
+
+		// 上传按钮点击事件
+		uploadButton.addEventListener("click", () => {
+			this.uploadFile(container, page);
+		});
+
+		const response = await HttpUtils.get(
+			`/fileList?page=${page}&pageSize=${this.pageSize}`,
+			{}
+		);
+		const fileData = response.data;
+
+		if (!fileData || !fileData.dataSet || fileData.dataSet.length === 0) {
+			container.createEl("p", {
+				text: i18n.t("error.noFiles"),
+			});
+			return;
+		}
+
+		// 修改:使用 HttpUtils.getCurrentHost()
+		fileData.dataSet.forEach((file: any) => {
+			file.url = Util.url.extractDomain(HttpUtils.getCurrentHost()) + file.path;
+		});
+
+		// 创建文件列表容器
+		const fileListContainer = container.createDiv({
+			cls: "file-list-container",
+		});
+
+		// 创建文件列表
+		const fileList = fileListContainer.createEl("ul", { cls: "file-list" });
+
+		// 添加文件项
+		fileData.dataSet.forEach((file: any) => {
+			const fileItem = fileList.createEl("li", { cls: "file-item" });
+
+			// 创建左侧信息区域
+			const infoContainer = fileItem.createDiv({
+				cls: "file-info-container",
+			});
+
+			// 如果是图片类型,添加缩略图预览
+			if (file.mime && file.mime.startsWith("image/")) {
+				const previewContainer = infoContainer.createDiv({
+					cls: "file-preview-container",
+				});
+
+				const previewImg = previewContainer.createEl("img", {
+					cls: "file-preview-img",
+					attr: { src: file.url },
+				});
+
+				// 点击图片弹出大屏预览
+				previewImg.addEventListener("click", (e) => {
+					e.stopPropagation();
+					this.showImageModal(file);
+				});
+			}
+
+			// 创建文件信息区域
+			const textContainer = infoContainer.createDiv({
+				cls: "file-text-container",
+			});
+
+			// 文件标题
+			textContainer.createEl("div", {
+				text: file.title,
+				cls: "file-title",
+			});
+
+			// 文件类型
+			textContainer.createEl("div", {
+				text: file.type ? file.type.toUpperCase() : "",
+				cls: "file-type",
+			});
+
+			// 创建右侧信息区域
+			const metaContainer = fileItem.createDiv({
+				cls: "file-meta-container",
+			});
+
+			// 文件时间
+			metaContainer.createEl("div", {
+				text: file.createdAt || "",
+				cls: "file-time",
+			});
+
+			// 操作按钮容器
+			const actionContainer = metaContainer.createDiv({
+				cls: "file-action-container",
+			});
+
+			// 复制URL按钮
+			const copyButton = actionContainer.createEl("button", {
+				cls: "file-action-button copy-button",
+				attr: { title: i18n.t("file.copyUrl") },
+			});
+			setIcon(copyButton, "link");
+
+			// 复制URL按钮点击事件
+			copyButton.addEventListener("click", (e) => {
+				e.stopPropagation();
+				this.copyToClipboard(file.url, file.title);
+			});
+
+			// 插入按钮
+			const insertButton = actionContainer.createEl("button", {
+				cls: "file-action-button insert-button",
+				attr: { title: i18n.t("file.insertToEditor") },
+			});
+			setIcon(insertButton, "document");
+
+			insertButton.addEventListener("click", async (e) => {
+				e.stopPropagation();
+				await this.insertToEditor(file.url, file.title);
+			});
+
+			// 删除按钮
+			const deleteButton = actionContainer.createEl("button", {
+				cls: "file-action-button delete-button",
+				attr: { title: i18n.t("file.deleteFile") },
+			});
+			setIcon(deleteButton, "trash");
+
+			// 删除按钮点击事件
+			deleteButton.addEventListener("click", async (e) => {
+				e.stopPropagation();
+				if (
+					!confirm(i18n.t("file.deleteConfirm", { fileName: file.title }))
+				) {
+					return;
+				}
+				// 只有真的删掉了才刷新列表,失败时保持原样等用户重试
+				if (await this.deleteFile(file.cid)) {
+					this.loadFileList(container, page);
+				}
+			});
+		});
+
+		// 添加分页控件
+		if (fileData.pages > 1) {
+			const paginationContainer = container.createDiv({
+				cls: "pagination-container",
+			});
+
+			// 上一页按钮
+			if (fileData.page > 1) {
+				const prevButton = paginationContainer.createEl("button", {
+					text: i18n.t("common.previousPage"),
+					cls: "pagination-button",
+				});
+				prevButton.addEventListener("click", () => {
+					this.loadFileList(container, fileData.page - 1);
+				});
+			}
+
+			// 页码信息
+			paginationContainer.createEl("span", {
+				text: `${fileData.page}/${fileData.pages}`,
+				cls: "pagination-info",
+			});
+
+			// 下一页按钮
+			if (fileData.page < fileData.pages) {
+				const nextButton = paginationContainer.createEl("button", {
+					text: i18n.t("common.nextPage"),
+					cls: "pagination-button",
+				});
+				nextButton.addEventListener("click", () => {
+					this.loadFileList(container, fileData.page + 1);
+				});
+			}
+		}
+	}
+
+	renderTree(container: Element, nodes: any[], depth = 0) {
+		const ul = container.createEl("ul", { cls: "tree-node-list" });
+
+		for (const node of nodes) {
+			const li = ul.createEl("li");
+			const wrapper = li.createDiv({ cls: "tree-node-wrapper" });
+
+			const indent = wrapper.createSpan({ cls: "tree-indent" });
+			indent.style.paddingLeft = `${depth * 16}px`;
+
+			if (node.children && node.children.length > 0) {
+				const toggleIcon = wrapper.createEl("span", {
+					text: node.isExpanded ? "▼" : "▶",
+					cls: "tree-toggle-icon",
+				});
+
+				toggleIcon.addEventListener("click", (e) => {
+					e.stopPropagation();
+					node.isExpanded = !node.isExpanded;
+					toggleIcon.setText(node.isExpanded ? "▼" : "▶");
+
+					if (node.isExpanded) {
+						const childContainer =
+							li.querySelector(".tree-children") ||
+							li.createEl("div", { cls: "tree-children" });
+						childContainer.empty();
+						this.renderTree(
+							childContainer,
+							node.children,
+							depth + 1
+						);
+					} else {
+						const childContainer =
+							li.querySelector(".tree-children");
+						if (childContainer) childContainer.remove();
+					}
+				});
+			}
+
+			wrapper.createEl("span", {
+				text: node.name,
+				cls: "tree-node-label",
+			});
+
+			if (node.count && node.count > 0) {
+				const articleIcon = wrapper.createEl("span", {
+					cls: "tree-article-icon",
+				});
+				setIcon(articleIcon, "newspaper");
+
+				articleIcon.addEventListener("click", (e) => {
+					e.stopPropagation();
+					new BrowseArticles(this.app, node, this.currentTab).open();
+				});
+			}
+
+			if (node.children && node.children.length > 0 && node.isExpanded) {
+				const childContainer = li.createEl("div", {
+					cls: "tree-children",
+				});
+				this.renderTree(childContainer, node.children, depth + 1);
+			}
+		}
+	}
+
+	// 显示图片大屏预览
+	showImageModal(file: any) {
+		const modal = new ImageModal(this.app, file);
+		modal.open();
+	}
+
+	// 删除文件
+	async deleteFile(cid: number) {
+		try {
+			const response = await HttpUtils.post("/deleteFile", { cid });
+			if (response) {
+				new Notice(i18n.t("file.deleteSuccess"));
+				return true;
+			}
+			return false;
+		} catch (error) {
+			console.error("delete file failed:", error);
+			// 具体原因(文件不存在 / 未登录 / 服务器报错)HttpUtils 已经弹过
+			HttpUtils.notifyError(error, i18n.t("file.deleteError"));
+			return false;
+		}
+	}
+
+	// 复制URL到剪贴板
+	copyToClipboard(url: string, fileName: string) {
+		if (!url) {
+			new Notice(i18n.t("file.copyFailed"));
+			return;
+		}
+
+		// 创建临时文本区域
+		const textarea = document.createElement("textarea");
+		textarea.value = url;
+		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("file.copySuccess", { fileName: fileName }));
+	}
+
+	/**
+	 * 获取当前活动的编辑器实例(兼容各种插件冲突)
+	 * 使用多种方式尝试获取,确保在各种情况下都能正常工作
+	 */
+	private getActiveEditor(): any {
+		try {
+			// 方法1: 通过 getActiveViewOfType 获取活动的 Markdown 视图
+			const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
+			if (markdownView && markdownView.editor) {
+				return markdownView.editor;
+			}
+			
+			// 方法2: 通过 activeLeaf 获取
+			const activeLeaf = this.app.workspace.activeLeaf;
+			if (activeLeaf && activeLeaf.view instanceof MarkdownView) {
+				return activeLeaf.view.editor;
+			}
+			
+			// 方法3: 遍历所有 Markdown 视图
+			const leaves = this.app.workspace.getLeavesOfType("markdown");
+			for (const leaf of leaves) {
+				if (leaf.view instanceof MarkdownView) {
+					return leaf.view.editor;
+				}
+			}
+			
+			// 方法4: 遍历所有叶子节点(兜底)
+			// 使用 getLeavesOfType 传入空字符串获取所有叶子
+			const allLeaves = this.app.workspace.getLeavesOfType("");
+			for (const leaf of allLeaves) {
+				if (leaf.view instanceof MarkdownView) {
+					return leaf.view.editor;
+				}
+			}
+			
+			return null;
+		} catch (error) {
+			console.error("获取编辑器实例失败:", error);
+			return null;
+		}
+	}
+
+	/**
+	 * 插入图片到当前编辑器
+	 * 修复了与写作助手等插件冲突的问题
+	 */
+	async insertToEditor(url: string, fileName: string) {
+		try {
+			// 使用增强的编辑器获取方法
+			const editor = this.getActiveEditor();
+			
+			if (!editor) {
+				new Notice(i18n.t("error.noEditor"));
+				return false;
+			}
+			
+			// 生成插入文本
+			let title = fileName.replace(/\.[^/.]+$/, "");
+			const insertText = `![${title}](${url})`;
+			
+			// 获取当前光标位置并插入
+			const cursor = editor.getCursor();
+			editor.replaceRange(insertText, cursor);
+			
+			// 可选:聚焦到编辑器
+			const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
+			if (activeView) {
+				this.app.workspace.revealLeaf(activeView.leaf);
+			}
+			
+			new Notice(i18n.t("error.inserted", { title }));
+			return true;
+			
+		} catch (error) {
+			console.error("insert to editor failed:", error);
+			new Notice(
+				i18n.t("error.insertFailed", {
+					message:
+						(error as any)?.message || i18n.t("error.unknownError"),
+				})
+			);
+			return false;
+		}
+	}
+
+	// 上传文件(单/多文件,带进度条 + 限速延迟)
+	uploadFile(container: Element, page: number) {
+		const fileInput = document.createElement("input");
+		fileInput.type = "file";
+		fileInput.multiple = true;
+		fileInput.style.display = "none";
+		document.body.appendChild(fileInput);
+
+		fileInput.addEventListener("change", async () => {
+			const files = Array.from(fileInput.files || []);
+			if (files.length === 0) {
+				document.body.removeChild(fileInput);
+				return;
+			}
+
+			// 创建上传进度面板
+			const progressPanel = this.createUploadProgressPanel(files.length);
+			document.body.appendChild(progressPanel.element);
+
+			let isCancelled = false;
+
+			// 取消按钮逻辑
+			if (progressPanel.cancelButton) {
+				progressPanel.cancelButton.onclick = () => {
+					isCancelled = true;
+					progressPanel.updateStatus(i18n.t("file.uploadCancelled"));
+					progressPanel.setProgress(0);
+					setTimeout(() => progressPanel.hide(), 1000);
+				};
+			}
+
+			try {
+				progressPanel.updateStatus(i18n.t("file.preparingUpload"));
+
+				for (let i = 0; i < files.length; i++) {
+					if (isCancelled) break;
+
+					const file = files[i];
+					const current = i + 1;
+					const total = files.length;
+
+					progressPanel.updateFile(file.name);
+					progressPanel.updateStatus(
+						i18n.t("file.uploadingProgress", { current, total })
+					);
+					progressPanel.setProgress(((current - 1) / total) * 100); // 上传前进度
+
+					try {
+						const buffer = await Util.file.fileToUint8Array(file);
+
+						// 修改:使用 HttpUtils.getCurrentUserUid()
+						const response = await HttpUtils.post(
+							"/upload?authorId=" + HttpUtils.getCurrentUserUid(),
+							{
+								file: buffer,
+								fileName: file.name,
+							}
+						);
+
+						if (!response) {
+							throw new Error("Upload response is empty");
+						}
+
+						// ✅ 单文件上传成功,更新进度为当前文件完成
+						progressPanel.setProgress((current / total) * 100);
+
+						// ⏱️ 限流延迟
+						if (i < files.length - 1) {
+							const delayMs =
+								300 + Math.floor(Math.random() * 300); // 300~600ms
+							await new Promise((resolve) =>
+								setTimeout(resolve, delayMs)
+							);
+						}
+					} catch (err) {
+						console.error(`Failed to upload ${file.name}:`, err);
+						progressPanel.updateStatus(
+							i18n.t("file.uploadItemFailed", {
+								fileName: file.name,
+							})
+						);
+						progressPanel.setProgress((current / total) * 100);
+						await new Promise((resolve) =>
+							setTimeout(resolve, 500)
+						);
+					}
+				}
+
+				if (isCancelled) {
+					progressPanel.updateStatus(i18n.t("file.uploadCancelled"));
+				} else {
+					progressPanel.updateStatus(i18n.t("file.uploadAllDone"));
+					progressPanel.setProgress(100);
+					await new Promise((resolve) => setTimeout(resolve, 1000));
+					this.loadFileList(container, page); // 刷新列表
+				}
+			} catch (error) {
+				console.error("Upload process error:", error);
+				progressPanel.updateStatus(i18n.t("file.uploadProcessError"));
+			} finally {
+				// 自动隐藏
+				setTimeout(
+					() => progressPanel.hide(),
+					isCancelled ? 1500 : 2000
+				);
+				document.body.removeChild(fileInput);
+			}
+		});
+
+		fileInput.click();
+	}
+
+	// 辅助方法:创建上传进度面板
+	private createUploadProgressPanel(totalFiles: number) {
+		const panel = document.createElement("div");
+		panel.className = "obsidian-upload-progress-panel";
+
+		// CSS 注入(一次性,防止重复)
+		if (!document.getElementById("upload-progress-style")) {
+			const style = document.createElement("style");
+			style.id = "upload-progress-style";
+			style.textContent = `
+            .obsidian-upload-progress-panel {
+                position: fixed;
+                bottom: 20px;
+                right: 20px;
+                z-index: 9999;
+                background: var(--background-secondary);
+                border: 1px solid var(--background-modifier-border);
+                border-radius: 8px;
+                padding: 12px 16px;
+                min-width: 300px;
+                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
+                font-size: var(--font-ui-smaller);
+                transition: opacity 0.3s, transform 0.3s;
+                opacity: 1;
+                transform: translateY(0);
+            }
+            .obsidian-upload-progress-panel.fade-out {
+                opacity: 0;
+                transform: translateY(20px);
+            }
+            .upload-progress-header {
+                display: flex;
+                justify-content: space-between;
+                align-items: center;
+                margin-bottom: 8px;
+            }
+            .upload-progress-title {
+                font-weight: 600;
+                color: var(--text-normal);
+            }
+            .upload-progress-cancel {
+                background: none;
+                border: none;
+                color: var(--text-muted);
+                cursor: pointer;
+                font-size: 16px;
+                padding: 2px;
+                border-radius: 4px;
+            }
+            .upload-progress-cancel:hover {
+                color: var(--text-accent);
+                background: var(--background-modifier-hover);
+            }
+            .upload-progress-filename {
+                color: var(--text-faint);
+                white-space: nowrap;
+                overflow: hidden;
+                text-overflow: ellipsis;
+                margin-bottom: 4px;
+            }
+            .upload-progress-bar-container {
+                width: 100%;
+                height: 6px;
+                background: var(--background-modifier-border);
+                border-radius: 3px;
+                overflow: hidden;
+                margin: 6px 0;
+            }
+            .upload-progress-bar {
+                height: 100%;
+                background: var(--interactive-accent);
+                border-radius: 3px;
+                width: 0%;
+                transition: width 0.3s ease;
+            }
+            .upload-progress-status {
+                font-size: var(--font-ui-smaller);
+                color: var(--text-muted);
+                display: flex;
+                justify-content: space-between;
+            }
+        `;
+			document.head.appendChild(style);
+		}
+
+		panel.innerHTML = `
+        
+ ${i18n.t("file.uploadPanelTitle")} + +
+
-
+
+
+
+
+ ${i18n.t("file.preparing")} + 0% +
+ `; + + const filenameEl = panel.querySelector( + ".upload-progress-filename" + ) as HTMLElement; + const barEl = panel.querySelector( + ".upload-progress-bar" + ) as HTMLElement; + const statusEl = panel.querySelector(".status-text") as HTMLElement; + const percentEl = panel.querySelector( + ".progress-percent" + ) as HTMLElement; + const cancelButton = panel.querySelector( + ".upload-progress-cancel" + ) as HTMLElement; + + const api = { + element: panel, + cancelButton, + + updateFile(filename: string) { + filenameEl.textContent = filename; + }, + + updateStatus(text: string) { + statusEl.textContent = text; + }, + + setProgress(percent: number) { + const p = Math.max(0, Math.min(100, Math.round(percent))); + barEl.style.width = `${p}%`; + percentEl.textContent = `${p}%`; + }, + + hide() { + panel.classList.add("fade-out"); + setTimeout(() => { + if (panel.parentNode) panel.parentNode.removeChild(panel); + }, 300); + }, + }; + + return api; + } + + async onClose() { + // 清理资源 + } +} + +export { CategoryView, VIEW_TYPE }; \ No newline at end of file diff --git a/view/browse_articles.ts b/view/browse_articles.ts new file mode 100644 index 0000000..822fd8c --- /dev/null +++ b/view/browse_articles.ts @@ -0,0 +1,192 @@ +import { App, Modal, htmlToMarkdown, setIcon } from "obsidian"; +import { HttpUtils } from "../utils/request"; +import i18n from "../utils/i18n"; +import { ArticlePreview } from "./article_preview"; + +export class BrowseArticles extends Modal { + data: any; + currentPage = 1; + totalPages = 1; + contentContainer: HTMLElement; + type: string; + + constructor(app: App, data: any,type: string) { + super(app); + this.data = data; + this.type = type; + this.modalEl.addClass("browse-articles-modal"); + } + + async onOpen() { + const { contentEl } = this; + contentEl.empty(); + + const header = contentEl.createEl("div", { cls: "modal-header" }); + header.createEl("h2", { + text: `${this.data.name}-${i18n.t("field.article")}`, + }); + + // 创建内容容器 + this.contentContainer = contentEl.createEl("div", { + cls: "modal-content", + }); + + await this.loadPage(this.currentPage); + } + + async loadPage(page: number) { + this.contentContainer.empty(); + const loadingEl = this.contentContainer.createEl("div", { + text: i18n.t("common.loading"), + }); + try { + const params = { + page: page.toString(), + pageSize: "10", + filterType: this.type ?? '', + filterSlug: this.data.slug ?? '', + }; + + let url = "/posts?"; + for (const key in params) { + url += `${key}=${params[key as keyof typeof params]}&`; + } + + const response = await HttpUtils.get(url); + + if ( + response.status === "success" && + response.data?.dataSet?.length > 0 + ) { + loadingEl.setText(""); + this.totalPages = response.data.pages; + this.currentPage = page; + response.data.dataSet.forEach((post: any) => { + const postEl = this.contentContainer.createEl("div", { + cls: "browse-article-item", + }); + // 标题部分 + const titleEl = postEl.createEl("div", { + cls: "article-title", + }); + titleEl.createEl("a", { + text: post.title, + href: post.permalink, + attr: { target: "_blank" }, + }); + + // 日期部分 + postEl.createEl("div", { + cls: "article-date", + text: `${post.year}-${post.month}-${post.day}`, + }); + + // 保存本地 + const downloadIcon = titleEl.createEl("span", { + cls: "download-icon", + }); + setIcon(downloadIcon, "hard-drive-download"); + downloadIcon.addEventListener("click", async (e) => { + const content = htmlToMarkdown(post.digest).toString(); + const fileName = `${post.title}.md`; + + // 构建带 frontmatter 的内容 + const frontmatter = `--- +title: ${post.title} +typecho: + cid: ${post.cid} + slug: ${post.slug} + permalink: ${post.permalink} + created: ${post.year}-${post.month}-${post.day} +--- + +`; + + const fullContent = frontmatter + content; + + let file = this.app.vault.getFileByPath(fileName); + if (file) { + await this.app.vault.modify(file, fullContent); + } else { + file = await this.app.vault.create(fileName, fullContent); + } + + // 打开文件 + if (file) { + this.app.workspace.openLinkText(file.path, "", true); + } + this.close(); +}); + + // 点击预览内容 + postEl.addEventListener("click", (e) => { + const target = e.target as HTMLElement; + if (target.closest("a") || target.closest("svg")) { + return; + } + e.stopPropagation(); + e.preventDefault(); + new ArticlePreview(this.app, post.digest).open(); + }); + }); + + // 清除旧的分页控件再重新渲染 + this.paginationEl?.remove(); + this.renderPagination(); + } else { + this.contentContainer.createEl("p", { + cls: "no-articles", + text: i18n.t("field.no_articles_found"), + }); + } + } catch (error) { + loadingEl.setText(""); + this.contentContainer.createEl("p", { + text: i18n.t("common.error_occurred"), + }); + console.error("Failed to fetch articles:", error); + } + } + + private paginationEl: HTMLElement | null = null; + renderPagination() { + // 先清除旧的分页控件 + this.paginationEl?.remove(); + + // 创建新的分页控件并保存引用 + this.paginationEl = this.contentContainer.createEl("div", { + cls: "pagination", + }); + + const prevBtn = this.paginationEl.createEl("button", { + text: i18n.t("common.previousPage"), + }); + prevBtn.disabled = this.currentPage <= 1; + prevBtn.addEventListener("click", () => { + if (this.currentPage > 1) { + this.loadPage(this.currentPage - 1); + } + }); + + this.paginationEl.createEl("span", { + text: i18n.t("common.pageOf", { + page: this.currentPage, + total: this.totalPages, + }), + }); + + const nextBtn = this.paginationEl.createEl("button", { + text: i18n.t("common.nextPage"), + }); + nextBtn.disabled = this.currentPage >= this.totalPages; + nextBtn.addEventListener("click", () => { + if (this.currentPage < this.totalPages) { + this.loadPage(this.currentPage + 1); + } + }); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + } +} diff --git a/view/category_tree.ts b/view/category_tree.ts new file mode 100644 index 0000000..33f91be --- /dev/null +++ b/view/category_tree.ts @@ -0,0 +1,520 @@ +export interface CategoryNode { + mid: string; + name: string; + parent?: string; + children: CategoryNode[]; + [key: string]: any; +} + +export interface MetaListOptions { + /** 标题 */ + title: string; + /** 空列表提示 */ + emptyText: string; + /** 右上角按钮文字 */ + addText: string; + /** 判断某项是否被选中 */ + isSelected: (mid: string) => boolean; + /** 勾选状态变化 */ + onToggle: (mid: string, checked: boolean) => void; + /** 点击「添加」 */ + onAdd: () => void; + /** 是否显示搜索框(标签多时用来模糊筛选) */ + searchable?: boolean; + /** 搜索框占位文字 */ + searchPlaceholder?: string; + /** 搜索无结果提示 */ + noMatchText?: string; + /** 列表底部提示:已选 / 总数 */ + selectionText?: (selected: number, total: number) => string; + /** 列表底部提示:超过渲染上限时剩余数量 */ + moreText?: (rest: number) => string; +} + +const PANEL_STYLE = ` + border: 1px solid var(--background-modifier-border); + padding: 10px; + border-radius: 5px; + max-height: 280px; + overflow-y: auto; +`; + +const HEADER_STYLE = + "display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; flex-wrap: wrap; gap: 4px;"; + +const HEADER_TITLE_STYLE = + "margin: 0; font-weight: bold; color: var(--text-normal); font-size: 14px;"; + +const EMPTY_STYLE = + "color: var(--text-muted); font-size: 13px; padding: 8px 0; text-align: center;"; + +const CHECKBOX_STYLE = + "margin-right: 3px; accent-color: var(--interactive-accent); flex-shrink: 0;"; + +const SEARCH_STYLE = ` + width: 100%; + padding: 4px 8px; + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + background: var(--background-primary); + color: var(--text-normal); + font-size: 12px; +`; + +const FOOTER_STYLE = + "margin-top: 6px; color: var(--text-faint); font-size: 11px; line-height: 1.4;"; + +/** + * 一次最多渲染多少个标签 + * + * 站点的标签动辄上千,全量渲染会明显卡顿;列表按相关度排序后只渲染前 N 个, + * 剩下的提示用户继续输入缩小范围。 + */ +const TAG_RENDER_LIMIT = 200; + +/** + * 模糊匹配打分(不匹配返回 -1) + * + * 依次按「完全相同 → 前缀 → 包含 → 子序列」降级,分数越高排得越前。 + * 中文没有拼音库,用子序列能覆盖「输几个字命中长标签」这种常见场景, + * 例如输入「前端」能命中「前端工程化实践」。 + */ +export function fuzzyScore(text: string, query: string): number { + const t = String(text || "").toLowerCase(); + const q = String(query || "").trim().toLowerCase().replace(/\s+/g, ""); + if (!q) return 0; + if (t === q) return 100; + + if (t.startsWith(q)) return 80; + + const index = t.indexOf(q); + if (index >= 0) return 60 - Math.min(index, 20); + + // 子序列匹配:query 的字符按顺序出现在 text 中即可 + let i = 0; + let first = -1; + for (let k = 0; k < t.length && i < q.length; k++) { + if (t[k] === q[i]) { + if (first < 0) first = k; + i++; + } + } + if (i >= q.length) return 30 - Math.min(first, 20); + + return -1; +} + +/** + * 构建分类树形结构(按名称排序) + */ +export function buildCategoryTree(categories: any[]): CategoryNode[] { + const map: { [key: string]: CategoryNode } = {}; + const tree: CategoryNode[] = []; + + categories.forEach((cat) => { + map[cat.mid] = { ...cat, children: [] }; + }); + + categories.forEach((cat) => { + const node = map[cat.mid]; + if (cat.parent && map[cat.parent]) { + map[cat.parent].children.push(node); + } else { + tree.push(node); + } + }); + + const sortChildren = (nodes: CategoryNode[]) => { + nodes.sort((a, b) => String(a.name).localeCompare(String(b.name))); + nodes.forEach((node) => { + if (node.children && node.children.length > 0) { + sortChildren(node.children); + } + }); + }; + sortChildren(tree); + + return tree; +} + +function createAddButton(container: HTMLElement, text: string, onAdd: () => void) { + const button = container.createEl("button", { + text, + attr: { + style: + "cursor: pointer; padding: 2px 10px; background-color: var(--interactive-normal); color: var(--text-normal); border: none; border-radius: 3px; font-size: 12px;", + }, + }); + button.addEventListener("click", () => onAdd()); +} + +function createPanel(container: HTMLElement, options: MetaListOptions) { + const groupContainer = container.createDiv({ attr: { style: PANEL_STYLE } }); + + const headerRow = groupContainer.createDiv({ attr: { style: HEADER_STYLE } }); + headerRow.createEl("h4", { + text: options.title, + attr: { style: HEADER_TITLE_STYLE }, + }); + createAddButton(headerRow, options.addText, options.onAdd); + + return groupContainer; +} + +function renderLeafNode( + container: HTMLElement, + node: CategoryNode, + options: MetaListOptions +) { + const wrapper = container.createDiv({ + attr: { + style: ` + display: inline-flex; + align-items: center; + padding: 2px 4px; + border-radius: 3px; + color: var(--text-normal); + cursor: pointer; + `, + }, + }); + + const checkbox = wrapper.createEl("input", { + type: "checkbox", + value: node.mid, + attr: { id: `category-${node.mid}`, style: CHECKBOX_STYLE }, + }); + checkbox.checked = options.isSelected(String(node.mid)); + + const label = wrapper.createEl("label", { + text: node.name, + attr: { + for: `category-${node.mid}`, + style: "cursor: pointer; font-size: 13px; color: var(--text-normal);", + }, + }); + + checkbox.addEventListener("change", () => { + options.onToggle(String(node.mid), checkbox.checked); + }); + // 注意:label 已经通过 for="category-" 原生关联了 checkbox, + // 点击文字会自动触发一次 click。这里再手动 checkbox.click() 就是第二次, + // 相当于「选中后立刻取消」,表现为点标签文字永远勾不上。交给浏览器原生行为即可。 +} + +/** + * 递归渲染分类树 + */ +function renderCategoryTree( + container: HTMLElement, + tree: CategoryNode[], + options: MetaListOptions, + level: number = 0 +) { + const withChildren = tree.filter((node) => node.children.length > 0); + const withoutChildren = tree.filter((node) => node.children.length === 0); + + // 没有子分类的平铺成一行,节省纵向空间 + if (withoutChildren.length > 0) { + const rowContainer = container.createDiv({ + attr: { + style: ` + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 12px; + padding-left: ${level * 20}px; + margin: 2px 0; + `, + }, + }); + withoutChildren.forEach((node) => { + renderLeafNode(rowContainer, node, options); + }); + } + + // 有子分类的独占一行,可展开收起 + withChildren.forEach((node) => { + renderParentNode(container, node, options, level); + }); +} + +/** + * 渲染有子分类的节点(点击名称或箭头展开 / 收起) + */ +function renderParentNode( + container: HTMLElement, + node: CategoryNode, + options: MetaListOptions, + level: number = 0 +) { + let isExpanded = false; + + const parentWrapper = container.createDiv({ + attr: { + style: ` + margin: 2px 0; + padding-left: ${level * 20}px; + `, + }, + }); + + const row = parentWrapper.createDiv({ + attr: { + style: ` + display: flex; + align-items: center; + padding: 2px 4px; + border-radius: 3px; + color: var(--text-normal); + cursor: pointer; + `, + }, + }); + + const checkbox = row.createEl("input", { + type: "checkbox", + value: node.mid, + attr: { id: `category-${node.mid}`, style: CHECKBOX_STYLE }, + }); + checkbox.checked = options.isSelected(String(node.mid)); + + const label = row.createEl("label", { + text: node.name, + attr: { + for: `category-${node.mid}`, + style: ` + cursor: pointer; + font-size: 13px; + color: var(--text-normal); + font-weight: 500; + `, + }, + }); + + row.createSpan({ + text: `(${node.children.length})`, + attr: { + style: + "color: var(--text-muted); font-size: 11px; margin-left: 2px; flex-shrink: 0;", + }, + }); + + const toggleIndicator = row.createSpan({ + text: " ▶", + attr: { + style: ` + color: var(--text-muted); + font-size: 11px; + margin-left: 4px; + user-select: none; + `, + }, + }); + + const childrenContainer = parentWrapper.createDiv({ + attr: { style: "display: none; margin-left: 0px;" }, + }); + + renderCategoryTree(childrenContainer, node.children, options, level + 1); + + const toggleExpand = (e: Event) => { + e.stopPropagation(); + isExpanded = !isExpanded; + childrenContainer.style.display = isExpanded ? "block" : "none"; + toggleIndicator.setText(isExpanded ? " ▼" : " ▶"); + }; + + label.addEventListener("click", toggleExpand); + toggleIndicator.addEventListener("click", toggleExpand); + + checkbox.addEventListener("change", () => { + options.onToggle(String(node.mid), checkbox.checked); + }); + // 点复选框不要连带折叠 + checkbox.addEventListener("click", (e) => e.stopPropagation()); +} + +/** + * 渲染分类面板(含标题、添加按钮、空状态) + */ +export function renderCategoryPanel( + container: HTMLElement, + categories: any[], + options: MetaListOptions +) { + const groupContainer = createPanel(container, options); + const listContainer = groupContainer.createDiv({ + attr: { style: "margin-top: 5px;" }, + }); + + const tree = buildCategoryTree(categories); + + if (tree.length === 0) { + listContainer.createDiv({ text: options.emptyText, attr: { style: EMPTY_STYLE } }); + return; + } + + renderCategoryTree(listContainer, tree, options); +} + +/** + * 渲染一个标签复选框 + */ +function renderTagItem( + container: HTMLElement, + item: any, + options: MetaListOptions +) { + const wrapper = container.createDiv({ + attr: { + style: ` + display: inline-flex; + align-items: center; + padding: 2px 4px; + color: var(--text-normal); + cursor: pointer; + `, + }, + }); + + const checkbox = wrapper.createEl("input", { + type: "checkbox", + value: item.mid, + attr: { id: `tag-${item.mid}`, style: CHECKBOX_STYLE }, + }); + checkbox.checked = options.isSelected(String(item.mid)); + + const label = wrapper.createEl("label", { + text: item.name, + attr: { + for: `tag-${item.mid}`, + style: "cursor: pointer; font-size: 13px; color: var(--text-normal);", + }, + }); + + checkbox.addEventListener("change", () => { + options.onToggle(String(item.mid), checkbox.checked); + }); + // label 已通过 for 原生关联 checkbox,点击文字会自动切换一次; + // 再手动 checkbox.click() 就成了第二次,等于「选中又取消」,始终勾不上。 +} + +/** + * 渲染标签面板(平铺复选框 + 模糊搜索) + * + * 标签一多(几百上千个)按原样平铺根本找不到,这里加一个搜索框: + * 输入即筛选,已勾选的始终留在列表里(方便取消),其余按相关度排序。 + */ +export function renderTagPanel( + container: HTMLElement, + tags: any[], + options: MetaListOptions +) { + const groupContainer = createPanel(container, options); + + const listContainer = groupContainer.createDiv({ + attr: { + style: + "display: flex; flex-wrap: wrap; gap: 4px 12px; margin-top: 5px;", + }, + }); + const footer = groupContainer.createDiv({ attr: { style: FOOTER_STYLE } }); + + if (tags.length === 0) { + listContainer.createDiv({ text: options.emptyText, attr: { style: EMPTY_STYLE } }); + return; + } + + const isSelected = (item: any) => options.isSelected(String(item.mid)); + const totalSelected = () => tags.filter(isSelected).length; + + // 当前搜索词(输入框在下面创建,闭包里共用) + let query = ""; + + // 渲染上限之外还剩多少个(切搜索词时变) + let restCount = 0; + + const updateFooter = () => { + if (restCount > 0) { + footer.setText( + options.moreText + ? options.moreText(restCount) + : `+${restCount}` + ); + } else if (options.selectionText) { + footer.setText(options.selectionText(totalSelected(), tags.length)); + } else { + footer.setText(""); + } + }; + + // 勾选后不重绘列表(重绘会丢掉搜索框焦点),只刷新底部统计 + const itemOptions: MetaListOptions = { + ...options, + onToggle: (mid, checked) => { + options.onToggle(mid, checked); + updateFooter(); + }, + }; + + const render = () => { + listContainer.empty(); + + // 已选中的先列出来(不管是否匹配搜索词),再按相关度排其余匹配项 + const selected = tags.filter(isSelected); + const selectedIds = new Set(selected.map((item) => String(item.mid))); + const matched = tags + .filter((item) => !selectedIds.has(String(item.mid))) + .map((item) => ({ item, score: fuzzyScore(item.name, query) })) + .filter((entry) => entry.score >= 0) + .sort((a, b) => { + if (b.score !== a.score) return b.score - a.score; + return String(a.item.name).localeCompare(String(b.item.name)); + }) + .map((entry) => entry.item); + + const list = [...selected, ...matched]; + const shown = list.slice(0, TAG_RENDER_LIMIT); + restCount = list.length - shown.length; + + if (shown.length === 0) { + listContainer.createDiv({ + text: options.noMatchText || options.emptyText, + attr: { style: EMPTY_STYLE }, + }); + } else { + shown.forEach((item) => + renderTagItem(listContainer, item, itemOptions) + ); + } + + updateFooter(); + }; + + // 搜索框放在标题下方、列表上方(列表可滚动,搜索框吸顶常驻) + if (options.searchable) { + const searchRow = groupContainer.createDiv({ + attr: { + style: + "margin-top: 8px; position: sticky; top: 0; z-index: 1; padding-bottom: 4px; background: var(--background-primary);", + }, + }); + groupContainer.insertBefore(searchRow, listContainer); + + const searchInput = searchRow.createEl("input", { + type: "text", + attr: { + placeholder: + options.searchPlaceholder || `搜索${options.title}…`, + style: SEARCH_STYLE, + }, + }); + searchInput.addEventListener("input", () => { + query = searchInput.value; + render(); + }); + } + + render(); +} diff --git a/view/comment_modal.ts b/view/comment_modal.ts new file mode 100644 index 0000000..251e13a --- /dev/null +++ b/view/comment_modal.ts @@ -0,0 +1,133 @@ +import { App, Modal, Notice } from "obsidian"; +import i18n from "../utils/i18n"; + +export interface CommentModalOptions { + title: string; + initial?: string; + placeholder?: string; + submitText: string; + onSubmit: (text: string) => Promise | void; +} + +/** + * 评论回复 / 编辑弹窗 + */ +export class CommentModal extends Modal { + private options: CommentModalOptions; + private submitting = false; + + constructor(app: App, options: CommentModalOptions) { + super(app); + this.options = options; + } + + onOpen() { + const { contentEl } = this; + contentEl.empty(); + + contentEl.createEl("h2", { text: this.options.title }); + + const textarea = contentEl.createEl("textarea", { + cls: "otm-textarea", + attr: { + rows: "6", + placeholder: this.options.placeholder ?? "", + }, + }); + textarea.value = this.options.initial ?? ""; + + const footer = contentEl.createDiv({ cls: "otm-modal-actions" }); + + const submitButton = footer.createEl("button", { + cls: "mod-cta", + text: this.options.submitText, + }); + submitButton.addEventListener("click", async () => { + if (this.submitting) return; + + const text = textarea.value.trim(); + if (!text) { + new Notice(i18n.t("manager.textRequired")); + return; + } + + this.submitting = true; + submitButton.disabled = true; + try { + await this.options.onSubmit(text); + this.close(); + } catch (error) { + console.error("提交评论操作失败", error); + } finally { + this.submitting = false; + submitButton.disabled = false; + } + }); + + const cancelButton = footer.createEl("button", { + text: i18n.t("manager.cancel"), + }); + cancelButton.addEventListener("click", () => this.close()); + + textarea.focus(); + } + + onClose() { + this.contentEl.empty(); + } +} + +/** + * 通用确认弹窗(用于删除这类不可恢复操作) + */ +export class ConfirmModal extends Modal { + private titleText: string; + private message: string; + private onConfirm: () => Promise | void; + + constructor( + app: App, + titleText: string, + message: string, + onConfirm: () => Promise | void + ) { + super(app); + this.titleText = titleText; + this.message = message; + this.onConfirm = onConfirm; + } + + onOpen() { + const { contentEl } = this; + contentEl.empty(); + + contentEl.createEl("h2", { text: this.titleText }); + contentEl.createEl("p", { text: this.message }); + + const footer = contentEl.createDiv({ cls: "otm-modal-actions" }); + + const confirmButton = footer.createEl("button", { + cls: "mod-warning", + text: i18n.t("manager.confirm"), + }); + confirmButton.addEventListener("click", async () => { + confirmButton.disabled = true; + try { + await this.onConfirm(); + this.close(); + } catch (error) { + console.error("确认操作失败", error); + confirmButton.disabled = false; + } + }); + + const cancelButton = footer.createEl("button", { + text: i18n.t("manager.cancel"), + }); + cancelButton.addEventListener("click", () => this.close()); + } + + onClose() { + this.contentEl.empty(); + } +} diff --git a/view/meta_edit_modal.ts b/view/meta_edit_modal.ts new file mode 100644 index 0000000..28e2fa0 --- /dev/null +++ b/view/meta_edit_modal.ts @@ -0,0 +1,182 @@ +import { App, Modal, Notice, Setting } from "obsidian"; +import { HttpUtils } from "../utils/request"; +import i18n from "../utils/i18n"; + +export type MetaType = "category" | "tag"; + +/** + * 分类 / 标签的新增与编辑弹窗 + * + * meta 为 null 时是新增,否则是编辑已有项。 + */ +export class MetaEditModal extends Modal { + private type: MetaType; + private meta: any | null; + private onSaved: () => void | Promise; + + private nameValue: string; + private slugValue: string; + private descriptionValue: string; + private parentValue: string; + private categories: any[] = []; + private saving = false; + + constructor( + app: App, + type: MetaType, + meta: any | null, + onSaved: () => void | Promise + ) { + super(app); + this.type = type; + this.meta = meta; + this.onSaved = onSaved; + this.nameValue = meta?.name ?? ""; + this.slugValue = meta?.slug ?? ""; + this.descriptionValue = meta?.description ?? ""; + this.parentValue = String(meta?.parent ?? 0); + } + + async onOpen() { + const { contentEl } = this; + contentEl.empty(); + + const isEdit = !!this.meta; + const isCategory = this.type === "category"; + contentEl.createEl("h2", { + text: i18n.t( + isEdit + ? isCategory + ? "manager.editCategoryTitle" + : "manager.editTagTitle" + : isCategory + ? "manager.newCategoryTitle" + : "manager.newTagTitle" + ), + }); + + new Setting(contentEl) + .setName(i18n.t("manager.metaName")) + .addText((text) => + text.setValue(this.nameValue).onChange((value) => { + this.nameValue = value; + }) + ); + + new Setting(contentEl) + .setName(i18n.t("manager.metaSlug")) + .setDesc(i18n.t("manager.metaSlugDesc")) + .addText((text) => + text + .setValue(this.slugValue) + .setPlaceholder(this.meta?.slug ?? "") + .onChange((value) => { + this.slugValue = value; + }) + ); + + new Setting(contentEl) + .setName(i18n.t("manager.metaDescription")) + .addTextArea((area) => + area.setValue(this.descriptionValue).onChange((value) => { + this.descriptionValue = value; + }) + ); + + if (isCategory) { + await this.loadCategories(); + if (this.categories.length > 0) { + new Setting(contentEl) + .setName(i18n.t("manager.metaParent")) + .addDropdown((dropdown) => { + dropdown.addOption("0", i18n.t("manager.metaParentNone")); + for (const category of this.categories) { + if ( + this.meta && + Number(category.mid) === Number(this.meta.mid) + ) { + // 不能把自己设成自己的父级 + continue; + } + dropdown.addOption( + String(category.mid), + category.name + ); + } + dropdown.setValue(this.parentValue); + dropdown.onChange((value) => { + this.parentValue = value; + }); + }); + } + } + + const footer = contentEl.createDiv({ cls: "otm-modal-actions" }); + + const saveButton = footer.createEl("button", { + cls: "mod-cta", + text: i18n.t("manager.save"), + }); + saveButton.addEventListener("click", () => this.save(saveButton)); + + const cancelButton = footer.createEl("button", { + text: i18n.t("manager.cancel"), + }); + cancelButton.addEventListener("click", () => this.close()); + } + + private async loadCategories() { + try { + const response = await HttpUtils.get("/categories", {}, true); + this.categories = response?.data ?? []; + } catch (error) { + this.categories = []; + } + } + + private async save(button: HTMLButtonElement) { + if (this.saving) return; + + const name = this.nameValue.trim(); + if (!name) { + new Notice(i18n.t("manager.nameRequired")); + return; + } + + this.saving = true; + button.disabled = true; + + try { + if (this.meta) { + await HttpUtils.post("/editMeta", { + mid: this.meta.mid, + name, + slug: this.slugValue.trim(), + description: this.descriptionValue, + parent: Number(this.parentValue) || 0, + }); + } else { + await HttpUtils.post("/addMetas", { + name, + type: this.type, + slug: this.slugValue.trim(), + description: this.descriptionValue, + parent: Number(this.parentValue) || 0, + }); + } + + new Notice(i18n.t("manager.saved")); + await this.onSaved(); + this.close(); + } catch (error) { + console.error("保存分类/标签失败", error); + } finally { + this.saving = false; + button.disabled = false; + } + } + + onClose() { + this.contentEl.empty(); + } +} diff --git a/view/push.ts b/view/push.ts new file mode 100644 index 0000000..9f0db0e --- /dev/null +++ b/view/push.ts @@ -0,0 +1,943 @@ +import { App, Modal, Notice } from "obsidian"; +import { getSettings, saveSettings, getSites, getActiveSite, getSite } from "../main"; +import { addMetas } from "./add_metasl"; +import { HttpUtils } from "../utils/request"; +import i18n from "../utils/i18n"; +import { Util } from "../utils/util"; +import { renderCategoryPanel, renderTagPanel } from "./category_tree"; +import { + readTypechoMetaFresh, + writeTypechoMeta, +} from "../utils/frontmatter"; +import { formatBeijingTime } from "../utils/datetime"; + +const YAML_BLOCK = /^---\s*[\s\S]*?---\s*/; +const VERSION_SUFFIX = /\(v\d+\)-\d+$/; +const RENAME_PREFIX = /^.*?_改为_/; + +/** + * 记住最近一次 ribbon/命令打开发布框时聚焦的笔记路径。 + * + * 多窗口场景下 getActiveFile() 是「全局最后聚焦的文件」,弹窗打开过程中 + * 焦点可能被别的窗口抢走,导致 onOpen 里前后两次 getActiveFile() 拿到不同 + * 笔记:站点推断用 A、笔记加载用 B,分类/标签就勾不上。这里把路径冻结在 + * onOpen 开头一次,后续站点推断、笔记加载、回填全部复用它。 + */ +let lastFocusedNotePath = ""; + +export class PushModal extends Modal { + constructor(app: App) { + super(app); + } + notice: Notice; + baseFileName = ""; + title = ""; + slug = ""; + slugInput: HTMLInputElement; + content = ""; + selectedTags: string[] = []; + selectedCategories: string[] = []; + categoriesDom: HTMLElement; + tagsDom: HTMLElement; + activeFilePath: string; + + async onOpen() { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: i18n.t("sync.title") }); + + // 只在这里取一次聚焦笔记路径,冻结给本次弹窗全程使用。 + // getActiveFile() 在多窗口下会随焦点变化,前后两次调用可能拿到不同笔记, + // 导致「站点按 A 推断、笔记按 B 加载」,分类/标签自然勾不上。 + const activeFileAtOpen = this.app.workspace.getActiveFile(); + const notePath = activeFileAtOpen?.path || lastFocusedNotePath; + if (notePath) lastFocusedNotePath = notePath; + + // 默认站点按这篇笔记的 ty-url 域名推断,避免笔记属于 B 站、 + // 当前激活的是 A 站时首屏就匹配不到分类/标签 + const preferredSite = await this.preferredSiteForNote(notePath); + this.renderSiteSelector(contentEl, preferredSite?.id); + + await this.getCategories(contentEl); + await this.getTags(contentEl); + + // 标题输入 + const titleInput = contentEl.createEl("input", { + attr: { + type: "text", + placeholder: `${i18n.t("common.input")} ${i18n.t("field.title")}`, + style: + "width: 100%; margin-top: 15px; margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);", + }, + }); + titleInput.addEventListener("input", (event) => { + this.title = (event.target as HTMLInputElement).value; + }); + + // 等笔记属性回填完成再走完 onOpen:之前是 fire-and-forget, + // 回填里的重绘可能发生在弹窗其余控件之后,表现为「slug 有、分类标签没有」 + await this.renderFileSelector(contentEl, titleInput); + this.renderSlugField(contentEl); + this.renderPublishButton(contentEl); + } + + /** + * 按笔记属性里 ty-url 的域名,推断这篇笔记属于哪个站点。 + * 找不到就返回 null,让调用方沿用当前激活站点。 + */ + private async preferredSiteForNote(path: string) { + if (!path) return null; + const meta = await readTypechoMetaFresh(this.app, path); + if (!meta.url) return null; + + const normalize = (host: string) => + host + .replace(/^https?:\/\//i, "") + .replace(/^www\./i, "") + .replace(/\/.*$/, "") + .toLowerCase(); + const noteHost = normalize(meta.url); + const sites = getSites(); + return ( + sites.find((site) => normalize(site.Host || "") === noteHost) || null + ); + } + + /** + * 多站点选择器 + */ + private renderSiteSelector(contentEl: HTMLElement, preferredSiteId?: string) { + const sites = getSites(); + if (sites.length === 0) return; + + const siteDiv = contentEl.createDiv({ + attr: { style: "margin-bottom: 15px;" }, + }); + siteDiv.createEl("label", { + text: i18n.t("sync.selectSite"), + attr: { style: "margin-right: 10px;" }, + }); + const siteSelect = siteDiv.createEl("select"); + + const defaultSiteId = preferredSiteId || getActiveSite()?.id; + for (const site of sites) { + siteSelect.createEl("option", { + text: site.name, + value: site.id, + }); + } + + // 不依赖 option.selected 的 DOM 副作用:直接用推断出的 id 设置 value。 + // 某些 Obsidian 版本里 createEl 后再改 selected 不会同步到 select.value, + // 结果列表拉的是 A 站、select 显示 B 站,切换前后对不上。 + if (defaultSiteId) siteSelect.value = defaultSiteId; + + const initSite = getSite(siteSelect.value) || getActiveSite(); + if (initSite) { + HttpUtils.setCurrentSite(initSite.Host, initSite.Token); + } + + siteSelect.addEventListener("change", async () => { + const selectedSite = getSite(siteSelect.value); + if (!selectedSite) return; + HttpUtils.setCurrentSite(selectedSite.Host, selectedSite.Token); + // 只重新拉列表会把之前的勾选清空;必须按当前笔记属性再匹配一次 + // (restoreSelection 内部自带列表渲染,不用在这里单独 getCategories/getTags) + await this.restoreSelection(); + new Notice(i18n.t("sync.switchedTo", { name: selectedSite.name })); + }); + } + + /** + * 笔记文件选择器 + */ + private async renderFileSelector( + contentEl: HTMLElement, + titleInput: HTMLInputElement + ): Promise { + const files = this.app.vault.getFiles(); + // 优先用 onOpen 开头冻结的路径:多窗口下这里再取一次 getActiveFile() + // 可能已经指向另一个窗口的笔记,和站点推断用的那篇不是同一篇。 + this.activeFilePath = lastFocusedNotePath; + + const selectEl = contentEl.createEl("select", { + attr: { + style: + "width: 100%; margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);", + }, + }); + + for (const file of files) { + if (!file.path.endsWith(".md")) continue; + selectEl.createEl("option", { + text: file.path, + value: file.path, + }); + } + + // 冻结路径可能属于另一个库的窗口(多窗口各开不同库),在当前库里 + // 并不存在。逐层回退到一个真实存在的 md,保证一定能加载并回填。 + const exists = (p: string) => !!p && !!this.app.vault.getFileByPath(p); + if (!exists(this.activeFilePath)) { + const activeFile = this.app.workspace.getActiveFile(); + this.activeFilePath = exists(activeFile?.path || "") + ? activeFile!.path + : ""; + } + if (!this.activeFilePath && selectEl.value) { + this.activeFilePath = selectEl.value; + } + + // 关键:无论来自哪条路径,都要真正 loadNote 一次。 + // restoreSelection 是在 loadNote → setTitleFromFileName 里触发的; + // 旧代码只在 activeFilePath 恰好命中某文件时才 loadNote,冻结路径 + // 一旦不在列表里就整段跳过,表现为「提示获取分类/标签却没勾选」。 + if (this.activeFilePath) { + selectEl.value = this.activeFilePath; + await this.loadNote(this.activeFilePath, titleInput); + } + + selectEl.addEventListener("change", async (event) => { + const selectedFilePath = (event.target as HTMLSelectElement).value; + if (!selectedFilePath) { + new Notice(i18n.t("error.noFileSelected")); + return; + } + await this.loadNote(selectedFilePath, titleInput); + }); + } + + /** + * 选中一篇笔记:先读内容再设标题。 + * + * 两件事必须按顺序做完,否则会出现「标题是新的、正文还是上一篇」的错配: + * 读取本身是异步的,早先版本没有 await,点发布时 this.content 可能还是空串 + * 或上一次的文件内容。 + */ + private async loadNote(path: string, titleInput: HTMLInputElement) { + await this.readFileAndSetContent(path); + await this.setTitleFromFileName(path, titleInput); + } + + /** + * 高级选项:别名 + */ + private renderSlugField(contentEl: HTMLElement) { + const advancedDetails = contentEl.createEl("details", { + attr: { + style: + "margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; padding: 10px;", + }, + }); + advancedDetails.createEl("summary", { + text: i18n.t("sync.advancedOptions"), + attr: { + style: + "cursor: pointer; color: var(--text-muted); font-size: 0.9em;", + }, + }); + + const slugContainer = advancedDetails.createDiv({ + attr: { style: "margin-top: 10px;" }, + }); + slugContainer.createEl("label", { + text: i18n.t("sync.alias"), + attr: { + style: + "display: block; font-size: 0.8em; color: var(--text-muted); margin-bottom: 5px;", + }, + }); + + this.slugInput = slugContainer.createEl("input", { + attr: { + type: "text", + placeholder: "Slug", + style: + "width: 100%; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);", + }, + }); + this.slugInput.value = this.slug; + this.slugInput.addEventListener("input", (event) => { + this.slug = (event.target as HTMLInputElement).value; + }); + } + + private renderPublishButton(contentEl: HTMLElement) { + const button = contentEl.createEl("button", { + text: i18n.t("sync.publish"), + attr: { + style: + "margin-top: 15px; padding: 8px 16px; border: none; border-radius: 4px; color: var(--text-normal); cursor: pointer;", + }, + }); + button.addEventListener("click", () => this.publish()); + } + + /** + * 发布 / 更新 + */ + private async publish() { + // 兜底:弹窗刚打开就点发布,异步读取可能还没回填,这里补读一次 + if (this.content === "" && this.activeFilePath) { + await this.readFileAndSetContent(this.activeFilePath); + } + + if (this.title === "" || this.content === "") { + new Notice(i18n.t("error.titleOrContentCannotBeEmpty")); + return; + } + + this.notice = new Notice(i18n.t("sync.publishing")); + try { + const mid = [...this.selectedCategories, ...this.selectedTags]; + + let finalContent = this.content; + if (getSettings().removeMetadata) { + finalContent = finalContent.replace(YAML_BLOCK, ""); + } + + const filePath = + this.activeFilePath || (await this.getSelectedFilePath()); + const meta = await readTypechoMetaFresh(this.app, filePath); + + // 传给服务端的 originalTitle 保留旧值(用于判断是否改过标题), + // 但写回笔记属性的必须是本次发布的实际标题,否则改了标题后 + // 属性面板永远显示旧标题,下次回填又用旧的。 + let originalTitle = meta.title || this.title; + originalTitle = originalTitle.replace(VERSION_SUFFIX, ""); + const syncedTitle = this.title + .replace(VERSION_SUFFIX, "") + .replace(RENAME_PREFIX, "") + .trim(); + + // ========== 自动插入 Obsidian 标识 ========== + const isUpdate = !!meta.cid; + if (getSettings().enableSignature) { + const signatureHtml = isUpdate + ? '
本文从 Obsidian 修改更新
' + : '
本文从 Obsidian 撰写发布
'; + finalContent = signatureHtml + "\n\n" + finalContent; + } + + const data: any = { + title: this.title, + text: "" + finalContent, + authorId: HttpUtils.getCurrentUserUid(), + mid: mid.join(","), + slug: this.slug || meta.slug || undefined, + originalTitle: originalTitle, + }; + if (meta.cid) data.cid = meta.cid; + + const response = await HttpUtils.post("/postArticle", data); + if (response.status !== "success") { + this.notice.hide(); + return; + } + + const savedCid = await this.resolveCid(response, meta.cid); + // 跳转链接:接口没给(或给的是占位符)就按 cid 再问一次 + const permalink = await this.resolvePermalink(response, savedCid); + + if (savedCid && filePath) { + const categoryNames = await this.getCategoryNamesByIds( + this.selectedCategories + ); + const tagNames = await this.getTagNamesByIds(this.selectedTags); + const file = this.app.vault.getFileByPath(filePath); + if (file) { + await writeTypechoMeta(this.app, file, { + cid: savedCid, + slug: this.slug, + url: permalink, + categories: categoryNames, + tags: tagNames, + title: syncedTitle, + // 首次发布就从现在算起;更新已有文章时沿用笔记里原来的发布时间 + created: meta.created || formatBeijingTime(), + }); + } + + if (this.baseFileName) { + getSettings().slugMapping[this.baseFileName] = this.slug; + await saveSettings(); + } + } + + this.notice.hide(); + new Notice( + `${isUpdate ? i18n.t("sync.updated") : i18n.t("sync.created")}${i18n.t("common.success")}` + ); + + // 发布后跳转到网站上的文章页(先打开再关弹窗,避免关窗后 + // 浏览器把这次 window.open 当成无用户操作的弹窗拦掉) + if (getSettings().openAfterPublish) { + if (permalink) { + this.openInBrowser(permalink); + } else { + new Notice( + i18n.t("sync.permalinkMissing", { + cid: savedCid ? String(savedCid) : "-", + }), + 8000 + ); + } + } + this.close(); + } catch (error) { + this.notice.hide(); + // HttpUtils 已经弹过具体原因(HTTP 500 / 接口不存在 / 服务器原文), + // 这里只在它没弹过时补一句,避免两条提示叠在一起互相盖住 + if (!(error as any)?.__notified) { + new Notice(`${i18n.t("sync.publish")} ${i18n.t("common.failed")}`); + } + console.error("publish failed:", error); + } + } + + /** + * 取本次发布后的真实 cid。 + * + * 新增文章时,后端 `insert()` 的返回值在部分 Typecho 版本下不是真实 cid + * (可能是个布尔值,转成数字就成了 1),只有更新分支才稳定返回 cid。 + * 所以新增时再用 slug 反查一次,以接口返回的真实 cid 为准。 + */ + private async resolveCid( + response: any, + fallback: number | null + ): Promise { + const cid = this.pickCid(response, fallback); + + const isAdd = response?.data?.type === "add"; + const slug = + typeof response?.data?.slug === "string" ? response.data.slug.trim() : ""; + if (!isAdd || !slug) return cid; + + try { + // silent = true:反查失败不打扰用户,沿用后端返回值即可 + const res = await HttpUtils.get( + `/post?slug=${encodeURIComponent(slug)}`, + undefined, + true + ); + const real = Number(res?.data?.cid); + if (Number.isFinite(real) && real > 0) return real; + } catch (error) { + console.warn("[typecho] 按 slug 反查 cid 失败,沿用后端返回值", error); + } + + return cid; + } + + private pickCid(response: any, fallback: number | null): number | null { + const candidates = [ + response?.data?.cid, + response?.data?.id, + typeof response?.data === "number" ? response.data : null, + response?.cid, + response?.id, + fallback, + ]; + for (const value of candidates) { + const cid = Number(value); + if (Number.isFinite(cid) && cid > 0) return cid; + } + return null; + } + + private pickPermalink(response: any): string { + const candidates = [ + response?.data?.permalink, + response?.data?.url, + response?.permalink, + response?.url, + ]; + for (const value of candidates) { + if (typeof value === "string" && value.trim() !== "") { + return value.trim(); + } + } + return ""; + } + + /** + * 取发布后的文章链接 + * + * 正常情况 /postArticle 会直接带回 permalink;但服务端路由参数不全时 + * 可能给空、给带占位符的地址,甚至只给相对路径。这里依次兜底: + * 接口返回值 → 按 cid 查一次 /post → 都拿不到就返回空串(由调用方提示) + */ + private async resolvePermalink( + response: any, + cid: number | null + ): Promise { + const direct = this.normalizeUrl(this.pickPermalink(response)); + if (direct) return direct; + + if (cid) { + try { + // silent = true:这里只是补链接,失败不该再弹一条错误 + const res = await HttpUtils.get( + `/post?cid=${cid}`, + undefined, + true + ); + const url = this.normalizeUrl( + this.pickPermalink(res) || + String((res as any)?.data?.permalink || "") + ); + if (url) return url; + } catch (error) { + console.warn("[typecho] 按 cid 获取文章链接失败", error); + } + } + + console.warn("[typecho] 发布成功但未取得文章链接", response); + return ""; + } + + /** + * 补成绝对地址 + * + * Typecho 某些固定链接配置下会返回 /archives/xx/ 这种相对路径, + * Electron 里的 window.open 会把相对路径当成本地文件,点了没反应。 + */ + private normalizeUrl(url: string): string { + const value = String(url || "").trim(); + if (!value || value === "#" || value.includes("{")) return ""; + if (/^https?:\/\//i.test(value)) return value; + + const root = Util.url.extractDomain(HttpUtils.getCurrentHost()); + if (!root) return ""; + const base = root.replace(/\/+$/, ""); + return base + (value.startsWith("/") ? value : "/" + value); + } + + /** + * 用系统浏览器打开链接(只打开一次)。 + * + * 关键:在 Obsidian/Electron 里 window.open() 返回 null 并不代表失败—— + * Obsidian 接管后用系统默认浏览器打开了页面,只是不返回 window 句柄。 + * 旧代码看到 null 就用隐藏 再点一次兜底,结果同一 + * 链接被打开两遍(两个浏览器窗口)。这里只调用一次 window.open,去掉 + * 双击兜底;真正被弹窗拦截的情况由调用方的 Notice 提示用户手动打开。 + */ + private openInBrowser(url: string) { + console.info("[typecho] 发布后打开文章页:", url); + + try { + window.open(url, "_blank"); + } catch (error) { + // 极少数环境下 window.open 直接抛错:这一种才用 兜底, + // 且仅当确实抛错,避免正常返回 null 时重复打开。 + console.warn("[typecho] window.open 抛错,改用链接点击", error); + const link = document.createElement("a"); + link.href = url; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + link.style.display = "none"; + document.body.appendChild(link); + link.click(); + link.remove(); + } + } + + /** + * 读取文件,设置内容 + * @param path 文件路径 + */ + async readFileAndSetContent(path: string) { + const file = this.app.vault.getFileByPath(path); + if (!file) { + new Notice(i18n.t("error.readFileError")); + return; + } + // 必须等读取完成再返回:early return 的写法会让调用方在 + // this.content 赋值之前就继续往下走(发布空内容 / 发错文件) + try { + this.content = await this.app.vault.cachedRead(file); + } catch (error) { + new Notice(i18n.t("error.readFileError")); + console.error("read note content failed:", error); + } + } + + async setTitleFromFileName(path = "", titleInput: HTMLInputElement) { + if (path) { + this.activeFilePath = path; + } + + const noteFile = this.app.vault.getFileByPath( + path != "" ? path : this.activeFilePath + ); + if (!noteFile) { + new Notice(i18n.t("error.readFileError")); + return; + } + this.baseFileName = noteFile.basename; + + let cleanTitle = ""; + + try { + const content = await this.app.vault.read(noteFile); + const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/); + if (fmMatch) { + const titleMatch = fmMatch[1].match(/title:\s*(.+)/); + if (titleMatch) { + cleanTitle = titleMatch[1] + .trim() + .replace(VERSION_SUFFIX, "") + .replace(RENAME_PREFIX, "") + .trim(); + } + } + } catch (e) { + console.error("read note content failed:", e); + } + + if (!cleanTitle) { + cleanTitle = noteFile.basename + .replace(VERSION_SUFFIX, "") + .replace(RENAME_PREFIX, "") + .trim(); + } + + this.title = cleanTitle; + if (titleInput) { + titleInput.value = this.title; + } + + await this.restoreSlug(); + await this.restoreSelection(); + } + + /** + * 恢复别名:优先笔记属性,其次是插件里保存的映射 + */ + private async restoreSlug() { + const meta = await readTypechoMetaFresh(this.app, this.activeFilePath); + let savedSlug = meta.slug; + + if (!savedSlug) { + savedSlug = getSettings().slugMapping[this.baseFileName]; + } + + this.slug = + savedSlug || "obsidian-" + Util.hash.simpleHash(this.baseFileName); + + if (this.slugInput) { + this.slugInput.value = this.slug; + } + } + + /** + * 按笔记属性里记录的分类 / 标签,恢复勾选状态。 + * + * 匹配策略:mid(发布回写的是名称,但旧笔记可能存 ID)→ 名称 → slug, + * 名称和 slug 都忽略大小写与空白差异;服务端 mid 有时是数字有时是字符串, + * 这里统一存成字符串,避免复选框的 includes(mid) 因类型不同永远 false。 + */ + private async restoreSelection() { + // 关键:不能只信 this.activeFilePath 一个来源。 + // 多窗口下它可能被冻结到另一篇笔记;刚发布回写后 metadataCache / + // cachedRead 也可能还是旧值。这里按多个候选路径重读,取第一个 + // 真正读到 ty-categories / ty-tags 的 meta,作为回填依据。 + const candidatePaths: string[] = []; + if (this.activeFilePath) candidatePaths.push(this.activeFilePath); + const activePath = this.app.workspace.getActiveFile()?.path; + if (activePath && !candidatePaths.includes(activePath)) { + candidatePaths.push(activePath); + } + + let meta = await readTypechoMetaFresh(this.app, this.activeFilePath); + for (const path of candidatePaths) { + const attempt = await readTypechoMetaFresh(this.app, path); + if (attempt.categories.length > 0 || attempt.tags.length > 0) { + meta = attempt; + // 同步修正路径:后续发布写回必须落在真正读到的这篇笔记上 + this.activeFilePath = path; + break; + } + } + + // 关键兜底:发布时写回的是「发布框里的勾选」,而勾选又来自笔记属性。 + // 一旦某次没勾上(或老笔记压根没写回),就会陷入 + // 「读不到 → 不勾选 → 写回空 → 更读不到」的死循环。 + // 服务端其实一直记着这篇文章的分类/标签:/postDetail 会返回 + // categoryNames / tagNames。笔记缺属性时按 cid(或 slug)问一次线上。 + if ( + meta.categories.length === 0 && + meta.tags.length === 0 && + (meta.cid || meta.slug) + ) { + try { + const lookup = meta.cid + ? `cid=${encodeURIComponent(String(meta.cid))}` + : `slug=${encodeURIComponent(meta.slug || "")}`; + // silent=true:老站点可能没有这个接口,可选兜底不该弹错误打扰 + const res = await HttpUtils.get( + `/postDetail?${lookup}`, + undefined, + true + ); + const post: any = res && (res as any).data; + // 多站点下 cid 可能撞到另一篇文章;slug / 标题至少一样才敢用。 + // 宁可不勾,也不能把别的文章的分类标签勾到这篇上。 + const sameSlug = + !!meta.slug && + !!post?.slug && + String(post.slug) === String(meta.slug); + const sameTitle = + !!meta.title && + !!post?.title && + String(post.title) === String(meta.title); + if (post && (sameSlug || sameTitle)) { + const toNames = (value: unknown): string[] => { + if (!Array.isArray(value)) return []; + return value + .map((item: any) => + String( + item && typeof item === "object" + ? item.name ?? "" + : item ?? "" + ).trim() + ) + .filter((name) => name !== ""); + }; + const categories = toNames(post.categoryNames ?? post.categories); + const tags = toNames(post.tagNames ?? post.tags); + if (categories.length > 0 || tags.length > 0) { + meta = { ...meta, categories, tags }; + console.info("[typecho] 已从线上文章补回分类/标签", { + 笔记路径: this.activeFilePath, + 分类: categories, + 标签: tags, + }); + } + } + } catch (error) { + // 可选兜底失败不影响主流程(HttpUtils 已 silent,不会再弹提示) + console.warn("[typecho] 线上文章分类/标签兜底查询失败", error); + } + } + + // 注意:即使笔记没有分类/标签属性,也要重新拉列表渲染—— + // 切换网站时列表内容是新的,不能因为有属性缺失就整段跳过。 + + const categoriesData = await HttpUtils.get("/categories"); + const allCategories = categoriesData.data || []; + const tagsData = await HttpUtils.get("/tags"); + const allTags = tagsData.data || []; + + const normalize = (value: unknown) => + String(value ?? "") + .trim() + .replace(/\s+/g, "") + .toLowerCase(); + const findMid = (list: any[], value: string): string | undefined => { + const key = String(value ?? "").trim(); + if (!key) return undefined; + const hit = list.find( + (item: any) => + String(item.mid ?? "") === key || + normalize(item.name) === normalize(key) || + normalize(item.slug) === normalize(key) + ); + return hit ? String(hit.mid) : undefined; + }; + + this.selectedCategories = Array.from( + new Set( + meta.categories + .map((name) => findMid(allCategories, name)) + .filter((mid): mid is string => !!mid) + ) + ); + this.selectedTags = Array.from( + new Set( + meta.tags + .map((name) => findMid(allTags, name)) + .filter((mid): mid is string => !!mid) + ) + ); + + await this.getCategories(this.contentEl, true); + await this.getTags(this.contentEl, true); + + // 诊断日志:回填失败时把「读到的属性 / 拉到的选项 / 匹配结果」一次性 + // 打到控制台,避免只靠猜。正常勾上时不打扰。 + const hasMeta = meta.categories.length > 0 || meta.tags.length > 0; + if (hasMeta) { + console.info("[typecho] 回填诊断", { + 笔记路径: this.activeFilePath, + 笔记分类: meta.categories, + 笔记标签: meta.tags, + 站点分类数: allCategories.length, + 站点标签数: allTags.length, + 匹配到分类: this.selectedCategories, + 匹配到标签: this.selectedTags, + }); + } + + // 有属性却一个都没勾上:把「读到的属性」直接显示出来,方便一眼定位是 + // 站点选错还是属性为空。以前只提示「没找到同名项」,看不到读到了什么。 + if ( + hasMeta && + this.selectedCategories.length === 0 && + this.selectedTags.length === 0 + ) { + new Notice( + `笔记分类[${meta.categories.join("/")}]、标签[${meta.tags.join("/")}]在当前网站没找到同名项。若刚切换过网站请重开发布框;否则检查上方网站是否正确。`, + 10000 + ); + } else if (!hasMeta) { + // 读不到属性时也要留痕:区分「这篇笔记没发布过」和「读错了文件」 + console.warn("[typecho] 回填时未读到分类/标签属性", { + 笔记路径: this.activeFilePath, + 候选路径: candidatePaths, + }); + } + } + + private async getSelectedFilePath(): Promise { + const activeFile = this.app.workspace.getActiveFile(); + return activeFile ? activeFile.path : ""; + } + + /** + * 打开「添加分类 / 标签」弹窗 + */ + private openAddMeta(type: "tag" | "category") { + const refresh = async () => { + // preserveSelection=true:新增分类/标签后刷新列表,别把已勾选项清掉 + if (type === "tag") { + await this.getTags(this.contentEl, true); + } else { + await this.getCategories(this.contentEl, true); + } + }; + new addMetas(this.app, type, refresh).open(); + } + + private toggleSelection(list: string[], mid: string, checked: boolean) { + // 服务端 mid 可能是数字,回填时已统一成字符串;点击时同样归一化 + const id = String(mid); + if (checked) { + if (!list.includes(id)) list.push(id); + } else { + const index = list.indexOf(id); + if (index > -1) list.splice(index, 1); + } + } + + async getCategories(contentEl: HTMLElement, preserveSelection = false) { + if (!this.categoriesDom) { + this.categoriesDom = contentEl.createDiv({ + attr: { style: "margin-bottom: 15px;" }, + }); + } + while (this.categoriesDom.firstChild) { + this.categoriesDom.removeChild(this.categoriesDom.firstChild); + } + if (!preserveSelection) { + this.selectedCategories = []; + } + + const notice = new Notice( + `${i18n.t("common.get")}${i18n.t("field.category")}...` + ); + try { + const categoriesResponse = await HttpUtils.get("/categories"); + renderCategoryPanel( + this.categoriesDom, + categoriesResponse.data || [], + { + title: i18n.t("field.category"), + emptyText: i18n.t("sync.noCategories"), + addText: i18n.t("common.add"), + isSelected: (mid) => this.selectedCategories.includes(String(mid)), + onToggle: (mid, checked) => + this.toggleSelection(this.selectedCategories, mid, checked), + onAdd: () => this.openAddMeta("category"), + } + ); + } finally { + notice.hide(); + } + } + + async getTags(contentEl: HTMLElement, preserveSelection = false) { + if (!this.tagsDom) { + this.tagsDom = contentEl.createDiv({ + attr: { style: "margin-bottom: 15px;" }, + }); + } + while (this.tagsDom.firstChild) { + this.tagsDom.removeChild(this.tagsDom.firstChild); + } + if (!preserveSelection) { + this.selectedTags = []; + } + + const notice = new Notice( + `${i18n.t("common.get")}${i18n.t("field.tag")}...` + ); + try { + const tagsResponse = await HttpUtils.get("/tags"); + renderTagPanel(this.tagsDom, tagsResponse.data || [], { + title: i18n.t("field.tag"), + emptyText: i18n.t("sync.noTags"), + addText: i18n.t("common.add"), + // 标签通常成百上千个,开搜索框按模糊匹配筛 + searchable: true, + searchPlaceholder: i18n.t("sync.tagSearchPlaceholder"), + noMatchText: i18n.t("sync.tagSearchNoMatch"), + selectionText: (selected, total) => + i18n.t("sync.tagSelectedCount", { + selected: String(selected), + total: String(total), + }), + moreText: (rest) => + i18n.t("sync.tagSearchMore", { count: rest }), + isSelected: (mid) => this.selectedTags.includes(String(mid)), + onToggle: (mid, checked) => + this.toggleSelection(this.selectedTags, mid, checked), + onAdd: () => this.openAddMeta("tag"), + }); + } finally { + notice.hide(); + } + } + + /** + * 根据分类 ID 列表获取分类名称列表 + */ + private async getCategoryNamesByIds(ids: string[]): Promise { + const response = await HttpUtils.get("/categories"); + const categories = response.data || []; + const names: string[] = []; + for (const id of ids) { + const category = categories.find((c: any) => c.mid == id); + if (category) names.push(category.name); + } + return names; + } + + /** + * 根据标签 ID 列表获取标签名称列表 + */ + private async getTagNamesByIds(ids: string[]): Promise { + const response = await HttpUtils.get("/tags"); + const tags = response.data || []; + const names: string[] = []; + for (const id of ids) { + const tag = tags.find((t: any) => t.mid == id); + if (tag) names.push(tag.name); + } + return names; + } + + onClose() { + this.contentEl.empty(); + } +} diff --git a/view/site_manager.ts b/view/site_manager.ts new file mode 100644 index 0000000..bd5fa5e --- /dev/null +++ b/view/site_manager.ts @@ -0,0 +1,1562 @@ +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(); + private tabCountEls = new Map(); + private panels = new Map(); + 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(); + list.forEach((item) => byId.set(Number(item.mid), item)); + + const depthOf = (item: any, seen: Set): 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(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 = { + 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(); + } +}