From 957df501f0a5d5cd2808888bfc42efc6bcef6bbd Mon Sep 17 00:00:00 2001 From: XIGE <710062962@qq.com> Date: Thu, 26 Nov 2026 15:04:39 +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 | 73 ++ README.md | 31 +- main.ts | 3282 +++++++++++++++++++++++++++++++++++++++++++++++ manifest.json | 10 + styles.css | 1767 +++++++++++++++++++++++++ 8 files changed, 5217 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 main.ts create mode 100644 manifest.json create mode 100644 styles.css 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..2f87fa5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright 2026 GI-OBSIDIAN + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md index e5407d0..af6af35 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,31 @@ -# Memos +# Memos Manager +> 仓库:`Memos` · 类型:Obsidian 插件 · 版本:`1.9.5` · 作者:XIGE + +在 Obsidian 边栏中管理 Memos:发布、批量图片上传、待办勾选、搜索筛选、引用与编辑、置顶、插入笔记。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `main.ts` +- `manifest.json` +- `styles.css` + +## 安装与使用 + +1. 本仓库仅包含插件源代码,未包含依赖与构建工具;请先按 Obsidian 插件标准流程构建生成 `main.js`。 +2. 将 `manifest.json`、构建后的 `main.js`、`styles.css` 及源码目录放入 `/.obsidian/plugins/<插件 id>/`。 +3. 在 Obsidian「设置 → 第三方插件」中启用该插件。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(Apache License 2.0)。第三方组件版权归各自作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/main.ts b/main.ts new file mode 100644 index 0000000..b2973e5 --- /dev/null +++ b/main.ts @@ -0,0 +1,3282 @@ +import { + App, + Component, + ItemView, + MarkdownRenderer, + MarkdownView, + Modal, + Notice, + Plugin, + PluginSettingTab, + RequestUrlParam, + Setting, + WorkspaceLeaf, + getIcon, + requestUrl, + setIcon, +} from 'obsidian'; + +// ============================================================ +// 常量 +// ============================================================ + +const VIEW_TYPE_MEMOS = 'memos-sidebar-view'; +const DRAFT_KEY = 'memos-plugin-draft'; +const DRAFT_REFS_KEY = 'memos-plugin-draft-refs'; +const MAX_COMPOSER_HEIGHT = 240; + +// ============================================================ +// 类型 +// ============================================================ + +type MemoVisibility = 'PRIVATE' | 'PUBLIC' | 'PROTECTED'; + +interface MemosPluginSettings { + serverUrl: string; + apiToken: string; + pageSize: number; + defaultVisibility: MemoVisibility; + showImages: boolean; + autoLoadMore: boolean; + showTags: boolean; + debug: boolean; +} + +interface MemoResource { + id?: number | string; + filename?: string; + externalLink?: string; + type?: string; + size?: number; +} + +/** Memos 的 MemoRelation:网页端那条「🔗 #612 正文」的小卡片就是它渲染的 */ +interface MemoRelation { + memoId?: number | string; + relatedMemoId?: number | string; + type?: string; +} + +interface Memo { + id: number | string; + content: string; + visibility?: MemoVisibility; + pinned?: boolean; + // v0.18.x + createdTs?: number; + updatedTs?: number; + displayTs?: number; + resourceList?: MemoResource[]; + relationList?: MemoRelation[]; + // 旧版 / 新版服务端字段 + createTime?: string; + updateTime?: string; + displayTime?: string; +} + +interface MemoListPage { + memos: Memo[]; + nextPageToken?: string; + hasMore: boolean; +} + +interface StatusResponse { + profile?: { version?: string; mode?: string }; + host?: { username?: string }; +} + +interface MeResponse { + nickname?: string; + username?: string; + avatarUrl?: string; +} + +const DEFAULT_SETTINGS: MemosPluginSettings = { + serverUrl: 'https://me.sangushui.com', + apiToken: '', + pageSize: 20, + defaultVisibility: 'PUBLIC', + showImages: true, + autoLoadMore: true, + showTags: true, + debug: false, +}; + +// ============================================================ +// 工具函数 +// ============================================================ + +function pad2(n: number): string { + return n < 10 ? '0' + n : String(n); +} + +/** 取 Memo 的显示时间戳(秒) */ +function memoTime(memo: Memo): number { + if (typeof memo.displayTs === 'number' && memo.displayTs > 0) return memo.displayTs; + if (typeof memo.createdTs === 'number' && memo.createdTs > 0) return memo.createdTs; + const iso = memo.createTime || memo.displayTime; + if (iso) { + const t = Date.parse(iso); + if (!isNaN(t)) return Math.floor(t / 1000); + } + return 0; +} + +/** 是否被编辑过(更新晚于创建 1 分钟以上) */ +function isEdited(memo: Memo): boolean { + const created = memo.createdTs || 0; + const updated = memo.updatedTs || 0; + return updated > 0 && created > 0 && updated - created > 60; +} + +function formatAbsolute(seconds: number): string { + if (!seconds) return '未知时间'; + const d = new Date(seconds * 1000); + return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; +} + +function formatRelative(seconds: number): string { + if (!seconds) return '未知时间'; + const now = Date.now() / 1000; + const diff = now - seconds; + + if (diff < 60) return '刚刚'; + if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`; + if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`; + + const d = new Date(seconds * 1000); + const nowDate = new Date(); + const sameYear = d.getFullYear() === nowDate.getFullYear(); + const yesterday = new Date(nowDate.getTime() - 86400000); + + if (d.getFullYear() === yesterday.getFullYear() + && d.getMonth() === yesterday.getMonth() + && d.getDate() === yesterday.getDate()) { + return `昨天 ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; + } + if (sameYear) { + return `${d.getMonth() + 1}月${d.getDate()}日 ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; + } + return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`; +} + +/** 提取正文中的 #标签 */ +function extractTags(content: string): string[] { + const out: string[] = []; + const re = /(^|[\s((])#([^\s#()(),,。;;::!!??]+)/g; + let m: RegExpExecArray | null; + while ((m = re.exec(content || '')) !== null) { + const tag = m[2]; + if (tag && out.indexOf(tag) === -1) out.push(tag); + } + return out; +} + +/** 排序:置顶优先,其次按时间倒序 */ +function sortMemos(list: Memo[]): Memo[] { + return list.slice().sort((a, b) => { + const pa = a.pinned ? 1 : 0; + const pb = b.pinned ? 1 : 0; + if (pa !== pb) return pb - pa; + return memoTime(b) - memoTime(a); + }); +} + +function mergeUnique(base: Memo[], incoming: Memo[]): Memo[] { + const seen: Record = {}; + const out: Memo[] = []; + const push = (m: Memo) => { + const key = String(m.id); + if (seen[key]) return; + seen[key] = true; + out.push(m); + }; + base.forEach(push); + incoming.forEach(push); + return out; +} + +/** 把 Memos 的 HTML 片段 / 相对资源路径整理成 Obsidian 可渲染的 Markdown */ +function normalizeContent(content: string, serverUrl: string): string { + let out = content || ''; + + // 相对资源路径补全为绝对地址(v0.18 的 /o/r/、/assets/) + const base = serverUrl.replace(/\/+$/, ''); + out = out.replace(/\]\((\/(?:o\/r|assets)\/[^)\s]+)\)/g, (_m, p: string) => `](${base}${p})`); + + // -> Markdown + out = out.replace(/]*>/gi, (tag) => { + const srcMatch = tag.match(/src=["']([^"']+)["']/i); + if (!srcMatch) return ''; + const altMatch = tag.match(/alt=["']([^"']*)["']/i); + const alt = altMatch ? altMatch[1] : '图片'; + return `![${alt}](${srcMatch[1]})`; + }); + + out = out.replace(//gi, '\n'); + out = out.replace(/ /g, ' '); + out = out.replace(/

