同步插件源代码并补齐标准项目文件
This commit is contained in:
29
.gitignore
vendored
Normal file
29
.gitignore
vendored
Normal file
@@ -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
|
||||
7
CHANGELOG.md
Normal file
7
CHANGELOG.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# 变更记录
|
||||
|
||||
## 2026-11-26 · 初始同步
|
||||
|
||||
- 同步插件源代码到新 Gitea 仓库。
|
||||
- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。
|
||||
- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。
|
||||
19
CONTRIBUTING.md
Normal file
19
CONTRIBUTING.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# 贡献指南
|
||||
|
||||
欢迎对本插件提出改进建议或提交代码。
|
||||
|
||||
## 提交前检查
|
||||
|
||||
- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。
|
||||
- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。
|
||||
- 涉及对外服务或凭据的配置不要写入代码或文档。
|
||||
|
||||
## 提交流程
|
||||
|
||||
1. Fork 仓库并创建功能分支。
|
||||
2. 完成修改后提交 Pull Request,说明改动目的与影响范围。
|
||||
3. 重要功能变更请同步更新 `CHANGELOG.md`。
|
||||
|
||||
## 问题反馈
|
||||
|
||||
请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -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.
|
||||
35
README.md
35
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` 及源码目录放入 `<Vault>/.obsidian/plugins/<插件 id>/`。
|
||||
3. 在 Obsidian「设置 → 第三方插件」中启用该插件。
|
||||
|
||||
## 开发与贡献
|
||||
|
||||
详见 [CONTRIBUTING.md](CONTRIBUTING.md)。
|
||||
|
||||
## 授权
|
||||
|
||||
授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。
|
||||
|
||||
## 变更记录
|
||||
|
||||
详见 [CHANGELOG.md](CHANGELOG.md)。
|
||||
|
||||
217
locales/en.json
Normal file
217
locales/en.json
Normal file
@@ -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}"
|
||||
}
|
||||
}
|
||||
217
locales/zh.json
Normal file
217
locales/zh.json
Normal file
@@ -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}"
|
||||
}
|
||||
}
|
||||
250
main.ts
Normal file
250
main.ts
Normal file
@@ -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",
|
||||
`<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1745386247342" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1491" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M517.04420574 882.47531656c-289.98573089 0-391.40007045-98.3302631-391.40007043-379.40894092 0-281.09368555 101.41433957-379.39393331 391.40007043-379.39393327 289.98573089 0 391.40007045 98.3002478 391.40007044 379.39393327 0 281.07867783-101.41433957 379.40143714-391.40007044 379.40143709zM306.28397227 386.32169964h421.50545924v-58.3648341H306.28397227v58.37233801z m0 145.92709302h301.07640006V473.8914624H306.28397227v58.36483409z m0 145.92709298h361.28717777v-58.37233793H306.2914761v58.37233793z" p-id="1492"></path></svg>`
|
||||
);
|
||||
|
||||
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<void>;
|
||||
autoRefresh?: () => Promise<void>;
|
||||
};
|
||||
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<boolean> {
|
||||
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<void> {
|
||||
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<SiteConfig>): Promise<boolean> {
|
||||
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<boolean> {
|
||||
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;
|
||||
}
|
||||
9
manifest.json
Normal file
9
manifest.json
Normal file
@@ -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
|
||||
}
|
||||
54
setting/plugin_settings.ts
Normal file
54
setting/plugin_settings.ts
Normal file
@@ -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<string, string>; // 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: "" },
|
||||
};
|
||||
}
|
||||
376
setting/setting_tab.ts
Normal file
376
setting/setting_tab.ts
Normal file
File diff suppressed because it is too large
Load Diff
1288
styles.css
Normal file
1288
styles.css
Normal file
File diff suppressed because it is too large
Load Diff
41
utils/datetime.ts
Normal file
41
utils/datetime.ts
Normal file
@@ -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}`;
|
||||
}
|
||||
366
utils/frontmatter.ts
Normal file
366
utils/frontmatter.ts
Normal file
File diff suppressed because it is too large
Load Diff
21
utils/i18n.ts
Normal file
21
utils/i18n.ts
Normal file
@@ -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;
|
||||
247
utils/post_import.ts
Normal file
247
utils/post_import.ts
Normal file
@@ -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<void> {
|
||||
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<TFile | null> {
|
||||
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<TFile | null> {
|
||||
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;
|
||||
}
|
||||
223
utils/request.ts
Normal file
223
utils/request.ts
Normal file
@@ -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<string, string>,
|
||||
silent = false
|
||||
): Promise<ResponseType> {
|
||||
return this.request("GET", url, undefined, headers, silent);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起 POST 请求
|
||||
*/
|
||||
public static async post(
|
||||
url: string,
|
||||
body: any,
|
||||
headers?: Record<string, string>
|
||||
): Promise<ResponseType> {
|
||||
return this.request("POST", url, body, headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起通用 HTTP 请求
|
||||
*/
|
||||
private static async request(
|
||||
method: string,
|
||||
url: string,
|
||||
body?: any,
|
||||
headers?: Record<string, string>,
|
||||
silent = false
|
||||
): Promise<ResponseType> {
|
||||
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),
|
||||
// 直接把 "<pre><code>" 丢给 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(/<script[\s\S]*?<\/script>/gi, " ")
|
||||
.replace(/<style[\s\S]*?<\/style>/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);
|
||||
}
|
||||
}
|
||||
5
utils/response_type.ts
Normal file
5
utils/response_type.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export interface ResponseType {
|
||||
status: string;
|
||||
message: string;
|
||||
data: any;
|
||||
}
|
||||
276
utils/util.ts
Normal file
276
utils/util.ts
Normal file
@@ -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 <T extends Record<string, any>>(
|
||||
data: T[],
|
||||
nodeId: keyof T,
|
||||
parentNodeKey: keyof T
|
||||
): TreeNode[] {
|
||||
// 将数据存储为以 nodeId 为 KEY 的 map 索引数据列
|
||||
const map: Record<string | number, TreeNode> = {};
|
||||
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<boolean> {
|
||||
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]] 或 
|
||||
try {
|
||||
const cursor = editor.getCursor();
|
||||
const line = editor.getLine(cursor.line);
|
||||
// 构造可能的原生粘贴内容(Obsidian 偏好双括号)
|
||||
const nativeEmbed1 = `![[${blob.name}]]`;
|
||||
const nativeEmbed2 = ``;
|
||||
const nativeEmbed3 = ``; // 少数情况
|
||||
|
||||
// 从光标位置往前找(原生粘贴通常在当前光标处插入)
|
||||
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 = ``;
|
||||
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;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
81
view/add_metasl.ts
Normal file
81
view/add_metasl.ts
Normal file
@@ -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<void>;
|
||||
/** 正在提交:防止连按回车重复新建同名分类/标签 */
|
||||
private submitting = false;
|
||||
constructor(app: App, type: string, fun: () => Promise<void>) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
38
view/article_preview.ts
Normal file
38
view/article_preview.ts
Normal file
@@ -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 时间匹配
|
||||
}
|
||||
}
|
||||
878
view/article_type.ts
Normal file
878
view/article_type.ts
Normal file
File diff suppressed because it is too large
Load Diff
192
view/browse_articles.ts
Normal file
192
view/browse_articles.ts
Normal file
@@ -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();
|
||||
}
|
||||
}
|
||||
520
view/category_tree.ts
Normal file
520
view/category_tree.ts
Normal file
File diff suppressed because it is too large
Load Diff
133
view/comment_modal.ts
Normal file
133
view/comment_modal.ts
Normal file
@@ -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> | 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> | void;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
titleText: string,
|
||||
message: string,
|
||||
onConfirm: () => Promise<void> | 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();
|
||||
}
|
||||
}
|
||||
182
view/meta_edit_modal.ts
Normal file
182
view/meta_edit_modal.ts
Normal file
@@ -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<void>;
|
||||
|
||||
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<void>
|
||||
) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
943
view/push.ts
Normal file
943
view/push.ts
Normal file
File diff suppressed because it is too large
Load Diff
1562
view/site_manager.ts
Normal file
1562
view/site_manager.ts
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user