Files
Memos/main.ts

3283 lines
118 KiB
TypeScript
Raw Normal View History

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<string, boolean> = {};
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})`);
// <img> -> Markdown
out = out.replace(/<img\s+[^>]*>/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(/<br\s*\/?>/gi, '\n');
out = out.replace(/&nbsp;/g, ' ');
out = out.replace(/<p>\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`;
}
/**
* 画一个和网页端一样的引用卡片(对应网页端的
* `<a class="...border rounded-md..."><svg class="lucide-link">…</svg><span>#612</span><span class="truncate">正文</span></a>`):
* 链接图标 + `#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<T extends (...args: never[]) => 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<void> {
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<void>[] = [];
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<string, string> {
const headers: Record<string, string> = {
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<string, unknown>;
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<string, unknown>;
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<T>(path: string, method: string, body?: unknown): Promise<T> {
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<T>(
legacyPath: string,
modernPath: string,
method: string,
body?: unknown
): Promise<T> {
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<T>(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<StatusResponse> {
return this.request<StatusResponse>('/status', 'GET');
}
async me(): Promise<MeResponse> {
return this.request<MeResponse>('/user/me', 'GET');
}
async listTags(): Promise<string[]> {
try {
const res = await this.request<unknown>('/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<MemoListPage> {
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<unknown>(`/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<number> {
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<boolean> => {
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<Memo> {
const body: Record<string, unknown> = {
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>('/memo', '/memos', 'POST', body);
}
/**
* 上传图片资源。
* Memos 服务端会把它落到「设置 → 存储」里配置的对象存储(S3 / 本地),
* 返回的 externalLink 就是该存储的公网地址,与网页端上传完全一致。
*/
async uploadResource(file: File): Promise<MemoResource> {
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<Memo> {
return this.requestWithFallback<Memo>(`/memo/${id}`, `/memos/${id}`, 'PATCH', patch);
}
async deleteMemo(id: number | string): Promise<void> {
await this.requestWithFallback<void>(`/memo/${id}`, `/memos/${id}`, 'DELETE');
}
/** 按 ID 取单条 Memo(用于「引用已有 Memo」) */
async getMemo(id: number | string): Promise<Memo> {
return this.requestWithFallback<Memo>(`/memo/${id}`, `/memos/${id}`, 'GET');
}
async setPinned(id: number | string, pinned: boolean): Promise<void> {
// 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();
}
}
// ============================================================
// 自绘下拉
// ============================================================
//
// 不用原生 <select>:Obsidian 本体对 select 有自己的 padding/背景/箭头声明,
// 不同版本、不同主题下文字的落点会变(表现为文字偏右或偏左),
// 而 select 的文字位置没法在 CSS 里精确控制。这里改用「按钮 + 浮层」:
// 文字靠 flex 居中,浮层自己定位,任何主题下都一样。
interface MenuSelectOption {
value: string;
label: string;
/** 选中该项时按钮上显示的文字(不填则用 label)。用于让「全部标签」这类菜单项
不在按钮上重复一遍,按钮仍显示「按标签筛选」。 */
btnLabel?: string;
}
class MemosMenuSelect {
readonly host: HTMLElement;
readonly el: HTMLButtonElement;
private labelEl: HTMLElement;
private opts: MenuSelectOption[];
private value: string;
private onChange?: (value: string) => void;
private menu: HTMLElement | null = null;
private onDocDown: ((evt: MouseEvent) => void) | null = null;
private onDocKey: ((evt: KeyboardEvent) => void) | null = null;
private onReposition: (() => void) | null = null;
constructor(
parent: HTMLElement,
cls: string,
opts: MenuSelectOption[],
value: string,
onChange?: (value: string) => void
) {
this.opts = opts.slice();
this.value = value;
this.onChange = onChange;
this.host = parent.createDiv(cls ? `memos-dd ${cls}` : 'memos-dd');
this.el = this.host.createEl('button', {
cls: 'memos-dd-btn',
attr: { type: 'button', 'aria-haspopup': 'listbox', 'aria-expanded': 'false' },
});
this.labelEl = this.el.createSpan({ cls: 'memos-dd-label' });
const chevron = this.el.createSpan({ cls: 'memos-dd-chevron' });
setIcon(chevron, 'chevron-down');
this.renderLabel();
this.el.addEventListener('click', (evt) => {
evt.preventDefault();
evt.stopPropagation();
this.toggle();
});
}
getValue(): string {
return this.value;
}
setValue(value: string, fire = false) {
const changed = value !== this.value;
this.value = value;
this.renderLabel();
if (changed && fire && this.onChange) this.onChange(value);
}
setOptions(opts: MenuSelectOption[]) {
this.opts = opts.slice();
if (!this.opts.some((o) => o.value === this.value)) {
this.value = this.opts.length ? this.opts[0].value : '';
}
this.renderLabel();
if (this.menu) this.close();
}
setActive(on: boolean) {
this.el.toggleClass('is-active', on);
}
setVisible(visible: boolean) {
this.host.toggleClass('is-hidden', !visible);
}
private renderLabel() {
const hit = this.opts.find((o) => o.value === this.value) || this.opts[0];
this.labelEl.setText(hit ? hit.btnLabel ?? hit.label : '');
}
private toggle() {
if (this.menu) this.close();
else this.open();
}
private open() {
this.close();
const menu = document.createElement('div');
menu.className = 'memos-menu-pop';
menu.setAttribute('role', 'listbox');
this.opts.forEach((opt) => {
const item = document.createElement('button');
item.type = 'button';
item.className = 'memos-menu-item';
item.setAttribute('role', 'option');
if (opt.value === this.value) {
item.classList.add('is-selected');
item.setAttribute('aria-selected', 'true');
}
const text = document.createElement('span');
text.className = 'memos-menu-item-label';
text.textContent = opt.label;
item.appendChild(text);
if (opt.value === this.value) {
const tick = document.createElement('span');
tick.className = 'memos-menu-item-tick';
setIcon(tick, 'check');
item.appendChild(tick);
}
item.addEventListener('click', (evt) => {
evt.preventDefault();
evt.stopPropagation();
this.close();
this.setValue(opt.value, true);
});
menu.appendChild(item);
});
// 先量尺寸再定位,避免出现一帧错位。
// 用 min-width 而不是 width:浮层至少和按钮一样宽(对齐好看),
// 但长标签能自己撑开,不会被截断。
menu.style.visibility = 'hidden';
const btnW = Math.round(this.el.getBoundingClientRect().width);
menu.style.minWidth = `${Math.max(btnW, 88)}px`;
document.body.appendChild(menu);
this.menu = menu;
this.position();
menu.style.visibility = '';
this.el.setAttribute('aria-expanded', 'true');
this.onDocDown = (evt: MouseEvent) => {
const target = evt.target as Node | null;
if (!target) return;
if (this.host.contains(target)) return;
if (this.menu && this.menu.contains(target)) return;
this.close();
};
this.onDocKey = (evt: KeyboardEvent) => {
if (evt.key === 'Escape') {
evt.stopPropagation();
this.close();
}
};
this.onReposition = () => this.position();
document.addEventListener('mousedown', this.onDocDown, true);
document.addEventListener('keydown', this.onDocKey, true);
window.addEventListener('resize', this.onReposition);
window.addEventListener('scroll', this.onReposition, true);
}
/** 浮层与按钮水平居中对齐,超出视口时贴边,空间不够就翻到按钮上方 */
private position() {
if (!this.menu) return;
const btn = this.el.getBoundingClientRect();
const box = this.menu.getBoundingClientRect();
const gap = 4;
const pad = 8;
let left = btn.left + btn.width / 2 - box.width / 2;
const maxLeft = window.innerWidth - box.width - pad;
if (left > maxLeft) left = Math.max(pad, maxLeft);
if (left < pad) left = pad;
let top = btn.bottom + gap;
if (top + box.height > window.innerHeight - pad) {
const above = btn.top - box.height - gap;
top = above >= pad ? above : Math.max(pad, window.innerHeight - box.height - pad);
}
this.menu.style.left = `${Math.round(left)}px`;
this.menu.style.top = `${Math.round(top)}px`;
}
private close() {
if (this.onDocDown) document.removeEventListener('mousedown', this.onDocDown, true);
if (this.onDocKey) document.removeEventListener('keydown', this.onDocKey, true);
if (this.onReposition) {
window.removeEventListener('resize', this.onReposition);
window.removeEventListener('scroll', this.onReposition, true);
}
this.onDocDown = null;
this.onDocKey = null;
this.onReposition = null;
if (this.menu) {
this.menu.remove();
this.menu = null;
}
if (this.el) this.el.setAttribute('aria-expanded', 'false');
}
}
// ============================================================
// 边栏视图
// ============================================================
class MemosSidebarView extends ItemView {
private plugin: MemosPlugin;
private searchEl!: HTMLInputElement;
private tagSelectEl!: MemosMenuSelect;
private visibilityFilterEl!: MemosMenuSelect;
private clearFilterBtnEl!: HTMLButtonElement;
private composerBoxEl!: HTMLElement;
private composerEl!: HTMLTextAreaElement;
private attachmentsEl!: HTMLElement;
private pendingRefsEl!: HTMLElement;
private composerVisibilityEl!: MemosMenuSelect;
private uploadBtnEl!: HTMLButtonElement;
private uploadBadgeEl!: HTMLElement;
private publishBtnEl!: HTMLButtonElement;
private listEl!: HTMLElement;
private footerEl!: HTMLElement;
private countEl!: HTMLElement;
private footerTextEl!: HTMLElement;
private loadMoreBtnEl!: HTMLButtonElement;
private memos: Memo[] = [];
private tags: string[] = [];
private nextPageToken: string | undefined;
private hasMore = false;
private loading = false;
private publishing = false;
private loadSeq = 0;
/** 已从服务端取回的条数,用于分页 offset(与去重后的本地数量区分) */
private fetchedCount = 0;
/** 服务端全部条数(-1 表示还没算出来) */
private totalCount = -1;
private totalCountAt = 0;
private countingTotal = false;
private lastError = '';
private query = '';
private activeTag = '';
private visibilityFilter: 'all' | MemoVisibility = 'all';
private tray!: AttachmentTray;
/** 待发布的引用(发布时作为 MemoRelation 发送,不进正文) */
private pendingRefs: { id: string; title: string }[] = [];
/** 引用 chip 的正文摘要缓存,key 是被引用 Memo 的 id */
private refTitleCache = new Map<string, string>();
private refTitlePending = new Map<string, Promise<string>>();
private renderComponent: Component | null = null;
private renderToken = 0;
constructor(leaf: WorkspaceLeaf, plugin: MemosPlugin) {
super(leaf);
this.plugin = plugin;
}
getViewType(): string {
return VIEW_TYPE_MEMOS;
}
getDisplayText(): string {
return 'Memos';
}
getIcon(): string {
return 'message-square';
}
async onOpen() {
this.buildLayout();
if (!this.plugin.settings.apiToken) {
this.renderConfigState();
return;
}
this.restoreDraft();
await Promise.all([this.refresh(true), this.loadTags()]);
}
async onClose() {
this.saveDraftNow();
if (this.renderComponent) {
this.renderComponent.unload();
this.renderComponent = null;
}
}
// ---------------- UI 骨架 ----------------
private buildLayout() {
const root = this.contentEl;
root.empty();
root.addClass('memos-sidebar');
// 顶部:标题 + 刷新
const header = root.createDiv('memos-header');
const titleWrap = header.createDiv('memos-header-title');
titleWrap.createSpan({ cls: 'memos-title-text', text: 'Memos' });
this.countEl = titleWrap.createSpan({ cls: 'memos-count', text: '' });
const headerActions = header.createDiv('memos-header-actions');
this.iconButton(headerActions, 'plus', '快速记录', () => {
new ComposeMemoModal(this.app, this.plugin, '', () => this.refresh(true)).open();
});
this.iconButton(headerActions, 'refresh-cw', '刷新', () => {
void this.refresh(true);
void this.refreshTotalCount(true);
});
// 搜索
const searchWrap = root.createDiv('memos-search');
this.searchEl = searchWrap.createEl('input', {
cls: 'memos-search-input',
attr: { type: 'search', placeholder: '搜索内容或 #标签…', spellcheck: 'false' },
});
this.searchEl.addEventListener('input', debounce(() => {
this.query = this.searchEl.value;
void this.renderList();
}, 160));
this.searchEl.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key === 'Escape') {
this.searchEl.value = '';
this.query = '';
void this.renderList();
}
});
// 筛选行:标签下拉 + 可见性下拉 + 清除
const filters = root.createDiv('memos-filters');
this.tagSelectEl = new MemosMenuSelect(
filters,
'is-filter',
[{ value: '', label: '全部标签', btnLabel: '按标签筛选' }],
'',
(value) => {
this.activeTag = value;
this.renderTagSelect();
void this.renderList();
}
);
this.visibilityFilterEl = new MemosMenuSelect(
filters,
'is-filter',
[
{ value: 'all', label: '全部权限', btnLabel: '按权限筛选' },
{ value: 'PRIVATE', label: '私有' },
{ value: 'PUBLIC', label: '公开' },
],
'all',
(value) => {
this.visibilityFilter = value as 'all' | MemoVisibility;
this.renderTagSelect();
void this.renderList();
}
);
this.clearFilterBtnEl = filters.createEl('button', { cls: 'memos-filter-clear is-hidden' });
this.clearFilterBtnEl.setAttribute('aria-label', '清除筛选');
setIcon(this.clearFilterBtnEl, 'x');
this.clearFilterBtnEl.addEventListener('click', () => this.clearFilters());
// 输入区
this.composerBoxEl = root.createDiv('memos-composer');
const composer = this.composerBoxEl;
this.composerEl = composer.createEl('textarea', {
cls: 'memos-composer-input',
attr: { placeholder: '写点什么…支持 Markdown 与 #标签,可粘贴/拖入图片', rows: '3' },
});
this.composerEl.addEventListener('input', () => {
this.autoGrow();
this.saveDraftDebounced();
});
this.composerEl.addEventListener('keydown', (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
void this.publish();
}
});
// 待发布的引用 chip(网页端那种带链接图标的小卡片)
this.pendingRefsEl = composer.createDiv('memos-pending-refs is-empty');
this.attachmentsEl = composer.createDiv('memos-attachments is-empty');
this.tray = new AttachmentTray(this.attachmentsEl, this.plugin, () => this.refreshTrayState());
wireAttachmentDnD(this.composerEl, this.composerBoxEl, this.tray);
const composerBar = composer.createDiv('memos-composer-bar');
this.composerVisibilityEl = new MemosMenuSelect(
composerBar,
'is-visibility',
[
{ value: 'PRIVATE', label: '私有' },
{ value: 'PUBLIC', label: '公开' },
],
this.plugin.settings.defaultVisibility
);
// 上传图片(紧接可见性按钮右侧,支持多选批量上传)
this.uploadBtnEl = composerBar.createEl('button', { cls: 'memos-upload-btn' });
setIcon(this.uploadBtnEl, firstAvailableIcon('image-plus', 'image', 'upload'));
this.uploadBtnEl.setAttribute('aria-label', '上传图片(可多选)');
this.uploadBtnEl.setAttribute('title', '上传图片(可多选,也可直接粘贴或拖入)');
this.uploadBtnEl.addEventListener('click', () => this.pickImages());
this.uploadBadgeEl = this.uploadBtnEl.createSpan({ cls: 'memos-upload-badge is-empty', text: '' });
// 引用已有 Memo(在上传按钮右侧):插入到输入框,方便拼成一条新的 Memo
// 引用已有 Memo(在上传按钮右侧):加一个引用 chip,发布时作为 MemoRelation 发送
const quoteBtn = composerBar.createEl('button', { cls: 'memos-tool-btn' });
setIcon(quoteBtn, firstAvailableIcon('quote', 'text-quote', 'message-square-quote'));
quoteBtn.setAttribute('aria-label', '引用已有 Memo');
quoteBtn.setAttribute('title', '引用已有 Memo:输入 ID,发布后与网页端一样显示成引用卡片');
quoteBtn.addEventListener('click', () => {
new QuoteMemoModal(
this.app,
this.plugin,
{
toComposer: (memos) => this.addPendingRefs(memos),
toNote: (md) => insertIntoNote(this.app, md),
},
'composer'
).open();
});
// 待办事项:在输入框插入 `- [ ] `,发布后可在列表里点勾
const taskBtn = composerBar.createEl('button', { cls: 'memos-tool-btn' });
setIcon(taskBtn, firstAvailableIcon('list-todo', 'list-checks', 'check-square'));
taskBtn.setAttribute('aria-label', '插入待办事项');
taskBtn.setAttribute('title', '插入待办事项:Ctrl/⌘+Enter 发布后可在列表里勾选完成');
taskBtn.addEventListener('click', () => this.insertTaskMarker());
// 提示文案已移除,整行空间留给按钮(图片数量以小角标显示在上传按钮上)
this.publishBtnEl = composerBar.createEl('button', {
cls: 'memos-publish-btn',
text: '发布',
});
this.publishBtnEl.addEventListener('click', () => void this.publish());
// 列表
this.listEl = root.createDiv('memos-list');
// 底部
this.footerEl = root.createDiv('memos-footer');
this.loadMoreBtnEl = this.footerEl.createEl('button', {
cls: 'memos-load-more',
text: '加载更多',
});
this.loadMoreBtnEl.addEventListener('click', () => void this.loadMore());
this.footerTextEl = this.footerEl.createSpan({ cls: 'memos-footer-note', text: '' });
this.registerDomEvent(this.listEl, 'scroll', () => {
if (!this.plugin.settings.autoLoadMore) return;
const el = this.listEl;
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 120) {
void this.loadMore();
}
});
// 点击标签筛选
this.registerDomEvent(this.listEl, 'click', (evt: MouseEvent) => {
const target = evt.target as HTMLElement | null;
if (!target) return;
const tagEl = target.closest('a.tag');
if (tagEl) {
evt.preventDefault();
evt.stopPropagation();
const raw = tagEl.getAttribute('data-href') || tagEl.textContent || '';
this.toggleTag(raw.replace(/^#/, ''));
}
});
this.updateFooter('', false);
}
private iconButton(parent: HTMLElement, icon: string, label: string, onClick: () => void): HTMLButtonElement {
const btn = parent.createEl('button', { cls: 'memos-icon-btn' });
btn.setAttribute('aria-label', label);
setIcon(btn, icon);
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
onClick();
});
return btn;
}
private autoGrow() {
const el = this.composerEl;
el.style.height = 'auto';
const next = Math.min(el.scrollHeight, MAX_COMPOSER_HEIGHT);
el.style.height = next + 'px';
el.style.overflowY = el.scrollHeight > MAX_COMPOSER_HEIGHT ? 'auto' : 'hidden';
}
// ---------------- 草稿 ----------------
private saveDraftDebounced = debounce(() => this.saveDraftNow(), 500);
private saveDraftNow() {
try {
if (!this.composerEl) return;
const value = this.composerEl.value;
if (value && value.trim()) {
window.localStorage.setItem(DRAFT_KEY, value);
} else {
window.localStorage.removeItem(DRAFT_KEY);
}
// 引用 chip 也跟着草稿存,重开边栏不丢
if (this.pendingRefs.length) {
window.localStorage.setItem(DRAFT_REFS_KEY, JSON.stringify(this.pendingRefs));
} else {
window.localStorage.removeItem(DRAFT_REFS_KEY);
}
} catch (e) {
this.plugin.log('保存草稿失败', e);
}
}
private restoreDraft() {
try {
const draft = window.localStorage.getItem(DRAFT_KEY);
if (draft && this.composerEl && !this.composerEl.value) {
this.composerEl.value = draft;
this.autoGrow();
}
const refs = window.localStorage.getItem(DRAFT_REFS_KEY);
if (refs) {
const parsed = JSON.parse(refs) as { id: string; title: string }[];
if (Array.isArray(parsed)) {
this.pendingRefs = parsed.filter((ref) => ref && ref.id).map((ref) => ({
id: String(ref.id),
title: String(ref.title || ''),
}));
this.renderPendingRefs();
}
}
} catch {
/* 忽略 */
}
}
private clearDraft() {
try {
window.localStorage.removeItem(DRAFT_KEY);
window.localStorage.removeItem(DRAFT_REFS_KEY);
} catch {
/* 忽略 */
}
}
// ---------------- 数据 ----------------
async refresh(reset = true) {
const seq = ++this.loadSeq;
this.loading = true;
if (reset) {
this.memos = [];
this.fetchedCount = 0;
this.nextPageToken = undefined;
this.hasMore = false;
this.renderLoadingState();
}
this.lastError = '';
this.updateFooter('加载中…', true);
try {
const page = await this.plugin.api.listMemos({
limit: this.plugin.settings.pageSize,
offset: reset ? 0 : this.fetchedCount,
pageToken: reset ? undefined : this.nextPageToken,
});
if (seq !== this.loadSeq) return;
this.fetchedCount = (reset ? 0 : this.fetchedCount) + page.memos.length;
this.memos = sortMemos(reset ? page.memos : mergeUnique(this.memos, page.memos));
this.nextPageToken = page.nextPageToken;
this.hasMore = page.hasMore && page.memos.length > 0;
// 已经全部加载完就不必再问服务端要总数了
if (!this.hasMore) this.totalCount = this.memos.length;
else if (reset) void this.refreshTotalCount();
await this.renderList();
this.renderTagSelect();
this.renderHeaderCount();
} catch (e) {
if (seq !== this.loadSeq) return;
this.lastError = (e as Error).message;
this.renderErrorState(this.lastError);
} finally {
if (seq === this.loadSeq) {
this.loading = false;
this.updateFooter(this.lastError, false);
}
}
}
private async loadMore() {
if (this.loading || !this.hasMore) return;
await this.refresh(false);
}
private async loadTags() {
const tags = await this.plugin.api.listTags();
this.tags = tags.slice().sort((a, b) => a.localeCompare(b, 'zh'));
this.renderTagSelect();
}
// ---------------- 渲染 ----------------
private renderConfigState() {
this.listEl.empty();
const box = this.listEl.createDiv('memos-placeholder');
box.createDiv({ cls: 'memos-placeholder-icon', text: '⚙️' });
box.createEl('p', { text: '还没有配置 Memos 服务器' });
const btn = box.createEl('button', { cls: 'memos-primary-btn', text: '打开设置' });
btn.addEventListener('click', () => {
const app = this.app as App & { setting?: { open: () => void; openTabById?: (id: string) => void } };
app.setting?.open();
app.setting?.openTabById?.(this.plugin.manifest.id);
});
this.updateFooter('', false);
}
private renderLoadingState() {
if (!this.listEl) return;
this.listEl.empty();
const box = this.listEl.createDiv('memos-skeleton');
for (let i = 0; i < 3; i++) {
const item = box.createDiv('memos-skeleton-item');
item.createDiv('memos-skeleton-line');
item.createDiv('memos-skeleton-line short');
}
}
private renderErrorState(message: string) {
if (!this.listEl) return;
this.listEl.empty();
const box = this.listEl.createDiv('memos-placeholder');
box.createDiv({ cls: 'memos-placeholder-icon', text: '⚠️' });
box.createEl('p', { text: message });
const btn = box.createEl('button', { cls: 'memos-primary-btn', text: '重试' });
btn.addEventListener('click', () => void this.refresh(true));
}
private renderTagSelect() {
if (!this.tagSelectEl) return;
const opts: MenuSelectOption[] = [{ value: '', label: '全部标签', btnLabel: '按标签筛选' }];
const tags = this.tags.slice();
if (this.activeTag && tags.indexOf(this.activeTag) === -1) tags.unshift(this.activeTag);
for (const tag of tags) opts.push({ value: tag, label: tag });
this.tagSelectEl.setOptions(opts);
this.tagSelectEl.setValue(this.activeTag);
this.tagSelectEl.setActive(!!this.activeTag);
this.tagSelectEl.setVisible(this.plugin.settings.showTags);
if (this.visibilityFilterEl) {
this.visibilityFilterEl.setValue(this.visibilityFilter);
this.visibilityFilterEl.setActive(this.visibilityFilter !== 'all');
}
if (this.clearFilterBtnEl) {
this.clearFilterBtnEl.toggleClass('is-hidden', !this.hasActiveFilter());
}
}
private hasActiveFilter(): boolean {
return !!this.query || !!this.activeTag || this.visibilityFilter !== 'all';
}
private toggleTag(tag: string) {
if (!tag) return;
this.activeTag = this.activeTag === tag ? '' : tag;
this.renderTagSelect();
void this.renderList();
}
private clearFilters() {
this.activeTag = '';
this.visibilityFilter = 'all';
this.query = '';
if (this.searchEl) this.searchEl.value = '';
if (this.visibilityFilterEl) this.visibilityFilterEl.setValue('all');
this.renderTagSelect();
void this.renderList();
}
private getFilteredMemos(): Memo[] {
const q = this.query.trim().toLowerCase();
const tag = this.activeTag.toLowerCase();
return this.memos.filter((memo) => {
if (this.visibilityFilter !== 'all' && memo.visibility !== this.visibilityFilter) return false;
if (tag) {
const memoTags = extractTags(memo.content).map((t) => t.toLowerCase());
if (memoTags.indexOf(tag) === -1) return false;
}
if (q) {
const hay = (memo.content || '').toLowerCase();
if (hay.indexOf(q) === -1) return false;
}
return true;
});
}
private async renderList() {
if (!this.listEl) return;
const token = ++this.renderToken;
const list = this.getFilteredMemos();
if (this.renderComponent) {
try {
this.renderComponent.unload();
} catch {
/* 忽略 */
}
}
const component = new Component();
component.load();
this.renderComponent = component;
this.listEl.empty();
if (!list.length) {
const box = this.listEl.createDiv('memos-placeholder');
if (this.memos.length === 0) {
box.createDiv({ cls: 'memos-placeholder-icon', text: '✨' });
box.createEl('p', { text: '还没有 Memos,写下第一条吧' });
} else {
box.createDiv({ cls: 'memos-placeholder-icon', text: '🔍' });
box.createEl('p', { text: '没有匹配的 Memo' });
const btn = box.createEl('button', { cls: 'memos-secondary-btn', text: '清除筛选' });
btn.addEventListener('click', () => this.clearFilters());
}
this.updateFooter('', false);
return;
}
const tasks: Promise<void>[] = [];
for (const memo of list) {
tasks.push(this.renderMemo(memo, component, token));
}
await Promise.all(tasks);
if (token !== this.renderToken) return;
this.updateFooter('', false);
}
private async renderMemo(memo: Memo, component: Component, token: number): Promise<void> {
const item = this.listEl.createDiv('memo-item');
if (memo.pinned) item.addClass('is-pinned');
// 头部:左侧时间(+ 徽章),右侧 ID——两头对齐,像天平一样
const head = item.createDiv('memo-head');
const timeEl = head.createSpan({ cls: 'memo-time', text: formatRelative(memoTime(memo)) });
timeEl.setAttribute('aria-label', formatAbsolute(memoTime(memo)));
if (isEdited(memo)) {
head.createSpan({ cls: 'memo-badge', text: '已编辑' });
}
if (memo.visibility === 'PUBLIC') {
head.createSpan({ cls: 'memo-vis', text: '公开' });
}
if (memo.pinned) {
const pin = head.createSpan({ cls: 'memo-pin' });
setIcon(pin, 'pin');
}
const idEl = head.createSpan({ cls: 'memo-id', text: `#${memo.id}` });
idEl.setAttribute('title', '点击复制 ID');
idEl.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
navigator.clipboard.writeText(String(memo.id)).then(
() => new Notice(`已复制 ID:${memo.id}`),
() => new Notice('复制失败')
);
});
// 正文
const contentEl = item.createDiv('memo-content');
const text = normalizeContent(memo.content, this.plugin.settings.serverUrl);
if (text) {
try {
if (token === this.renderToken) {
await MarkdownRenderer.render(this.app, text, contentEl, '', component);
}
} catch (e) {
this.plugin.log('Markdown 渲染失败', e);
contentEl.setText(text);
}
if (token === this.renderToken) this.wireTaskCheckboxes(memo, contentEl);
}
// 附件图片
const resources = memo.resourceList || [];
const images = resources.filter(
(r) => !!r.externalLink && !!r.type && r.type.indexOf('image/') === 0
);
if (this.plugin.settings.showImages && images.length) {
const media = item.createDiv('memo-media');
const max = 4;
images.slice(0, max).forEach((res) => {
const url = this.resolveUrl(res.externalLink || '');
if (!url) return;
const img = media.createEl('img', {
cls: 'memo-image',
attr: { src: url, alt: res.filename || '图片', loading: 'lazy' },
});
img.addEventListener('click', (e) => {
e.stopPropagation();
new ImagePreviewModal(this.app, url, res.filename || '').open();
});
});
if (images.length > max) {
media.createSpan({ cls: 'memo-media-more', text: `+${images.length - max}` });
}
}
// 非图片附件
const files = resources.filter(
(r) => !!r.externalLink && (!r.type || r.type.indexOf('image/') !== 0)
);
if (files.length) {
const box = item.createDiv('memo-files');
files.forEach((res) => {
const link = box.createEl('a', {
cls: 'memo-file',
text: '📎 ' + (res.filename || '附件'),
attr: { href: this.resolveUrl(res.externalLink || ''), target: '_blank', rel: 'noopener' },
});
link.addEventListener('click', (e) => e.stopPropagation());
});
}
// 引用关系(网页端那种带链接图标的卡片),跟在正文/附件下方
this.renderMemoRefs(item, memo);
// 操作
const actions = item.createDiv('memo-actions');
this.iconButton(actions, 'pencil', '编辑', () => {
new EditMemoModal(this.app, this.plugin, memo, () => void this.refresh(true)).open();
});
this.iconButton(actions, 'copy', '复制内容', () => {
navigator.clipboard.writeText(memo.content).then(
() => new Notice('已复制到剪贴板'),
() => new Notice('复制失败')
);
});
this.iconButton(actions, 'file-input', '插入到当前笔记', () => this.insertToNote(memo));
this.iconButton(
actions,
firstAvailableIcon('quote', 'text-quote', 'message-square-quote'),
'引用到输入框',
() => {
this.addPendingRef(memo);
}
);
this.iconButton(actions, memo.pinned ? 'pin-off' : 'pin', memo.pinned ? '取消置顶' : '置顶', () => {
void this.togglePin(memo);
});
this.iconButton(actions, 'trash-2', '删除', () => {
new ConfirmModal(this.app, {
title: '删除 Memo',
message: '删除后无法恢复,确定要删除这条 Memo 吗?',
confirmText: '删除',
danger: true,
onConfirm: async () => {
try {
await this.plugin.api.deleteMemo(memo.id);
this.memos = this.memos.filter((m) => String(m.id) !== String(memo.id));
if (this.totalCount > 0) this.totalCount = Math.max(0, this.totalCount - 1);
new Notice('🗑️ 已删除');
await this.renderList();
this.updateFooter('', false);
} catch (e) {
new Notice('❌ 删除失败:' + (e as Error).message, 5000);
}
},
}).open();
});
}
/**
* 让正文里的任务列表可点:Obsidian 渲染出来的 checkbox 默认是禁用的,
* 这里放开并在切换后回写 Memo 内容(`- [ ]` ↔ `- [x]`)。
* 用 change 而不是 click —— click 上 preventDefault 会被浏览器的
* 「取消激活」逻辑把 checked 还原,出现「文字划线了但框没勾上」。
*/
private wireTaskCheckboxes(memo: Memo, contentEl: HTMLElement) {
const boxes = Array.from(
contentEl.querySelectorAll<HTMLInputElement>(
'input.task-list-item-checkbox, li.task-list-item input[type="checkbox"]'
)
);
if (!boxes.length) return;
boxes.forEach((box, ordinal) => {
box.disabled = false;
box.removeAttribute('disabled');
box.addClass('memos-task-checkbox');
box.setAttribute('aria-label', '点击切换完成状态');
const li = box.closest('li');
if (li) {
li.addClass('memos-task-item');
li.toggleClass('is-done', box.checked);
}
box.addEventListener('click', (evt: MouseEvent) => evt.stopPropagation());
box.addEventListener('change', () => {
void this.toggleMemoTask(memo, ordinal, box, li);
});
});
}
private async toggleMemoTask(
memo: Memo,
ordinal: number,
box: HTMLInputElement,
li: Element | null
) {
const done = box.checked;
const next = setTaskLine(memo.content, ordinal, done);
if (next === null) {
box.checked = !done;
return;
}
li?.toggleClass('is-done', done);
box.disabled = true;
try {
const updated = await this.plugin.api.updateMemo(memo.id, { content: next });
const content = typeof updated?.content === 'string' ? updated.content : next;
memo.content = content;
const cached = this.memos.find((m) => String(m.id) === String(memo.id));
if (cached) cached.content = content;
} catch (e) {
box.checked = !done;
li?.toggleClass('is-done', !done);
new Notice('❌ 更新待办失败:' + (e as Error).message, 5000);
} finally {
box.disabled = false;
}
}
private resolveUrl(url: string): string {
if (!url) return '';
if (/^https?:\/\//i.test(url) || url.indexOf('data:') === 0) return url;
const base = this.plugin.settings.serverUrl.replace(/\/+$/, '');
return base + (url.startsWith('/') ? url : '/' + url);
}
private async togglePin(memo: Memo) {
const next = !memo.pinned;
try {
await this.plugin.api.setPinned(memo.id, next);
new Notice(next ? '📌 已置顶' : '已取消置顶');
await this.refresh(true);
} catch (e) {
new Notice('置顶失败:' + (e as Error).message, 5000);
}
}
/** 插入到当前笔记(正文 + 图片 + 来源行) */
private insertToNote(memo: Memo) {
const res = insertIntoNote(
this.app,
memoToMarkdown(memo, this.plugin.settings.serverUrl)
);
if (!res.ok) {
new Notice('没有可用的笔记:请先打开一个 Markdown 笔记');
return;
}
new Notice(`已插入到「${res.note}」`);
}
/** 公开给命令调用:把引用加进输入区(发布时作为 MemoRelation 发送) */
insertQuoteIntoComposer(memos: Memo[]): boolean {
return this.addPendingRefs(memos);
}
// ---------------- 发布 ----------------
private async publish() {
if (this.publishing) return;
if (this.tray.busy) {
new Notice('图片还在上传中,请稍候');
return;
}
const raw = this.composerEl.value.trim();
const ids = this.tray.ids;
if (!raw && !ids.length) {
new Notice(
this.pendingRefs.length
? '引用会随 Memo 一起发送,还需要写点正文'
: '请输入内容或添加图片'
);
this.composerEl.focus();
return;
}
this.publishing = true;
this.publishBtnEl.disabled = true;
this.publishBtnEl.setText('发布中…');
try {
const visibility = this.composerVisibilityEl.getValue() as MemoVisibility;
const content = normalizeContent(raw, this.plugin.settings.serverUrl);
const refIds = this.pendingRefs.map((ref) => ref.id);
await this.plugin.api.createMemo(content, visibility, ids, refIds);
this.composerEl.value = '';
this.autoGrow();
this.tray.clear();
this.clearPendingRefs();
this.clearDraft();
new Notice('✅ 已发布');
if (this.totalCount >= 0) this.totalCount += 1;
await this.refresh(true);
await this.loadTags();
} catch (e) {
new Notice('❌ 发布失败:' + (e as Error).message, 6000);
} finally {
this.publishing = false;
this.refreshTrayState();
this.publishBtnEl.setText('发布');
}
}
/** 在输入框插入待办标记(支持选中多行) */
private insertTaskMarker() {
const el = this.composerEl;
const start = el.selectionStart ?? el.value.length;
const end = el.selectionEnd ?? start;
const res = applyTaskPrefix(el.value, start, end);
el.value = res.value;
el.selectionStart = el.selectionEnd = res.caret;
el.focus();
this.autoGrow();
this.saveDraftDebounced();
}
private pickImages() {
pickImageFiles((files) => {
void this.tray.add(files);
});
}
// ---------------- 引用 chip(对齐网页端 MemoRelation) ----------------
/** 往输入区加一批引用(来自引用弹窗),返回是否成功 */
addPendingRefs(memos: Memo[]): boolean {
if (!this.pendingRefsEl) return false;
let added = 0;
for (const memo of memos) {
const id = String(memo.id);
if (this.pendingRefs.some((ref) => ref.id === id)) continue;
const title = memoReferenceTitle(memo, 60);
this.pendingRefs.push({ id, title });
this.refTitleCache.set(id, title);
added++;
}
if (added) this.renderPendingRefs();
if (this.composerEl) this.composerEl.focus();
return true;
}
/** 单条引用(卡片上的引用按钮) */
private addPendingRef(memo: Memo): boolean {
const ok = this.addPendingRefs([memo]);
if (ok && this.pendingRefs.some((ref) => ref.id === String(memo.id))) {
new Notice(`已引用 #${memo.id},发布时随 Memo 一起发送`);
}
return ok;
}
private removePendingRef(id: string) {
this.pendingRefs = this.pendingRefs.filter((ref) => ref.id !== id);
this.renderPendingRefs();
}
private clearPendingRefs() {
this.pendingRefs = [];
this.renderPendingRefs();
}
private renderPendingRefs() {
if (!this.pendingRefsEl) return;
this.pendingRefsEl.empty();
this.pendingRefsEl.toggleClass('is-empty', this.pendingRefs.length === 0);
this.pendingRefs.forEach((ref) => {
buildRefChip(this.pendingRefsEl, {
id: ref.id,
title: ref.title,
extraClass: 'is-pending',
onRemove: () => this.removePendingRef(ref.id),
});
});
}
/** 列表里的引用区:一条 Memo 下方那排 chip */
private renderMemoRefs(item: HTMLElement, memo: Memo) {
const ids = outgoingReferenceIds(memo);
if (!ids.length) return;
const box = item.createDiv('memo-refs');
const base = (this.plugin.settings.serverUrl || '').replace(/\/+$/, '');
ids.forEach((id) => {
const known = this.lookupRefTitle(id);
const { chip, titleEl } = buildRefChip(box, {
id,
title: known || '',
href: `${base}/m/${id}`,
});
if (known !== null) return;
void this.resolveRefTitle(id).then((text) => {
if (!titleEl.isConnected) return;
titleEl.setText(text);
chip.setAttribute('title', `#${id} ${text}`);
});
});
}
private lookupRefTitle(id: string): string | null {
const cached = this.refTitleCache.get(id);
if (cached !== undefined) return cached;
const memo = this.memos.find((m) => String(m.id) === id);
if (memo) {
const title = memoReferenceTitle(memo, 60);
this.refTitleCache.set(id, title);
return title;
}
return null;
}
/** 被引用的 Memo 不在已加载列表里时,单独取一次正文摘要 */
private async resolveRefTitle(id: string): Promise<string> {
const hit = this.lookupRefTitle(id);
if (hit !== null) return hit;
let task = this.refTitlePending.get(id);
if (!task) {
task = this.plugin.api
.getMemo(id)
.then((memo) => memoReferenceTitle(memo, 60))
.catch(() => '(读取失败)');
this.refTitlePending.set(id, task);
}
const title = await task;
this.refTitleCache.set(id, title);
this.refTitlePending.delete(id);
return title;
}
private refreshTrayState() {
if (!this.publishBtnEl || !this.tray) return;
const busy = this.tray.busy;
const count = this.tray.count;
this.publishBtnEl.disabled = this.publishing || busy;
if (this.uploadBtnEl) {
this.uploadBtnEl.toggleClass('is-busy', busy);
this.uploadBtnEl.disabled = this.publishing;
}
// 待发图片数量做成按钮上的小角标,窄栏也不会挤掉其他控件
if (this.uploadBadgeEl) {
this.uploadBadgeEl.setText(count > 0 ? String(count) : '');
this.uploadBadgeEl.toggleClass('is-empty', count === 0);
}
if (this.uploadBtnEl) {
const tip = count > 0
? `上传图片(已添加 ${count} 张${busy ? ',上传中' : ''})`
: '上传图片(可多选,也可直接粘贴或拖入)';
this.uploadBtnEl.setAttribute('title', tip);
}
}
// ---------------- 底部 / 顶部计数 ----------------
/** 顶部计数:优先显示服务端全部条数,拿不到时才退回「已加载」并标 + */
private renderHeaderCount() {
if (!this.countEl) return;
const loaded = this.memos.length;
const total = this.totalCount;
if (total >= 0) {
this.countEl.setText(String(total));
this.countEl.setAttribute('aria-label', `共 ${total} 条 Memo`);
this.countEl.setAttribute('title', `共 ${total} 条 Memo`);
this.countEl.removeClass('is-partial');
} else if (loaded > 0) {
this.countEl.setText(loaded + (this.hasMore ? '+' : ''));
this.countEl.setAttribute('aria-label', `已加载 ${loaded} 条,正在统计总数`);
this.countEl.setAttribute('title', `已加载 ${loaded} 条,正在统计总数`);
this.countEl.addClass('is-partial');
} else {
this.countEl.setText('');
this.countEl.setAttribute('aria-label', '');
this.countEl.setAttribute('title', '');
this.countEl.removeClass('is-partial');
}
}
/** 后台统计全站条数,不阻塞列表渲染(60 秒内不重复算) */
private async refreshTotalCount(force = false) {
if (this.countingTotal) return;
if (!force && this.totalCount >= 0 && Date.now() - this.totalCountAt < 60000) return;
this.countingTotal = true;
try {
const total = await this.plugin.api.countMemos();
if (total >= 0) {
this.totalCount = total;
this.totalCountAt = Date.now();
this.renderHeaderCount();
this.updateFooter('', false);
}
} finally {
this.countingTotal = false;
}
}
private updateFooter(message: string, busy: boolean) {
if (!this.footerEl) return;
this.renderHeaderCount();
const hasFilter = this.hasActiveFilter();
// 底部只留「加载更多」:条数已经在顶部统计里显示,这里不再重复「已加载 N 条」
if (this.footerTextEl) {
this.footerTextEl.setText(message);
this.footerTextEl.toggleClass('is-empty', !message);
}
if (this.clearFilterBtnEl) {
this.clearFilterBtnEl.toggleClass('is-hidden', !hasFilter);
}
const showMore = this.hasMore && !busy;
this.loadMoreBtnEl.style.display = showMore ? '' : 'none';
this.loadMoreBtnEl.disabled = busy || this.loading;
this.loadMoreBtnEl.setText(busy ? '加载中…' : '加载更多');
// 既没有「加载更多」也没有提示时,整块收起来,别在底部留一段空白
this.footerEl.toggleClass('is-empty', !showMore && !message);
}
}
// ============================================================
// 图片预览
// ============================================================
class ImagePreviewModal extends Modal {
private url: string;
private name: string;
constructor(app: App, url: string, name: string) {
super(app);
this.url = url;
this.name = name;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass('memos-image-modal');
const img = contentEl.createEl('img', { cls: 'memos-image-full', attr: { src: this.url, alt: this.name } });
img.addEventListener('click', () => this.close());
const bar = contentEl.createDiv('memos-image-bar');
bar.createSpan({ cls: 'memos-image-name', text: this.name || '图片' });
const openBtn = bar.createEl('button', { cls: 'memos-secondary-btn', text: '在浏览器打开' });
openBtn.addEventListener('click', () => {
window.open(this.url, '_blank');
});
}
onClose() {
this.contentEl.empty();
}
}
// ============================================================
// 编辑弹窗
// ============================================================
class EditMemoModal extends Modal {
private plugin: MemosPlugin;
private memo: Memo;
private onSaved: () => void;
private textarea!: HTMLTextAreaElement;
private previewEl!: HTMLElement;
private visibilityEl!: MemosMenuSelect;
private saveBtn!: HTMLButtonElement;
private previewComponent: Component | null = null;
private previewMode = false;
private saving = false;
private allowClose = false;
private saved = false;
constructor(app: App, plugin: MemosPlugin, memo: Memo, onSaved: () => void) {
super(app);
this.plugin = plugin;
this.memo = memo;
this.onSaved = onSaved;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass('memos-edit-modal');
this.modalEl.addClass('memos-modal-wide');
contentEl.createEl('h3', { text: '编辑 Memo', cls: 'memos-modal-title' });
const toolbar = contentEl.createDiv('memos-edit-toolbar');
const previewBtn = toolbar.createEl('button', { cls: 'memos-secondary-btn', text: '预览' });
previewBtn.addEventListener('click', () => {
this.previewMode = !this.previewMode;
previewBtn.setText(this.previewMode ? '编辑' : '预览');
previewBtn.toggleClass('is-active', this.previewMode);
void this.togglePreview();
});
this.visibilityEl = new MemosMenuSelect(
toolbar,
'is-visibility',
[
{ value: 'PRIVATE', label: '私有' },
{ value: 'PUBLIC', label: '公开' },
],
this.memo.visibility === 'PUBLIC' ? 'PUBLIC' : 'PRIVATE'
);
const body = contentEl.createDiv('memos-edit-body');
this.textarea = body.createEl('textarea', { cls: 'memos-edit-textarea' });
this.textarea.value = this.memo.content || '';
this.textarea.addEventListener('keydown', (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
void this.save();
}
});
this.previewEl = body.createDiv('memos-edit-preview');
this.previewEl.style.display = 'none';
setTimeout(() => this.textarea.focus(), 50);
const actions = contentEl.createDiv('memos-modal-actions');
const cancelBtn = actions.createEl('button', { cls: 'memos-secondary-btn', text: '取消' });
cancelBtn.addEventListener('click', () => this.close());
this.saveBtn = actions.createEl('button', { cls: 'memos-primary-btn', text: '保存' });
this.saveBtn.addEventListener('click', () => void this.save());
}
private async togglePreview() {
if (this.previewMode) {
this.textarea.style.display = 'none';
this.previewEl.style.display = '';
if (this.previewComponent) this.previewComponent.unload();
this.previewComponent = new Component();
this.previewComponent.load();
this.previewEl.empty();
try {
await MarkdownRenderer.render(
this.app,
normalizeContent(this.textarea.value, this.plugin.settings.serverUrl),
this.previewEl,
'',
this.previewComponent
);
} catch {
this.previewEl.setText(this.textarea.value);
}
} else {
this.textarea.style.display = '';
this.previewEl.style.display = 'none';
}
}
private async save() {
if (this.saving) return;
const content = this.textarea.value.trim();
if (!content) {
new Notice('内容不能为空');
return;
}
const visibility = this.visibilityEl.getValue() as MemoVisibility;
const contentChanged = content !== (this.memo.content || '').trim();
const visibilityChanged = visibility !== (this.memo.visibility || 'PRIVATE');
if (!contentChanged && !visibilityChanged) {
this.allowClose = true;
this.close();
return;
}
this.saving = true;
this.saveBtn.disabled = true;
this.saveBtn.setText('保存中…');
try {
const patch: { content?: string; visibility?: MemoVisibility } = {};
if (contentChanged) patch.content = content;
if (visibilityChanged) patch.visibility = visibility;
await this.plugin.api.updateMemo(this.memo.id, patch);
this.saved = true;
this.allowClose = true;
new Notice('✅ 已更新');
this.close();
this.onSaved();
} catch (e) {
new Notice('❌ 更新失败:' + (e as Error).message, 6000);
} finally {
this.saving = false;
this.saveBtn.disabled = false;
this.saveBtn.setText('保存');
}
}
close() {
if (!this.allowClose && !this.saved) {
const dirty = this.textarea && this.textarea.value.trim() !== (this.memo.content || '').trim();
if (dirty) {
new ConfirmModal(this.app, {
title: '放弃修改?',
message: '内容已修改但尚未保存,关闭后修改将丢失。',
confirmText: '放弃修改',
danger: true,
onConfirm: () => {
this.allowClose = true;
super.close();
},
}).open();
return;
}
}
super.close();
}
onClose() {
if (this.previewComponent) {
this.previewComponent.unload();
this.previewComponent = null;
}
this.contentEl.empty();
}
}
// ============================================================
// 引用已有 Memo 弹窗
// ============================================================
type QuoteInsertMode = 'composer' | 'note';
interface QuoteHandlers {
/** 把引用(MemoRelation)加进输入区,返回是否成功 */
toComposer: (memos: Memo[]) => boolean;
/** 把引用文本插入到当前笔记 */
toNote: (markdown: string) => { ok: boolean; note?: string };
}
class QuoteMemoModal extends Modal {
private plugin: MemosPlugin;
private handlers: QuoteHandlers;
private defaultMode: QuoteInsertMode;
private inputEl!: HTMLInputElement;
private statusEl!: HTMLElement;
private previewEl!: HTMLElement;
private composerBtn!: HTMLButtonElement;
private noteBtn!: HTMLButtonElement;
private resolved: Memo[] = [];
private seq = 0;
private lookupTimer: number | null = null;
constructor(
app: App,
plugin: MemosPlugin,
handlers: QuoteHandlers,
defaultMode: QuoteInsertMode = 'note'
) {
super(app);
this.plugin = plugin;
this.handlers = handlers;
this.defaultMode = defaultMode;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass('memos-quote-modal');
this.modalEl.addClass('memos-modal-wide');
contentEl.createEl('h3', { text: '引用已有 Memo', cls: 'memos-modal-title' });
contentEl.createEl('p', {
cls: 'memos-quote-desc',
text: '输入 Memo ID,可填多个(空格或逗号分隔),也支持直接粘贴链接。插入的是网页版那种引用标题(可点击跳回原 Memo),会接在正文下方。',
});
this.inputEl = contentEl.createEl('input', {
cls: 'memos-quote-input',
attr: { type: 'text', placeholder: '例如:613 或 613,614 或 https://…/m/613', spellcheck: 'false' },
});
this.statusEl = contentEl.createDiv({ cls: 'memos-quote-status', text: '输入 ID 后自动预览' });
this.previewEl = contentEl.createDiv('memos-quote-preview is-empty');
const actions = contentEl.createDiv('memos-modal-actions');
const cancel = actions.createEl('button', { cls: 'memos-secondary-btn', text: '取消' });
cancel.addEventListener('click', () => this.close());
this.composerBtn = actions.createEl('button', {
cls: this.defaultMode === 'composer' ? 'memos-primary-btn' : 'memos-secondary-btn',
text: '插入输入框',
attr: { title: '把引用接进边栏输入框,可继续编辑后发布' },
});
this.composerBtn.disabled = true;
this.composerBtn.addEventListener('click', () => this.insert('composer'));
this.noteBtn = actions.createEl('button', {
cls: this.defaultMode === 'note' ? 'memos-primary-btn' : 'memos-secondary-btn',
text: '插入当前笔记',
attr: { title: '把引用块写进当前打开笔记的光标处' },
});
this.noteBtn.disabled = true;
this.noteBtn.addEventListener('click', () => this.insert('note'));
this.inputEl.addEventListener('input', () => this.scheduleLookup());
this.inputEl.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key !== 'Enter') return;
e.preventDefault();
// 还没预览出结果就回车:先查再插,省一次点击
if (!this.resolved.length) {
void this.lookup().then(() => this.insert(this.defaultMode));
} else {
this.insert(this.defaultMode);
}
});
setTimeout(() => this.inputEl.focus(), 40);
}
private parseIds(text: string): string[] {
const ids: string[] = [];
const matches = text.match(/\d+/g) || [];
for (const raw of matches) {
if (ids.indexOf(raw) === -1) ids.push(raw);
}
return ids;
}
private scheduleLookup() {
if (this.lookupTimer !== null) window.clearTimeout(this.lookupTimer);
this.lookupTimer = window.setTimeout(() => {
this.lookupTimer = null;
void this.lookup();
}, 350);
}
private async lookup() {
const ids = this.parseIds(this.inputEl.value);
const seq = ++this.seq;
if (!ids.length) {
this.resolved = [];
this.renderPreview();
this.statusEl.setText('输入 ID 后自动预览');
this.statusEl.removeClass('is-error');
this.setButtonsEnabled(false);
return;
}
this.statusEl.setText(`查询 ${ids.length} 条…`);
this.statusEl.removeClass('is-error');
const found: Memo[] = [];
const missing: string[] = [];
for (const id of ids) {
try {
found.push(await this.plugin.api.getMemo(id));
} catch {
missing.push(id);
}
if (seq !== this.seq) return;
}
this.resolved = found;
this.renderPreview();
if (!found.length) {
this.statusEl.setText(`未找到:${missing.join(', ')}`);
this.statusEl.addClass('is-error');
} else if (missing.length) {
this.statusEl.setText(`找到 ${found.length} 条,未找到:${missing.join(', ')}`);
this.statusEl.addClass('is-error');
} else {
this.statusEl.setText(`找到 ${found.length} 条,可插入`);
this.statusEl.removeClass('is-error');
}
this.setButtonsEnabled(found.length > 0);
}
private setButtonsEnabled(on: boolean) {
this.composerBtn.disabled = !on;
this.noteBtn.disabled = !on;
}
private renderPreview() {
this.previewEl.empty();
this.previewEl.toggleClass('is-empty', !this.resolved.length);
this.resolved.forEach((memo) => {
const row = this.previewEl.createDiv('memos-quote-item');
const head = row.createDiv('memos-quote-head');
head.createSpan({ cls: 'memo-id', text: `#${memo.id}` });
head.createSpan({ cls: 'memos-quote-time', text: formatAbsolute(memoTime(memo)) });
if (memo.visibility === 'PUBLIC') head.createSpan({ cls: 'memo-vis', text: '公开' });
const text = stripForPreview(memo.content);
row.createDiv({
cls: 'memos-quote-text',
text: text.length > 140 ? text.slice(0, 140) + '…' : text || '(无正文)',
});
const images = (memo.resourceList || []).filter(
(r) => !!r.externalLink && !!r.type && r.type.indexOf('image/') === 0
);
if (images.length) {
row.createDiv({ cls: 'memos-quote-meta', text: `含 ${images.length} 张图片` });
}
});
}
private insert(mode: QuoteInsertMode) {
if (!this.resolved.length) {
new Notice('没有可插入的 Memo,请先输入有效 ID');
return;
}
if (mode === 'composer') {
// 输入框走「引用关系」:正文保持干净,发布后和网页端一样显示引用卡片
if (!this.handlers.toComposer(this.resolved)) {
new Notice('没有可用的输入框');
return;
}
new Notice(`已引用 ${this.resolved.length} 条,发布时随 Memo 发送`);
} else {
const md = this.resolved
.map((memo) => memoToQuote(memo, this.plugin.settings.serverUrl))
.join('\n');
const res = this.handlers.toNote(md);
if (!res.ok) {
new Notice('没有可用的笔记:请先打开一个 Markdown 笔记');
return;
}
new Notice(`已引用 ${this.resolved.length} 条到「${res.note}」`);
}
this.close();
}
onClose() {
if (this.lookupTimer !== null) {
window.clearTimeout(this.lookupTimer);
this.lookupTimer = null;
}
this.contentEl.empty();
}
}
// ============================================================
// 快速记录弹窗
// ============================================================
class ComposeMemoModal extends Modal {
private plugin: MemosPlugin;
private initial: string;
private onDone: () => void;
private textarea!: HTMLTextAreaElement;
private attachmentsEl!: HTMLElement;
private refsEl!: HTMLElement;
private tray!: AttachmentTray;
private visibilityEl!: MemosMenuSelect;
private submitBtn!: HTMLButtonElement;
private submitting = false;
/** 待发布的引用(发布时作为 MemoRelation 发送) */
private pendingRefs: { id: string; title: string }[] = [];
constructor(app: App, plugin: MemosPlugin, initial: string, onDone: () => void) {
super(app);
this.plugin = plugin;
this.initial = initial;
this.onDone = onDone;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass('memos-compose-modal');
this.modalEl.addClass('memos-modal-wide');
contentEl.createEl('h3', { text: '快速记录', cls: 'memos-modal-title' });
this.textarea = contentEl.createEl('textarea', { cls: 'memos-edit-textarea' });
this.textarea.value = this.initial;
this.textarea.setAttribute('placeholder', '写点什么…支持 Markdown 与 #标签,可粘贴/拖入图片');
this.refsEl = contentEl.createDiv('memos-pending-refs is-empty');
this.attachmentsEl = contentEl.createDiv('memos-attachments is-empty');
this.tray = new AttachmentTray(this.attachmentsEl, this.plugin, () => this.syncSubmitState());
wireAttachmentDnD(this.textarea, contentEl, this.tray);
const actions = contentEl.createDiv('memos-modal-actions');
this.visibilityEl = new MemosMenuSelect(
actions,
'is-visibility',
[
{ value: 'PRIVATE', label: '私有' },
{ value: 'PUBLIC', label: '公开' },
],
this.plugin.settings.defaultVisibility
);
const upload = actions.createEl('button', { cls: 'memos-upload-btn is-labeled' });
setIcon(upload, firstAvailableIcon('image-plus', 'image', 'upload'));
upload.createSpan({ cls: 'memos-upload-label', text: '上传图片' });
// 引用:加一个引用 chip,发布时作为 MemoRelation 发送
const quote = actions.createEl('button', { cls: 'memos-tool-btn' });
setIcon(quote, firstAvailableIcon('quote', 'text-quote', 'message-square-quote'));
quote.setAttribute('aria-label', '引用已有 Memo');
quote.setAttribute('title', '引用已有 Memo:输入 ID,发布后与网页端一样显示成引用卡片');
quote.addEventListener('click', () => {
new QuoteMemoModal(
this.app,
this.plugin,
{
toComposer: (memos) => this.addRefs(memos),
toNote: (md) => insertIntoNote(this.app, md),
},
'composer'
).open();
});
// 待办:插入 `- [ ] `,发布后可在列表里勾选
const task = actions.createEl('button', { cls: 'memos-tool-btn' });
setIcon(task, firstAvailableIcon('list-todo', 'list-checks', 'check-square'));
task.setAttribute('aria-label', '插入待办事项');
task.setAttribute('title', '插入待办事项:发布后可在列表里勾选完成');
task.addEventListener('click', () => this.insertTask());
upload.setAttribute('aria-label', '上传图片(可多选)');
upload.addEventListener('click', () => {
pickImageFiles((files) => void this.tray.add(files));
});
const spacer = actions.createDiv('memos-actions-spacer');
spacer.style.flex = '1';
const cancel = actions.createEl('button', { cls: 'memos-secondary-btn', text: '取消' });
cancel.addEventListener('click', () => this.close());
this.submitBtn = actions.createEl('button', { cls: 'memos-primary-btn', text: '发布' });
this.submitBtn.addEventListener('click', () => void this.submit());
this.textarea.addEventListener('keydown', (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
void this.submit();
}
});
setTimeout(() => this.textarea.focus(), 50);
}
private syncSubmitState() {
if (!this.submitBtn || !this.tray) return;
this.submitBtn.disabled = this.submitting || this.tray.busy;
}
/** 加引用 chip(弹窗里的引用入口调它) */
private addRefs(memos: Memo[]): boolean {
if (!this.refsEl) return false;
for (const memo of memos) {
const id = String(memo.id);
if (this.pendingRefs.some((ref) => ref.id === id)) continue;
this.pendingRefs.push({ id, title: memoReferenceTitle(memo, 60) });
}
this.renderRefs();
this.textarea.focus();
return true;
}
private renderRefs() {
if (!this.refsEl) return;
this.refsEl.empty();
this.refsEl.toggleClass('is-empty', this.pendingRefs.length === 0);
this.pendingRefs.forEach((ref) => {
buildRefChip(this.refsEl, {
id: ref.id,
title: ref.title,
extraClass: 'is-pending',
onRemove: () => {
this.pendingRefs = this.pendingRefs.filter((item) => item.id !== ref.id);
this.renderRefs();
},
});
});
}
/** 在弹窗输入框插入待办标记 */
private insertTask() {
const el = this.textarea;
const start = el.selectionStart ?? el.value.length;
const end = el.selectionEnd ?? start;
const res = applyTaskPrefix(el.value, start, end);
el.value = res.value;
el.selectionStart = el.selectionEnd = res.caret;
el.focus();
}
private async submit() {
if (this.submitting) return;
if (this.tray.busy) {
new Notice('图片还在上传中,请稍候');
return;
}
const text = this.textarea.value.trim();
const ids = this.tray.ids;
if (!text && !ids.length) {
new Notice('请输入内容或添加图片');
return;
}
this.submitting = true;
this.submitBtn.disabled = true;
this.submitBtn.setText('发布中…');
try {
await this.plugin.api.createMemo(
normalizeContent(text, this.plugin.settings.serverUrl),
this.visibilityEl.getValue() as MemoVisibility,
ids,
this.pendingRefs.map((ref) => ref.id)
);
new Notice('✅ 已发布');
this.close();
this.onDone();
} catch (e) {
new Notice('❌ 发布失败:' + (e as Error).message, 6000);
} finally {
this.submitting = false;
this.syncSubmitState();
this.submitBtn.setText('发布');
}
}
onClose() {
this.contentEl.empty();
}
}
// ============================================================
// 确认弹窗
// ============================================================
interface ConfirmOptions {
title: string;
message: string;
confirmText?: string;
cancelText?: string;
danger?: boolean;
onConfirm: () => void | Promise<void>;
}
class ConfirmModal extends Modal {
private opts: ConfirmOptions;
constructor(app: App, opts: ConfirmOptions) {
super(app);
this.opts = opts;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass('memos-confirm-modal');
contentEl.createEl('h3', { text: this.opts.title, cls: 'memos-modal-title' });
contentEl.createEl('p', { text: this.opts.message, cls: 'memos-confirm-text' });
const actions = contentEl.createDiv('memos-modal-actions');
const cancel = actions.createEl('button', {
cls: 'memos-secondary-btn',
text: this.opts.cancelText || '取消',
});
cancel.addEventListener('click', () => this.close());
const confirm = actions.createEl('button', {
cls: this.opts.danger ? 'memos-danger-btn' : 'memos-primary-btn',
text: this.opts.confirmText || '确认',
});
confirm.addEventListener('click', () => {
this.close();
void this.opts.onConfirm();
});
}
onClose() {
this.contentEl.empty();
}
}
// ============================================================
// 设置页
// ============================================================
class MemosSettingTab extends PluginSettingTab {
plugin: MemosPlugin;
private statusEl: HTMLElement | null = null;
private versionEl: HTMLElement | null = null;
constructor(app: App, plugin: MemosPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.addClass('memos-settings');
containerEl.createEl('h2', { text: 'Memos 设置' });
new Setting(containerEl)
.setName('服务器地址')
.setDesc('Memos 实例地址,例如 https://me.sangushui.com')
.addText((text) => {
text.setPlaceholder('https://me.sangushui.com')
.setValue(this.plugin.settings.serverUrl)
.onChange(async (value) => {
this.plugin.settings.serverUrl = value.trim();
await this.plugin.saveSettings();
});
text.inputEl.addClass('memos-setting-input');
});
new Setting(containerEl)
.setName('API Token')
.setDesc('Memos 中:设置 → 我的账户 → API Token')
.addText((text) => {
text.setPlaceholder('粘贴 API Token')
.setValue(this.plugin.settings.apiToken)
.onChange(async (value) => {
this.plugin.settings.apiToken = value.trim();
await this.plugin.saveSettings();
});
text.inputEl.type = 'password';
text.inputEl.addClass('memos-setting-input');
})
.addExtraButton((btn) => {
btn.setIcon('eye').setTooltip('显示 / 隐藏').onClick(() => {
const input = btn.extraSettingsEl.parentElement?.querySelector('input');
if (input) input.type = input.type === 'password' ? 'text' : 'password';
});
});
new Setting(containerEl)
.setName('每页条数')
.setDesc('一次加载多少条 Memo(1 - 200)')
.addText((text) => {
text.inputEl.type = 'number';
text.inputEl.min = '1';
text.inputEl.max = '200';
text.setValue(String(this.plugin.settings.pageSize));
text.onChange(async (value) => {
const num = parseInt(value, 10);
if (!isNaN(num) && num >= 1 && num <= 200) {
this.plugin.settings.pageSize = num;
await this.plugin.saveSettings();
}
});
text.inputEl.addEventListener('blur', () => {
text.setValue(String(this.plugin.settings.pageSize));
this.plugin.refreshViews();
});
text.inputEl.addClass('memos-setting-input is-narrow');
});
new Setting(containerEl)
.setName('默认可见性')
.setDesc('发布时默认使用的可见性')
.addDropdown((dd) => {
dd.addOption('PRIVATE', '私有');
dd.addOption('PUBLIC', '公开');
dd.setValue(this.plugin.settings.defaultVisibility);
dd.onChange(async (value) => {
this.plugin.settings.defaultVisibility = value as MemoVisibility;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('显示图片附件')
.setDesc('在边栏中展示 Memo 附带的图片')
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.showImages).onChange(async (value) => {
this.plugin.settings.showImages = value;
await this.plugin.saveSettings();
this.plugin.refreshViews();
});
});
new Setting(containerEl)
.setName('显示标签筛选')
.setDesc('在边栏显示标签下拉筛选(关闭后隐藏该下拉)')
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.showTags).onChange(async (value) => {
this.plugin.settings.showTags = value;
await this.plugin.saveSettings();
this.plugin.refreshViews();
});
});
new Setting(containerEl)
.setName('滚动自动加载')
.setDesc('滚动到底部时自动加载下一页')
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.autoLoadMore).onChange(async (value) => {
this.plugin.settings.autoLoadMore = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('调试日志')
.setDesc('在开发者控制台输出请求日志')
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.debug).onChange(async (value) => {
this.plugin.settings.debug = value;
await this.plugin.saveSettings();
});
});
const testSetting = new Setting(containerEl)
.setName('连接测试')
.setDesc('使用当前 Token 访问一次账户信息');
testSetting.addButton((btn) => {
btn.setButtonText('测试连接').setCta().onClick(async () => {
if (!this.plugin.settings.apiToken) {
this.setStatus('请先填写 API Token', 'error');
return;
}
this.setStatus('测试中…', 'pending');
try {
const [me, status] = await Promise.all([
this.plugin.api.me(),
this.plugin.api.status(),
]);
const who = me.nickname || me.username || '未知用户';
const version = status.profile?.version || '未知版本';
this.setStatus(`连接成功 · ${who} · v${version}`, 'success');
} catch (e) {
this.setStatus((e as Error).message, 'error');
}
});
});
this.statusEl = testSetting.controlEl.createSpan({ cls: 'memos-connection-status' });
containerEl.createEl('hr');
const info = containerEl.createDiv('memos-settings-tips');
info.innerHTML = `
<p>1. 点击左侧 <strong>💬 图标</strong> 或命令「打开 Memos 边栏」</p>
<p>2. 输入框支持 <strong>Markdown</strong>,<kbd>Ctrl/⌘ + Enter</kbd> 发布,未发布内容自动存草稿</p>
<p>3. 支持 <strong>搜索</strong>、<strong>按标签 / 可见性筛选</strong>、<strong>滚动加载</strong></p>
<p>4. 每条 Memo 可 <strong>编辑</strong>、<strong>复制</strong>、<strong>插入到当前笔记</strong>、<strong>置顶</strong>、<strong>删除</strong></p>
<p>5. 命令「快速记录一条 Memo」可绑定热键,随时捕捉想法</p>
`;
this.versionEl = containerEl.createDiv('memos-settings-version');
this.versionEl.setText(`插件版本 v${this.plugin.manifest.version} · 兼容 Memos v0.18+(含新版 API 自动回退)`);
}
private setStatus(text: string, kind: 'success' | 'error' | 'pending') {
if (!this.statusEl) return;
this.statusEl.setText(text);
this.statusEl.removeClass('is-success', 'is-error', 'is-pending');
this.statusEl.addClass(kind === 'success' ? 'is-success' : kind === 'error' ? 'is-error' : 'is-pending');
}
}