\s*/gi, '').replace(/\s*<\/p>/gi, '\n'); + return out.trim(); +} + +/** 纯文本摘要,用于预览列表 */ +function stripForPreview(content: string): string { + return normalizeContent(content || '', '') + .replace(/!\[[^\]]*\]\([^)]*\)/g, '') + .replace(/[*_`~>#]/g, '') + .replace(/\s+/g, ' ') + .trim(); +} + +/** Memo 的网页端链接 */ +function memoUrl(memo: Memo, serverUrl: string): string { + const base = (serverUrl || '').replace(/\/+$/, ''); + return `${base}/m/${memo.id}`; +} + +/** 把 Memo 转成可插入笔记的 Markdown */ +function memoToMarkdown(memo: Memo, serverUrl: string): string { + const content = normalizeContent(memo.content, serverUrl).trim(); + const parts: string[] = []; + if (content) parts.push(content); + + const images = (memo.resourceList || []).filter( + (r) => !!r.externalLink && !!r.type && r.type.indexOf('image/') === 0 + ); + if (images.length) { + parts.push(images.map((r) => `![${r.filename || '图片'}](${r.externalLink})`).join('\n')); + } + + const time = formatAbsolute(memoTime(memo)); + parts.push(`> 🗒️ 来自 Memos · ${time}`); + return parts.join('\n\n') + '\n'; +} + +/** 链接文本里的方括号会截断 Markdown 链接,需要转义 */ +function escapeLinkText(text: string): string { + return text.replace(/\[/g, '\\[').replace(/\]/g, '\\]'); +} + +/** + * 被引用 Memo 的「标题」:网页端 chip 里显示的就是被引用 Memo 的正文, + * 这里取纯文本(去掉图片、Markdown 标记),过长截断。 + */ +function memoReferenceTitle(memo: Memo, max = 90): string { + const raw = stripForPreview(memo.content || '').replace(/\s+/g, ' ').trim(); + if (!raw) return '(无正文)'; + return raw.length > max ? raw.slice(0, max).trimEnd() + '…' : raw; +} + +const REFERENCE_TYPE = 'REFERENCE'; + +/** + * 取出「本条 Memo 引用了谁」——网页端下方那排 chip 的数据源。 + * 服务端返回的 relationList 是双向的(别人引用本条也会出现), + * 这里只保留 memoId === 本条 id 的出向引用。 + */ +function outgoingReferenceIds(memo: Memo): string[] { + const self = String(memo.id); + const out: string[] = []; + for (const rel of memo.relationList || []) { + if (!rel || rel.type !== REFERENCE_TYPE) continue; + if (rel.memoId !== undefined && rel.memoId !== null && String(rel.memoId) !== self) continue; + if (rel.relatedMemoId === undefined || rel.relatedMemoId === null) continue; + + const id = String(rel.relatedMemoId); + if (!id || id === '0' || id === self) continue; + if (out.indexOf(id) === -1) out.push(id); + } + return out; +} + +/** + * 引用写进笔记时的文本形态(笔记里没有 chip,只能退化成一行链接): + * `🔗 [#612 正文摘要](原贴地址)` + */ +function memoToQuote(memo: Memo, serverUrl: string): string { + const title = escapeLinkText(`🔗 #${memo.id} ${memoReferenceTitle(memo)}`); + return `[${title}](${memoUrl(memo, serverUrl)})\n`; +} + +/** + * 画一个和网页端一样的引用卡片(对应网页端的 + * `…#612正文`): + * 链接图标 + `#ID` + 正文摘要,可点则整块是 A 标签。 + */ +function buildRefChip( + parent: HTMLElement, + opts: { id: string; title: string; href?: string; extraClass?: string; onRemove?: () => void } +): { chip: HTMLElement; titleEl: HTMLElement } { + const cls = 'memo-ref' + (opts.extraClass ? ' ' + opts.extraClass : ''); + const chip = parent.createEl(opts.href ? 'a' : 'span', { cls }); + + if (opts.href) { + chip.setAttribute('href', opts.href); + chip.setAttribute('target', '_blank'); + chip.setAttribute('rel', 'noopener'); + chip.addEventListener('click', (e) => e.stopPropagation()); + } + chip.setAttribute('title', opts.title ? `#${opts.id} ${opts.title}` : `#${opts.id}`); + + const icon = chip.createSpan({ cls: 'memo-ref-icon' }); + setIcon(icon, 'link'); + chip.createSpan({ cls: 'memo-ref-id', text: `#${opts.id}` }); + const titleEl = chip.createSpan({ cls: 'memo-ref-title', text: opts.title || '…' }); + + if (opts.onRemove) { + const remove = chip.createEl('button', { + cls: 'memo-ref-remove', + attr: { type: 'button', 'aria-label': `取消引用 #${opts.id}` }, + }); + setIcon(remove, 'x'); + remove.addEventListener('click', (e) => { + e.preventDefault(); + e.stopPropagation(); + opts.onRemove?.(); + }); + } + + return { chip, titleEl }; +} + +// ============================================================ +// 待办事项(Memos 的 - [ ] / - [x] 任务列表) +// ============================================================ + +/** 待办行的前缀:缩进 + 列表符号 + `[ ]` */ +const TASK_LINE_RE = /^(\s*(?:[-*+]|\d+[.)])\s+\[)([ xX])(\])/; + +/** 把第 ordinal 个待办行设成指定状态(与渲染出的顺序一一对应),返回新正文 */ +function setTaskLine(content: string, ordinal: number, done: boolean): string | null { + const lines = String(content || '').split('\n'); + let index = -1; + for (let i = 0; i < lines.length; i++) { + if (!TASK_LINE_RE.test(lines[i])) continue; + index++; + if (index !== ordinal) continue; + + lines[i] = lines[i].replace( + TASK_LINE_RE, + (_m, head: string, _state: string, tail: string) => `${head}${done ? 'x' : ' '}${tail}` + ); + return lines.join('\n'); + } + return null; +} + +/** + * 给光标所在行(或选中的每一行)加上待办标记: + * 普通文本 → `- [ ] 文本`;普通列表项 → `- [ ] 内容`;空行 → 空待办。 + */ +function applyTaskPrefix(value: string, start: number, end: number): { value: string; caret: number } { + const lineStart = value.lastIndexOf('\n', Math.max(0, start - 1)) + 1; + let lineEnd = value.indexOf('\n', end); + if (lineEnd === -1) lineEnd = value.length; + + const block = value.slice(lineStart, lineEnd); + const out = block.split('\n').map((line) => { + if (TASK_LINE_RE.test(line)) return line; + if (!line.trim()) return '- [ ] '; + const list = line.match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/); + if (list) return `${list[1]}- [ ] ${list[3]}`; + return `- [ ] ${line}`; + }); + + const replaced = out.join('\n'); + return { + value: value.slice(0, lineStart) + replaced + value.slice(lineEnd), + caret: lineStart + replaced.length, + }; +} + +/** + * 找到要插入的笔记。 + * 旧实现只看 getActiveViewOfType(MarkdownView),而点边栏按钮时「当前活动视图」 + * 是 Memos 边栏本身,于是明明开着笔记也报「请先打开一个笔记」。 + * 这里依次回退:活动视图 → 最近使用的 leaf → 任意一个 markdown leaf。 + */ +function findTargetMarkdownView(app: App): MarkdownView | null { + const active = app.workspace.getActiveViewOfType(MarkdownView); + if (active) return active; + + const recent = app.workspace.getMostRecentLeaf(); + if (recent && recent.view instanceof MarkdownView) return recent.view; + + for (const leaf of app.workspace.getLeavesOfType('markdown')) { + if (leaf.view instanceof MarkdownView) return leaf.view; + } + return null; +} + +/** 在目标笔记光标处插入 Markdown;没有笔记时返回 ok:false */ +function insertIntoNote(app: App, markdown: string): { ok: boolean; note?: string } { + const view = findTargetMarkdownView(app); + if (!view) return { ok: false }; + const editor = view.editor; + const cursor = editor.getCursor(); + editor.replaceSelection((cursor.ch > 0 ? '\n\n' : '') + markdown); + return { ok: true, note: view.file ? view.file.basename : '当前笔记' }; +} + +function debounce void>(fn: T, wait: number): T { + let timer: number | null = null; + return function (this: unknown, ...args: never[]) { + if (timer !== null) window.clearTimeout(timer); + timer = window.setTimeout(() => { + timer = null; + fn.apply(this, args); + }, wait); + } as T; +} + +// ============================================================ +// 图片附件托盘(粘贴 / 拖拽上传) +// ============================================================ + +class AttachmentTray { + resources: MemoResource[] = []; + private uploading = 0; + private container: HTMLElement; + private plugin: MemosPlugin; + private onChange: () => void; + + constructor(container: HTMLElement, plugin: MemosPlugin, onChange: () => void) { + this.container = container; + this.plugin = plugin; + this.onChange = onChange; + } + + /** 已上传成功的资源 id,用于创建 Memo 时的 resourceIdList */ + get ids(): number[] { + const out: number[] = []; + for (const r of this.resources) { + if (typeof r.id === 'number') out.push(r.id); + } + return out; + } + + get busy(): boolean { + return this.uploading > 0; + } + + get count(): number { + return this.resources.length + this.uploading; + } + + async add(files: File[]): Promise { + const images: File[] = []; + let skipped = 0; + for (const f of files) { + if (f.type.indexOf('image/') === 0) images.push(f); + else skipped++; + } + + if (skipped) new Notice(`已跳过 ${skipped} 个非图片文件`); + if (!images.length) { + if (!skipped) new Notice('没有可上传的文件'); + return; + } + + // 一次批量上传,3 路并发;上传中的占位块数量 = 剩余未完成任务数 + this.uploading += images.length; + this.render(); + + const queue = images.slice(); + const worker = async () => { + while (queue.length) { + const file = queue.shift(); + if (!file) break; + try { + const res = await this.plugin.api.uploadResource(file); + this.resources.push(res); + } catch (e) { + new Notice(`❌ ${file.name || '图片'} 上传失败:` + (e as Error).message, 6000); + } finally { + this.uploading = Math.max(0, this.uploading - 1); + this.render(); + } + } + }; + + const lanes = Math.min(3, images.length); + const tasks: Promise[] = []; + for (let i = 0; i < lanes; i++) tasks.push(worker()); + await Promise.all(tasks); + } + + remove(index: number) { + this.resources.splice(index, 1); + this.render(); + } + + clear() { + this.resources = []; + this.uploading = 0; + this.render(); + } + + render() { + this.container.empty(); + this.container.toggleClass('is-empty', this.count === 0); + + this.resources.forEach((res, index) => { + const box = this.container.createDiv('memo-attach'); + if (res.externalLink) { + box.createEl('img', { attr: { src: res.externalLink, alt: res.filename || '图片' } }); + } + const del = box.createEl('button', { cls: 'memo-attach-remove' }); + setIcon(del, 'x'); + del.setAttribute('aria-label', '移除图片'); + del.addEventListener('click', (e) => { + e.preventDefault(); + e.stopPropagation(); + this.remove(index); + }); + }); + + for (let i = 0; i < this.uploading; i++) { + this.container.createDiv('memo-attach is-uploading').setText('上传中'); + } + + this.onChange(); + } +} + +function wireAttachmentDnD(input: HTMLTextAreaElement, dropZone: HTMLElement, tray: AttachmentTray) { + input.addEventListener('paste', (evt: ClipboardEvent) => { + const data = evt.clipboardData; + if (!data) return; + + const files: File[] = []; + for (let i = 0; i < data.items.length; i++) { + const item = data.items[i]; + if (item.kind !== 'file') continue; + const file = item.getAsFile(); + if (file && file.type.indexOf('image/') === 0) files.push(file); + } + + if (files.length) { + evt.preventDefault(); + void tray.add(files); + } + }); + + dropZone.addEventListener('dragover', (evt: DragEvent) => { + evt.preventDefault(); + dropZone.addClass('is-dragover'); + }); + dropZone.addEventListener('dragleave', () => dropZone.removeClass('is-dragover')); + dropZone.addEventListener('drop', (evt: DragEvent) => { + evt.preventDefault(); + dropZone.removeClass('is-dragover'); + if (!evt.dataTransfer) return; + const files: File[] = []; + for (let i = 0; i < evt.dataTransfer.files.length; i++) { + files.push(evt.dataTransfer.files[i]); + } + if (files.length) void tray.add(files); + }); +} + +/** 打开系统文件选择框(支持多选图片),选中后回调 */ +function pickImageFiles(onPick: (files: File[]) => void) { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = 'image/*'; + input.multiple = true; + input.addClass('memos-file-input'); + + let settled = false; + const cleanup = () => { + if (settled) return; + settled = true; + input.remove(); + }; + + input.addEventListener('change', () => { + const files: File[] = []; + const list = input.files; + if (list) { + for (let i = 0; i < list.length; i++) { + const f = list.item(i); + if (f) files.push(f); + } + } + cleanup(); + if (files.length) onPick(files); + }); + // 用户取消选择时不会触发 change,靠 cancel 事件兜底清理 + input.addEventListener('cancel', cleanup); + + document.body.appendChild(input); + input.click(); +} + +/** 取第一个当前版本存在的图标,避免 lucide 版本差异导致按钮空白 */ +function firstAvailableIcon(...names: string[]): string { + for (const name of names) { + if (getIcon(name)) return name; + } + return 'plus'; +} + +// ============================================================ +// API 客户端(兼容 Memos v0.18.x 与 v0.22+ 的路径差异) +// ============================================================ + +class MemosApi { + private plugin: MemosPlugin; + /** true 时优先使用 0.18.x 的 /memo 路径 */ + private legacyPaths = true; + + constructor(plugin: MemosPlugin) { + this.plugin = plugin; + } + + resetStyle() { + this.legacyPaths = true; + } + + private get baseUrl(): string { + return (this.plugin.settings.serverUrl || '').trim().replace(/\/+$/, ''); + } + + private get token(): string { + return (this.plugin.settings.apiToken || '').trim(); + } + + private buildHeaders(hasBody: boolean): Record { + const headers: Record = { + Authorization: `Bearer ${this.token}`, + Accept: 'application/json', + }; + if (hasBody) headers['Content-Type'] = 'application/json'; + return headers; + } + + private extractMessage(json: unknown, text?: string): string { + if (json && typeof json === 'object') { + const obj = json as Record; + const msg = obj.message || obj.error || obj.detail; + if (typeof msg === 'string' && msg) return msg; + } + if (text) { + try { + const parsed = JSON.parse(text) as Record; + const msg = parsed.message || parsed.error; + if (typeof msg === 'string' && msg) return msg; + } catch { + const trimmed = text.trim(); + if (trimmed && trimmed.length < 200 && trimmed.indexOf('<') !== 0) return trimmed; + } + } + return ''; + } + + private messageForStatus(status: number, serverMessage: string): string { + switch (status) { + case 400: + return serverMessage || '请求参数有误(400)'; + case 401: + return 'API Token 无效或已过期,请在设置中重新生成'; + case 403: + return '没有权限执行该操作(403)'; + case 404: + return '接口不存在(404),请检查服务器地址或 Memos 版本'; + case 405: + return '接口方法不被支持(405),Memos 版本可能不匹配'; + case 413: + return '内容过大,服务端拒绝接收(413)'; + case 429: + return '请求过于频繁(429),请稍后再试'; + default: + if (status >= 500) return serverMessage || `服务器内部错误(${status})`; + return serverMessage || `请求失败(${status})`; + } + } + + private makeError(message: string, status?: number): Error { + const err = new Error(message); + if (typeof status === 'number') (err as Error & { status?: number }).status = status; + return err; + } + + private normalizeThrown(e: unknown): Error { + const err = e as { status?: number; json?: unknown; text?: string; message?: string }; + if (err && typeof err.status === 'number') { + return this.makeError( + this.messageForStatus(err.status, this.extractMessage(err.json, err.text)), + err.status + ); + } + const msg = (err && err.message) || String(e) || ''; + if (/net::|failed to fetch|econnrefused|enotfound|network|timeout|timed out|err_name/i.test(msg)) { + return this.makeError('无法连接到 Memos 服务器,请检查服务器地址与网络'); + } + if (/certificate|ssl|tls/i.test(msg)) { + return this.makeError('HTTPS 证书校验失败,请检查证书或改用 http'); + } + return this.makeError(msg || '未知错误'); + } + + private async request(path: string, method: string, body?: unknown): Promise { + if (!this.token) throw this.makeError('请先在插件设置中填写 API Token', 401); + if (!this.baseUrl) throw this.makeError('请先在插件设置中填写服务器地址'); + + const url = `${this.baseUrl}/api/v1${path.startsWith('/') ? path : '/' + path}`; + const params: RequestUrlParam = { + url, + method, + headers: this.buildHeaders(body !== undefined), + throw: false, + }; + if (body !== undefined) params.body = JSON.stringify(body); + + this.plugin.log(`[${method}] ${url}`); + if (body !== undefined) this.plugin.log('body:', JSON.stringify(body)); + + let res; + try { + res = await requestUrl(params); + } catch (e) { + throw this.normalizeThrown(e); + } + + if (res.status >= 400) { + throw this.makeError( + this.messageForStatus(res.status, this.extractMessage(undefined, res.text)), + res.status + ); + } + + const text = res.text; + if (!text || !text.trim()) return {} as T; + try { + return JSON.parse(text) as T; + } catch { + throw this.makeError('服务端返回了无法解析的数据,请检查服务器地址是否正确'); + } + } + + /** 依次尝试新旧两套路径,命中后记住风格 */ + private async requestWithFallback( + legacyPath: string, + modernPath: string, + method: string, + body?: unknown + ): Promise { + const order = this.legacyPaths ? [legacyPath, modernPath] : [modernPath, legacyPath]; + let firstError: Error | null = null; + + for (let i = 0; i < order.length; i++) { + try { + const result = await this.request(order[i], method, body); + if (i === 1) this.legacyPaths = !this.legacyPaths; + return result; + } catch (e) { + const err = e instanceof Error ? e : this.makeError(String(e)); + const status = (err as Error & { status?: number }).status; + if (i === 0) firstError = err; + if (status === 404 || status === 405) continue; + throw err; + } + } + throw firstError || this.makeError('接口不可用'); + } + + async status(): Promise { + return this.request('/status', 'GET'); + } + + async me(): Promise { + return this.request('/user/me', 'GET'); + } + + async listTags(): Promise { + try { + const res = await this.request('/tag', 'GET'); + const list: unknown[] = Array.isArray(res) + ? res + : Array.isArray((res as { data?: unknown[] }).data) + ? (res as { data: unknown[] }).data + : []; + return list.filter((t): t is string => typeof t === 'string'); + } catch (e) { + this.plugin.log('获取标签失败:', e); + return []; + } + } + + async listMemos(opts: { limit: number; offset: number; pageToken?: string }): Promise { + const query: string[] = [ + `limit=${opts.limit}`, + `offset=${opts.offset}`, + `pageSize=${opts.limit}`, + ]; + if (opts.pageToken) query.push(`pageToken=${encodeURIComponent(opts.pageToken)}`); + const qs = query.join('&'); + + const raw = await this.requestWithFallback(`/memo?${qs}`, `/memos?${qs}`, 'GET'); + + let memos: Memo[] = []; + let nextPageToken: string | undefined; + + if (Array.isArray(raw)) { + memos = raw as Memo[]; + } else if (raw && typeof raw === 'object') { + const obj = raw as { memos?: Memo[]; data?: Memo[]; nextPageToken?: string; nextPage?: string }; + memos = obj.memos || obj.data || []; + nextPageToken = obj.nextPageToken || obj.nextPage; + } + + const hasMore = !!nextPageToken || memos.length >= opts.limit; + return { memos, nextPageToken, hasMore }; + } + + /** + * 统计服务端全部 Memo 条数。 + * v0.18 的列表接口只返回数组、没有总数,所以用「越界 offset 返回空」的特性: + * 先按 4 倍步长探测上界,再二分逼近,每步只取 1 条(payload 极小)。 + * 失败返回 -1,由调用方保留旧值。 + */ + async countMemos(): Promise { + try { + const first = await this.listMemos({ limit: 1, offset: 0 }); + if (!first.memos.length) return 0; + const anchor = String(first.memos[0].id); + + const isEmptyAt = async (offset: number): Promise => { + const page = await this.listMemos({ limit: 1, offset }); + // v0.22+ 的 /memos 用 pageToken,不认 offset:探到同一条就放弃 + if (offset > 0 && page.memos.length && String(page.memos[0].id) === anchor) { + throw this.makeError('该服务端不支持按 offset 计数'); + } + return page.memos.length === 0; + }; + + // 找上界:largest offset 有数据 = lo,smallest offset 为空 = hi + let lo = 0; + let step = 1; + let hi = 0; + let guard = 0; + while (guard++ < 24) { + if (await isEmptyAt(step)) { + hi = step; + break; + } + lo = step; + step *= 4; + if (step > 5000000) return -1; + } + if (!hi) return -1; + + // 二分:offset 有数据 ⇔ offset < 总数 + while (hi - lo > 1) { + const mid = Math.floor((lo + hi) / 2); + if (await isEmptyAt(mid)) hi = mid; + else lo = mid; + } + return hi; + } catch (e) { + this.plugin.log('统计总条数失败', e); + return -1; + } + } + + async createMemo( + content: string, + visibility: MemoVisibility, + resourceIds?: number[], + relationIds?: string[] + ): Promise { + const body: Record = { + content: content.trim(), + visibility, + }; + if (resourceIds && resourceIds.length) body.resourceIdList = resourceIds; + // 引用走服务端的 MemoRelation(和网页端完全一致),不往正文里塞链接 + if (relationIds && relationIds.length) { + body.relationList = relationIds + .map((id) => Number(id)) + .filter((id) => Number.isFinite(id) && id > 0) + .map((id) => ({ relatedMemoId: id, type: REFERENCE_TYPE })); + } + return this.requestWithFallback('/memo', '/memos', 'POST', body); + } + + /** + * 上传图片资源。 + * Memos 服务端会把它落到「设置 → 存储」里配置的对象存储(S3 / 本地), + * 返回的 externalLink 就是该存储的公网地址,与网页端上传完全一致。 + */ + async uploadResource(file: File): Promise { + if (!this.token) throw this.makeError('请先在插件设置中填写 API Token', 401); + if (!this.baseUrl) throw this.makeError('请先在插件设置中填写服务器地址'); + + const boundary = '----ObsidianMemos' + Date.now().toString(16); + const filename = (file.name || `pasted-${Date.now()}.png`).replace(/["\r\n]/g, '_'); + const mime = file.type || 'application/octet-stream'; + const data = new Uint8Array(await file.arrayBuffer()); + + const encoder = new TextEncoder(); + const head = encoder.encode( + `--${boundary}\r\n` + + `Content-Disposition: form-data; name="file"; filename="${filename}"\r\n` + + `Content-Type: ${mime}\r\n\r\n` + ); + const tail = encoder.encode(`\r\n--${boundary}--\r\n`); + const body = new Uint8Array(head.length + data.length + tail.length); + body.set(head, 0); + body.set(data, head.length); + body.set(tail, head.length + data.length); + + const url = `${this.baseUrl}/api/v1/resource/blob`; + this.plugin.log(`[POST] ${url} (${filename}, ${data.length} bytes)`); + + let res; + try { + res = await requestUrl({ + url, + method: 'POST', + headers: { + Authorization: `Bearer ${this.token}`, + 'Content-Type': `multipart/form-data; boundary=${boundary}`, + }, + body: body.buffer as ArrayBuffer, + throw: false, + }); + } catch (e) { + throw this.normalizeThrown(e); + } + + if (res.status >= 400) { + throw this.makeError( + this.messageForStatus(res.status, this.extractMessage(undefined, res.text)), + res.status + ); + } + + try { + return JSON.parse(res.text) as MemoResource; + } catch { + throw this.makeError('上传返回的数据无法解析,请检查 Memos 版本'); + } + } + + async updateMemo( + id: number | string, + patch: { content?: string; visibility?: MemoVisibility; pinned?: boolean } + ): Promise { + return this.requestWithFallback(`/memo/${id}`, `/memos/${id}`, 'PATCH', patch); + } + + async deleteMemo(id: number | string): Promise { + await this.requestWithFallback(`/memo/${id}`, `/memos/${id}`, 'DELETE'); + } + + /** 按 ID 取单条 Memo(用于「引用已有 Memo」) */ + async getMemo(id: number | string): Promise { + return this.requestWithFallback(`/memo/${id}`, `/memos/${id}`, 'GET'); + } + + async setPinned(id: number | string, pinned: boolean): Promise { + // v0.18.x:organizer 接口;v0.22+:直接 PATCH memo + try { + await this.request(`/memo/${id}/organizer`, 'POST', { pinned }); + } catch (e) { + const status = (e as Error & { status?: number }).status; + if (status === 404 || status === 405) { + await this.request(`/memos/${id}`, 'PATCH', { pinned }); + return; + } + throw e; + } + } +} + +// ============================================================ +// 插件主体 +// ============================================================ + +export default class MemosPlugin extends Plugin { + settings: MemosPluginSettings; + api: MemosApi; + + async onload() { + await this.loadSettings(); + this.api = new MemosApi(this); + + this.registerView(VIEW_TYPE_MEMOS, (leaf) => new MemosSidebarView(leaf, this)); + + this.addRibbonIcon('message-square', 'Memos 管理器', () => { + void this.activateView(); + }); + + // 保留原有 command id,避免用户已设置的热键失效 + this.addCommand({ + id: 'open-memos-sidebar', + name: '打开 Memos 边栏', + callback: () => void this.activateView(), + }); + + this.addCommand({ + id: 'publish-selection-to-memos', + name: '发布选中文本到 Memos', + editorCallback: (editor) => { + const selection = editor.getSelection(); + if (!selection.trim()) { + new Notice('请先选中要发布的文本'); + return; + } + void this.publishFromCommand(selection); + }, + }); + + this.addCommand({ + id: 'memos-quick-capture', + name: '快速记录一条 Memo', + callback: () => { + new ComposeMemoModal(this.app, this, '', () => { + this.refreshViews(); + }).open(); + }, + }); + + this.addCommand({ + id: 'memos-quote-memo', + name: '引用一条 Memo(输入 ID)', + callback: () => { + new QuoteMemoModal( + this.app, + this, + { + toComposer: (memos) => { + const view = this.getSidebarView(); + return view ? view.insertQuoteIntoComposer(memos) : false; + }, + toNote: (md) => insertIntoNote(this.app, md), + }, + 'note' + ).open(); + }, + }); + + this.addSettingTab(new MemosSettingTab(this.app, this)); + } + + onunload() { + this.log('已卸载'); + } + + log(...args: unknown[]) { + if (this.settings && this.settings.debug) { + console.log('[Memos]', ...args); + } + } + + async activateView() { + const { workspace } = this.app; + let leaf = workspace.getLeavesOfType(VIEW_TYPE_MEMOS)[0]; + + if (!leaf) { + const right = workspace.getRightLeaf(false); + if (!right) { + new Notice('无法创建边栏'); + return; + } + await right.setViewState({ type: VIEW_TYPE_MEMOS, active: true }); + leaf = right; + } + + await workspace.revealLeaf(leaf); + } + + refreshViews() { + const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMOS); + for (const leaf of leaves) { + const view = leaf.view; + if (view instanceof MemosSidebarView) void view.refresh(true); + } + } + + /** 取已打开的 Memos 边栏视图(用于把引用插回输入框) */ + getSidebarView(): MemosSidebarView | null { + const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMOS); + for (const leaf of leaves) { + if (leaf.view instanceof MemosSidebarView) return leaf.view; + } + return null; + } + + private async publishFromCommand(text: string) { + try { + await this.api.createMemo( + normalizeContent(text, this.settings.serverUrl), + this.settings.defaultVisibility + ); + new Notice('✅ 已发布到 Memos'); + this.refreshViews(); + } catch (e) { + new Notice('❌ 发布失败:' + (e as Error).message, 6000); + } + } + + async loadSettings() { + const data = (await this.loadData()) || {}; + this.settings = Object.assign({}, DEFAULT_SETTINGS, data); + + // 旧版本字段迁移:limit -> pageSize + const legacyLimit = (data as { limit?: number }).limit; + if (!(data as { pageSize?: number }).pageSize && typeof legacyLimit === 'number' && legacyLimit > 0) { + this.settings.pageSize = legacyLimit; + } + if (this.settings.pageSize < 1) this.settings.pageSize = DEFAULT_SETTINGS.pageSize; + if (this.settings.pageSize > 200) this.settings.pageSize = 200; + } + + async saveSettings() { + await this.saveData(this.settings); + this.api.resetStyle(); + } +} + +// ============================================================ +// 自绘下拉 +// ============================================================ +// +// 不用原生