944 lines
30 KiB
TypeScript
944 lines
30 KiB
TypeScript
import { App, Modal, Notice } from "obsidian";
|
||
import { getSettings, saveSettings, getSites, getActiveSite, getSite } from "../main";
|
||
import { addMetas } from "./add_metasl";
|
||
import { HttpUtils } from "../utils/request";
|
||
import i18n from "../utils/i18n";
|
||
import { Util } from "../utils/util";
|
||
import { renderCategoryPanel, renderTagPanel } from "./category_tree";
|
||
import {
|
||
readTypechoMetaFresh,
|
||
writeTypechoMeta,
|
||
} from "../utils/frontmatter";
|
||
import { formatBeijingTime } from "../utils/datetime";
|
||
|
||
const YAML_BLOCK = /^---\s*[\s\S]*?---\s*/;
|
||
const VERSION_SUFFIX = /\(v\d+\)-\d+$/;
|
||
const RENAME_PREFIX = /^.*?_改为_/;
|
||
|
||
/**
|
||
* 记住最近一次 ribbon/命令打开发布框时聚焦的笔记路径。
|
||
*
|
||
* 多窗口场景下 getActiveFile() 是「全局最后聚焦的文件」,弹窗打开过程中
|
||
* 焦点可能被别的窗口抢走,导致 onOpen 里前后两次 getActiveFile() 拿到不同
|
||
* 笔记:站点推断用 A、笔记加载用 B,分类/标签就勾不上。这里把路径冻结在
|
||
* onOpen 开头一次,后续站点推断、笔记加载、回填全部复用它。
|
||
*/
|
||
let lastFocusedNotePath = "";
|
||
|
||
export class PushModal extends Modal {
|
||
constructor(app: App) {
|
||
super(app);
|
||
}
|
||
notice: Notice;
|
||
baseFileName = "";
|
||
title = "";
|
||
slug = "";
|
||
slugInput: HTMLInputElement;
|
||
content = "";
|
||
selectedTags: string[] = [];
|
||
selectedCategories: string[] = [];
|
||
categoriesDom: HTMLElement;
|
||
tagsDom: HTMLElement;
|
||
activeFilePath: string;
|
||
|
||
async onOpen() {
|
||
const { contentEl } = this;
|
||
contentEl.empty();
|
||
contentEl.createEl("h2", { text: i18n.t("sync.title") });
|
||
|
||
// 只在这里取一次聚焦笔记路径,冻结给本次弹窗全程使用。
|
||
// getActiveFile() 在多窗口下会随焦点变化,前后两次调用可能拿到不同笔记,
|
||
// 导致「站点按 A 推断、笔记按 B 加载」,分类/标签自然勾不上。
|
||
const activeFileAtOpen = this.app.workspace.getActiveFile();
|
||
const notePath = activeFileAtOpen?.path || lastFocusedNotePath;
|
||
if (notePath) lastFocusedNotePath = notePath;
|
||
|
||
// 默认站点按这篇笔记的 ty-url 域名推断,避免笔记属于 B 站、
|
||
// 当前激活的是 A 站时首屏就匹配不到分类/标签
|
||
const preferredSite = await this.preferredSiteForNote(notePath);
|
||
this.renderSiteSelector(contentEl, preferredSite?.id);
|
||
|
||
await this.getCategories(contentEl);
|
||
await this.getTags(contentEl);
|
||
|
||
// 标题输入
|
||
const titleInput = contentEl.createEl("input", {
|
||
attr: {
|
||
type: "text",
|
||
placeholder: `${i18n.t("common.input")} ${i18n.t("field.title")}`,
|
||
style:
|
||
"width: 100%; margin-top: 15px; margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);",
|
||
},
|
||
});
|
||
titleInput.addEventListener("input", (event) => {
|
||
this.title = (event.target as HTMLInputElement).value;
|
||
});
|
||
|
||
// 等笔记属性回填完成再走完 onOpen:之前是 fire-and-forget,
|
||
// 回填里的重绘可能发生在弹窗其余控件之后,表现为「slug 有、分类标签没有」
|
||
await this.renderFileSelector(contentEl, titleInput);
|
||
this.renderSlugField(contentEl);
|
||
this.renderPublishButton(contentEl);
|
||
}
|
||
|
||
/**
|
||
* 按笔记属性里 ty-url 的域名,推断这篇笔记属于哪个站点。
|
||
* 找不到就返回 null,让调用方沿用当前激活站点。
|
||
*/
|
||
private async preferredSiteForNote(path: string) {
|
||
if (!path) return null;
|
||
const meta = await readTypechoMetaFresh(this.app, path);
|
||
if (!meta.url) return null;
|
||
|
||
const normalize = (host: string) =>
|
||
host
|
||
.replace(/^https?:\/\//i, "")
|
||
.replace(/^www\./i, "")
|
||
.replace(/\/.*$/, "")
|
||
.toLowerCase();
|
||
const noteHost = normalize(meta.url);
|
||
const sites = getSites();
|
||
return (
|
||
sites.find((site) => normalize(site.Host || "") === noteHost) || null
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 多站点选择器
|
||
*/
|
||
private renderSiteSelector(contentEl: HTMLElement, preferredSiteId?: string) {
|
||
const sites = getSites();
|
||
if (sites.length === 0) return;
|
||
|
||
const siteDiv = contentEl.createDiv({
|
||
attr: { style: "margin-bottom: 15px;" },
|
||
});
|
||
siteDiv.createEl("label", {
|
||
text: i18n.t("sync.selectSite"),
|
||
attr: { style: "margin-right: 10px;" },
|
||
});
|
||
const siteSelect = siteDiv.createEl("select");
|
||
|
||
const defaultSiteId = preferredSiteId || getActiveSite()?.id;
|
||
for (const site of sites) {
|
||
siteSelect.createEl("option", {
|
||
text: site.name,
|
||
value: site.id,
|
||
});
|
||
}
|
||
|
||
// 不依赖 option.selected 的 DOM 副作用:直接用推断出的 id 设置 value。
|
||
// 某些 Obsidian 版本里 createEl 后再改 selected 不会同步到 select.value,
|
||
// 结果列表拉的是 A 站、select 显示 B 站,切换前后对不上。
|
||
if (defaultSiteId) siteSelect.value = defaultSiteId;
|
||
|
||
const initSite = getSite(siteSelect.value) || getActiveSite();
|
||
if (initSite) {
|
||
HttpUtils.setCurrentSite(initSite.Host, initSite.Token);
|
||
}
|
||
|
||
siteSelect.addEventListener("change", async () => {
|
||
const selectedSite = getSite(siteSelect.value);
|
||
if (!selectedSite) return;
|
||
HttpUtils.setCurrentSite(selectedSite.Host, selectedSite.Token);
|
||
// 只重新拉列表会把之前的勾选清空;必须按当前笔记属性再匹配一次
|
||
// (restoreSelection 内部自带列表渲染,不用在这里单独 getCategories/getTags)
|
||
await this.restoreSelection();
|
||
new Notice(i18n.t("sync.switchedTo", { name: selectedSite.name }));
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 笔记文件选择器
|
||
*/
|
||
private async renderFileSelector(
|
||
contentEl: HTMLElement,
|
||
titleInput: HTMLInputElement
|
||
): Promise<void> {
|
||
const files = this.app.vault.getFiles();
|
||
// 优先用 onOpen 开头冻结的路径:多窗口下这里再取一次 getActiveFile()
|
||
// 可能已经指向另一个窗口的笔记,和站点推断用的那篇不是同一篇。
|
||
this.activeFilePath = lastFocusedNotePath;
|
||
|
||
const selectEl = contentEl.createEl("select", {
|
||
attr: {
|
||
style:
|
||
"width: 100%; margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);",
|
||
},
|
||
});
|
||
|
||
for (const file of files) {
|
||
if (!file.path.endsWith(".md")) continue;
|
||
selectEl.createEl("option", {
|
||
text: file.path,
|
||
value: file.path,
|
||
});
|
||
}
|
||
|
||
// 冻结路径可能属于另一个库的窗口(多窗口各开不同库),在当前库里
|
||
// 并不存在。逐层回退到一个真实存在的 md,保证一定能加载并回填。
|
||
const exists = (p: string) => !!p && !!this.app.vault.getFileByPath(p);
|
||
if (!exists(this.activeFilePath)) {
|
||
const activeFile = this.app.workspace.getActiveFile();
|
||
this.activeFilePath = exists(activeFile?.path || "")
|
||
? activeFile!.path
|
||
: "";
|
||
}
|
||
if (!this.activeFilePath && selectEl.value) {
|
||
this.activeFilePath = selectEl.value;
|
||
}
|
||
|
||
// 关键:无论来自哪条路径,都要真正 loadNote 一次。
|
||
// restoreSelection 是在 loadNote → setTitleFromFileName 里触发的;
|
||
// 旧代码只在 activeFilePath 恰好命中某文件时才 loadNote,冻结路径
|
||
// 一旦不在列表里就整段跳过,表现为「提示获取分类/标签却没勾选」。
|
||
if (this.activeFilePath) {
|
||
selectEl.value = this.activeFilePath;
|
||
await this.loadNote(this.activeFilePath, titleInput);
|
||
}
|
||
|
||
selectEl.addEventListener("change", async (event) => {
|
||
const selectedFilePath = (event.target as HTMLSelectElement).value;
|
||
if (!selectedFilePath) {
|
||
new Notice(i18n.t("error.noFileSelected"));
|
||
return;
|
||
}
|
||
await this.loadNote(selectedFilePath, titleInput);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 选中一篇笔记:先读内容再设标题。
|
||
*
|
||
* 两件事必须按顺序做完,否则会出现「标题是新的、正文还是上一篇」的错配:
|
||
* 读取本身是异步的,早先版本没有 await,点发布时 this.content 可能还是空串
|
||
* 或上一次的文件内容。
|
||
*/
|
||
private async loadNote(path: string, titleInput: HTMLInputElement) {
|
||
await this.readFileAndSetContent(path);
|
||
await this.setTitleFromFileName(path, titleInput);
|
||
}
|
||
|
||
/**
|
||
* 高级选项:别名
|
||
*/
|
||
private renderSlugField(contentEl: HTMLElement) {
|
||
const advancedDetails = contentEl.createEl("details", {
|
||
attr: {
|
||
style:
|
||
"margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; padding: 10px;",
|
||
},
|
||
});
|
||
advancedDetails.createEl("summary", {
|
||
text: i18n.t("sync.advancedOptions"),
|
||
attr: {
|
||
style:
|
||
"cursor: pointer; color: var(--text-muted); font-size: 0.9em;",
|
||
},
|
||
});
|
||
|
||
const slugContainer = advancedDetails.createDiv({
|
||
attr: { style: "margin-top: 10px;" },
|
||
});
|
||
slugContainer.createEl("label", {
|
||
text: i18n.t("sync.alias"),
|
||
attr: {
|
||
style:
|
||
"display: block; font-size: 0.8em; color: var(--text-muted); margin-bottom: 5px;",
|
||
},
|
||
});
|
||
|
||
this.slugInput = slugContainer.createEl("input", {
|
||
attr: {
|
||
type: "text",
|
||
placeholder: "Slug",
|
||
style:
|
||
"width: 100%; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);",
|
||
},
|
||
});
|
||
this.slugInput.value = this.slug;
|
||
this.slugInput.addEventListener("input", (event) => {
|
||
this.slug = (event.target as HTMLInputElement).value;
|
||
});
|
||
}
|
||
|
||
private renderPublishButton(contentEl: HTMLElement) {
|
||
const button = contentEl.createEl("button", {
|
||
text: i18n.t("sync.publish"),
|
||
attr: {
|
||
style:
|
||
"margin-top: 15px; padding: 8px 16px; border: none; border-radius: 4px; color: var(--text-normal); cursor: pointer;",
|
||
},
|
||
});
|
||
button.addEventListener("click", () => this.publish());
|
||
}
|
||
|
||
/**
|
||
* 发布 / 更新
|
||
*/
|
||
private async publish() {
|
||
// 兜底:弹窗刚打开就点发布,异步读取可能还没回填,这里补读一次
|
||
if (this.content === "" && this.activeFilePath) {
|
||
await this.readFileAndSetContent(this.activeFilePath);
|
||
}
|
||
|
||
if (this.title === "" || this.content === "") {
|
||
new Notice(i18n.t("error.titleOrContentCannotBeEmpty"));
|
||
return;
|
||
}
|
||
|
||
this.notice = new Notice(i18n.t("sync.publishing"));
|
||
try {
|
||
const mid = [...this.selectedCategories, ...this.selectedTags];
|
||
|
||
let finalContent = this.content;
|
||
if (getSettings().removeMetadata) {
|
||
finalContent = finalContent.replace(YAML_BLOCK, "");
|
||
}
|
||
|
||
const filePath =
|
||
this.activeFilePath || (await this.getSelectedFilePath());
|
||
const meta = await readTypechoMetaFresh(this.app, filePath);
|
||
|
||
// 传给服务端的 originalTitle 保留旧值(用于判断是否改过标题),
|
||
// 但写回笔记属性的必须是本次发布的实际标题,否则改了标题后
|
||
// 属性面板永远显示旧标题,下次回填又用旧的。
|
||
let originalTitle = meta.title || this.title;
|
||
originalTitle = originalTitle.replace(VERSION_SUFFIX, "");
|
||
const syncedTitle = this.title
|
||
.replace(VERSION_SUFFIX, "")
|
||
.replace(RENAME_PREFIX, "")
|
||
.trim();
|
||
|
||
// ========== 自动插入 Obsidian 标识 ==========
|
||
const isUpdate = !!meta.cid;
|
||
if (getSettings().enableSignature) {
|
||
const signatureHtml = isUpdate
|
||
? '<div class="obsidian-signature updated">本文从 Obsidian 修改更新</div>'
|
||
: '<div class="obsidian-signature created">本文从 Obsidian 撰写发布</div>';
|
||
finalContent = signatureHtml + "\n\n" + finalContent;
|
||
}
|
||
|
||
const data: any = {
|
||
title: this.title,
|
||
text: "<!--markdown-->" + finalContent,
|
||
authorId: HttpUtils.getCurrentUserUid(),
|
||
mid: mid.join(","),
|
||
slug: this.slug || meta.slug || undefined,
|
||
originalTitle: originalTitle,
|
||
};
|
||
if (meta.cid) data.cid = meta.cid;
|
||
|
||
const response = await HttpUtils.post("/postArticle", data);
|
||
if (response.status !== "success") {
|
||
this.notice.hide();
|
||
return;
|
||
}
|
||
|
||
const savedCid = await this.resolveCid(response, meta.cid);
|
||
// 跳转链接:接口没给(或给的是占位符)就按 cid 再问一次
|
||
const permalink = await this.resolvePermalink(response, savedCid);
|
||
|
||
if (savedCid && filePath) {
|
||
const categoryNames = await this.getCategoryNamesByIds(
|
||
this.selectedCategories
|
||
);
|
||
const tagNames = await this.getTagNamesByIds(this.selectedTags);
|
||
const file = this.app.vault.getFileByPath(filePath);
|
||
if (file) {
|
||
await writeTypechoMeta(this.app, file, {
|
||
cid: savedCid,
|
||
slug: this.slug,
|
||
url: permalink,
|
||
categories: categoryNames,
|
||
tags: tagNames,
|
||
title: syncedTitle,
|
||
// 首次发布就从现在算起;更新已有文章时沿用笔记里原来的发布时间
|
||
created: meta.created || formatBeijingTime(),
|
||
});
|
||
}
|
||
|
||
if (this.baseFileName) {
|
||
getSettings().slugMapping[this.baseFileName] = this.slug;
|
||
await saveSettings();
|
||
}
|
||
}
|
||
|
||
this.notice.hide();
|
||
new Notice(
|
||
`${isUpdate ? i18n.t("sync.updated") : i18n.t("sync.created")}${i18n.t("common.success")}`
|
||
);
|
||
|
||
// 发布后跳转到网站上的文章页(先打开再关弹窗,避免关窗后
|
||
// 浏览器把这次 window.open 当成无用户操作的弹窗拦掉)
|
||
if (getSettings().openAfterPublish) {
|
||
if (permalink) {
|
||
this.openInBrowser(permalink);
|
||
} else {
|
||
new Notice(
|
||
i18n.t("sync.permalinkMissing", {
|
||
cid: savedCid ? String(savedCid) : "-",
|
||
}),
|
||
8000
|
||
);
|
||
}
|
||
}
|
||
this.close();
|
||
} catch (error) {
|
||
this.notice.hide();
|
||
// HttpUtils 已经弹过具体原因(HTTP 500 / 接口不存在 / 服务器原文),
|
||
// 这里只在它没弹过时补一句,避免两条提示叠在一起互相盖住
|
||
if (!(error as any)?.__notified) {
|
||
new Notice(`${i18n.t("sync.publish")} ${i18n.t("common.failed")}`);
|
||
}
|
||
console.error("publish failed:", error);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 取本次发布后的真实 cid。
|
||
*
|
||
* 新增文章时,后端 `insert()` 的返回值在部分 Typecho 版本下不是真实 cid
|
||
* (可能是个布尔值,转成数字就成了 1),只有更新分支才稳定返回 cid。
|
||
* 所以新增时再用 slug 反查一次,以接口返回的真实 cid 为准。
|
||
*/
|
||
private async resolveCid(
|
||
response: any,
|
||
fallback: number | null
|
||
): Promise<number | null> {
|
||
const cid = this.pickCid(response, fallback);
|
||
|
||
const isAdd = response?.data?.type === "add";
|
||
const slug =
|
||
typeof response?.data?.slug === "string" ? response.data.slug.trim() : "";
|
||
if (!isAdd || !slug) return cid;
|
||
|
||
try {
|
||
// silent = true:反查失败不打扰用户,沿用后端返回值即可
|
||
const res = await HttpUtils.get(
|
||
`/post?slug=${encodeURIComponent(slug)}`,
|
||
undefined,
|
||
true
|
||
);
|
||
const real = Number(res?.data?.cid);
|
||
if (Number.isFinite(real) && real > 0) return real;
|
||
} catch (error) {
|
||
console.warn("[typecho] 按 slug 反查 cid 失败,沿用后端返回值", error);
|
||
}
|
||
|
||
return cid;
|
||
}
|
||
|
||
private pickCid(response: any, fallback: number | null): number | null {
|
||
const candidates = [
|
||
response?.data?.cid,
|
||
response?.data?.id,
|
||
typeof response?.data === "number" ? response.data : null,
|
||
response?.cid,
|
||
response?.id,
|
||
fallback,
|
||
];
|
||
for (const value of candidates) {
|
||
const cid = Number(value);
|
||
if (Number.isFinite(cid) && cid > 0) return cid;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
private pickPermalink(response: any): string {
|
||
const candidates = [
|
||
response?.data?.permalink,
|
||
response?.data?.url,
|
||
response?.permalink,
|
||
response?.url,
|
||
];
|
||
for (const value of candidates) {
|
||
if (typeof value === "string" && value.trim() !== "") {
|
||
return value.trim();
|
||
}
|
||
}
|
||
return "";
|
||
}
|
||
|
||
/**
|
||
* 取发布后的文章链接
|
||
*
|
||
* 正常情况 /postArticle 会直接带回 permalink;但服务端路由参数不全时
|
||
* 可能给空、给带占位符的地址,甚至只给相对路径。这里依次兜底:
|
||
* 接口返回值 → 按 cid 查一次 /post → 都拿不到就返回空串(由调用方提示)
|
||
*/
|
||
private async resolvePermalink(
|
||
response: any,
|
||
cid: number | null
|
||
): Promise<string> {
|
||
const direct = this.normalizeUrl(this.pickPermalink(response));
|
||
if (direct) return direct;
|
||
|
||
if (cid) {
|
||
try {
|
||
// silent = true:这里只是补链接,失败不该再弹一条错误
|
||
const res = await HttpUtils.get(
|
||
`/post?cid=${cid}`,
|
||
undefined,
|
||
true
|
||
);
|
||
const url = this.normalizeUrl(
|
||
this.pickPermalink(res) ||
|
||
String((res as any)?.data?.permalink || "")
|
||
);
|
||
if (url) return url;
|
||
} catch (error) {
|
||
console.warn("[typecho] 按 cid 获取文章链接失败", error);
|
||
}
|
||
}
|
||
|
||
console.warn("[typecho] 发布成功但未取得文章链接", response);
|
||
return "";
|
||
}
|
||
|
||
/**
|
||
* 补成绝对地址
|
||
*
|
||
* Typecho 某些固定链接配置下会返回 /archives/xx/ 这种相对路径,
|
||
* Electron 里的 window.open 会把相对路径当成本地文件,点了没反应。
|
||
*/
|
||
private normalizeUrl(url: string): string {
|
||
const value = String(url || "").trim();
|
||
if (!value || value === "#" || value.includes("{")) return "";
|
||
if (/^https?:\/\//i.test(value)) return value;
|
||
|
||
const root = Util.url.extractDomain(HttpUtils.getCurrentHost());
|
||
if (!root) return "";
|
||
const base = root.replace(/\/+$/, "");
|
||
return base + (value.startsWith("/") ? value : "/" + value);
|
||
}
|
||
|
||
/**
|
||
* 用系统浏览器打开链接(只打开一次)。
|
||
*
|
||
* 关键:在 Obsidian/Electron 里 window.open() 返回 null 并不代表失败——
|
||
* Obsidian 接管后用系统默认浏览器打开了页面,只是不返回 window 句柄。
|
||
* 旧代码看到 null 就用隐藏 <a target=_blank> 再点一次兜底,结果同一
|
||
* 链接被打开两遍(两个浏览器窗口)。这里只调用一次 window.open,去掉
|
||
* 双击兜底;真正被弹窗拦截的情况由调用方的 Notice 提示用户手动打开。
|
||
*/
|
||
private openInBrowser(url: string) {
|
||
console.info("[typecho] 发布后打开文章页:", url);
|
||
|
||
try {
|
||
window.open(url, "_blank");
|
||
} catch (error) {
|
||
// 极少数环境下 window.open 直接抛错:这一种才用 <a> 兜底,
|
||
// 且仅当确实抛错,避免正常返回 null 时重复打开。
|
||
console.warn("[typecho] window.open 抛错,改用链接点击", error);
|
||
const link = document.createElement("a");
|
||
link.href = url;
|
||
link.target = "_blank";
|
||
link.rel = "noopener noreferrer";
|
||
link.style.display = "none";
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
link.remove();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取文件,设置内容
|
||
* @param path 文件路径
|
||
*/
|
||
async readFileAndSetContent(path: string) {
|
||
const file = this.app.vault.getFileByPath(path);
|
||
if (!file) {
|
||
new Notice(i18n.t("error.readFileError"));
|
||
return;
|
||
}
|
||
// 必须等读取完成再返回:early return 的写法会让调用方在
|
||
// this.content 赋值之前就继续往下走(发布空内容 / 发错文件)
|
||
try {
|
||
this.content = await this.app.vault.cachedRead(file);
|
||
} catch (error) {
|
||
new Notice(i18n.t("error.readFileError"));
|
||
console.error("read note content failed:", error);
|
||
}
|
||
}
|
||
|
||
async setTitleFromFileName(path = "", titleInput: HTMLInputElement) {
|
||
if (path) {
|
||
this.activeFilePath = path;
|
||
}
|
||
|
||
const noteFile = this.app.vault.getFileByPath(
|
||
path != "" ? path : this.activeFilePath
|
||
);
|
||
if (!noteFile) {
|
||
new Notice(i18n.t("error.readFileError"));
|
||
return;
|
||
}
|
||
this.baseFileName = noteFile.basename;
|
||
|
||
let cleanTitle = "";
|
||
|
||
try {
|
||
const content = await this.app.vault.read(noteFile);
|
||
const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
||
if (fmMatch) {
|
||
const titleMatch = fmMatch[1].match(/title:\s*(.+)/);
|
||
if (titleMatch) {
|
||
cleanTitle = titleMatch[1]
|
||
.trim()
|
||
.replace(VERSION_SUFFIX, "")
|
||
.replace(RENAME_PREFIX, "")
|
||
.trim();
|
||
}
|
||
}
|
||
} catch (e) {
|
||
console.error("read note content failed:", e);
|
||
}
|
||
|
||
if (!cleanTitle) {
|
||
cleanTitle = noteFile.basename
|
||
.replace(VERSION_SUFFIX, "")
|
||
.replace(RENAME_PREFIX, "")
|
||
.trim();
|
||
}
|
||
|
||
this.title = cleanTitle;
|
||
if (titleInput) {
|
||
titleInput.value = this.title;
|
||
}
|
||
|
||
await this.restoreSlug();
|
||
await this.restoreSelection();
|
||
}
|
||
|
||
/**
|
||
* 恢复别名:优先笔记属性,其次是插件里保存的映射
|
||
*/
|
||
private async restoreSlug() {
|
||
const meta = await readTypechoMetaFresh(this.app, this.activeFilePath);
|
||
let savedSlug = meta.slug;
|
||
|
||
if (!savedSlug) {
|
||
savedSlug = getSettings().slugMapping[this.baseFileName];
|
||
}
|
||
|
||
this.slug =
|
||
savedSlug || "obsidian-" + Util.hash.simpleHash(this.baseFileName);
|
||
|
||
if (this.slugInput) {
|
||
this.slugInput.value = this.slug;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按笔记属性里记录的分类 / 标签,恢复勾选状态。
|
||
*
|
||
* 匹配策略:mid(发布回写的是名称,但旧笔记可能存 ID)→ 名称 → slug,
|
||
* 名称和 slug 都忽略大小写与空白差异;服务端 mid 有时是数字有时是字符串,
|
||
* 这里统一存成字符串,避免复选框的 includes(mid) 因类型不同永远 false。
|
||
*/
|
||
private async restoreSelection() {
|
||
// 关键:不能只信 this.activeFilePath 一个来源。
|
||
// 多窗口下它可能被冻结到另一篇笔记;刚发布回写后 metadataCache /
|
||
// cachedRead 也可能还是旧值。这里按多个候选路径重读,取第一个
|
||
// 真正读到 ty-categories / ty-tags 的 meta,作为回填依据。
|
||
const candidatePaths: string[] = [];
|
||
if (this.activeFilePath) candidatePaths.push(this.activeFilePath);
|
||
const activePath = this.app.workspace.getActiveFile()?.path;
|
||
if (activePath && !candidatePaths.includes(activePath)) {
|
||
candidatePaths.push(activePath);
|
||
}
|
||
|
||
let meta = await readTypechoMetaFresh(this.app, this.activeFilePath);
|
||
for (const path of candidatePaths) {
|
||
const attempt = await readTypechoMetaFresh(this.app, path);
|
||
if (attempt.categories.length > 0 || attempt.tags.length > 0) {
|
||
meta = attempt;
|
||
// 同步修正路径:后续发布写回必须落在真正读到的这篇笔记上
|
||
this.activeFilePath = path;
|
||
break;
|
||
}
|
||
}
|
||
|
||
// 关键兜底:发布时写回的是「发布框里的勾选」,而勾选又来自笔记属性。
|
||
// 一旦某次没勾上(或老笔记压根没写回),就会陷入
|
||
// 「读不到 → 不勾选 → 写回空 → 更读不到」的死循环。
|
||
// 服务端其实一直记着这篇文章的分类/标签:/postDetail 会返回
|
||
// categoryNames / tagNames。笔记缺属性时按 cid(或 slug)问一次线上。
|
||
if (
|
||
meta.categories.length === 0 &&
|
||
meta.tags.length === 0 &&
|
||
(meta.cid || meta.slug)
|
||
) {
|
||
try {
|
||
const lookup = meta.cid
|
||
? `cid=${encodeURIComponent(String(meta.cid))}`
|
||
: `slug=${encodeURIComponent(meta.slug || "")}`;
|
||
// silent=true:老站点可能没有这个接口,可选兜底不该弹错误打扰
|
||
const res = await HttpUtils.get(
|
||
`/postDetail?${lookup}`,
|
||
undefined,
|
||
true
|
||
);
|
||
const post: any = res && (res as any).data;
|
||
// 多站点下 cid 可能撞到另一篇文章;slug / 标题至少一样才敢用。
|
||
// 宁可不勾,也不能把别的文章的分类标签勾到这篇上。
|
||
const sameSlug =
|
||
!!meta.slug &&
|
||
!!post?.slug &&
|
||
String(post.slug) === String(meta.slug);
|
||
const sameTitle =
|
||
!!meta.title &&
|
||
!!post?.title &&
|
||
String(post.title) === String(meta.title);
|
||
if (post && (sameSlug || sameTitle)) {
|
||
const toNames = (value: unknown): string[] => {
|
||
if (!Array.isArray(value)) return [];
|
||
return value
|
||
.map((item: any) =>
|
||
String(
|
||
item && typeof item === "object"
|
||
? item.name ?? ""
|
||
: item ?? ""
|
||
).trim()
|
||
)
|
||
.filter((name) => name !== "");
|
||
};
|
||
const categories = toNames(post.categoryNames ?? post.categories);
|
||
const tags = toNames(post.tagNames ?? post.tags);
|
||
if (categories.length > 0 || tags.length > 0) {
|
||
meta = { ...meta, categories, tags };
|
||
console.info("[typecho] 已从线上文章补回分类/标签", {
|
||
笔记路径: this.activeFilePath,
|
||
分类: categories,
|
||
标签: tags,
|
||
});
|
||
}
|
||
}
|
||
} catch (error) {
|
||
// 可选兜底失败不影响主流程(HttpUtils 已 silent,不会再弹提示)
|
||
console.warn("[typecho] 线上文章分类/标签兜底查询失败", error);
|
||
}
|
||
}
|
||
|
||
// 注意:即使笔记没有分类/标签属性,也要重新拉列表渲染——
|
||
// 切换网站时列表内容是新的,不能因为有属性缺失就整段跳过。
|
||
|
||
const categoriesData = await HttpUtils.get("/categories");
|
||
const allCategories = categoriesData.data || [];
|
||
const tagsData = await HttpUtils.get("/tags");
|
||
const allTags = tagsData.data || [];
|
||
|
||
const normalize = (value: unknown) =>
|
||
String(value ?? "")
|
||
.trim()
|
||
.replace(/\s+/g, "")
|
||
.toLowerCase();
|
||
const findMid = (list: any[], value: string): string | undefined => {
|
||
const key = String(value ?? "").trim();
|
||
if (!key) return undefined;
|
||
const hit = list.find(
|
||
(item: any) =>
|
||
String(item.mid ?? "") === key ||
|
||
normalize(item.name) === normalize(key) ||
|
||
normalize(item.slug) === normalize(key)
|
||
);
|
||
return hit ? String(hit.mid) : undefined;
|
||
};
|
||
|
||
this.selectedCategories = Array.from(
|
||
new Set(
|
||
meta.categories
|
||
.map((name) => findMid(allCategories, name))
|
||
.filter((mid): mid is string => !!mid)
|
||
)
|
||
);
|
||
this.selectedTags = Array.from(
|
||
new Set(
|
||
meta.tags
|
||
.map((name) => findMid(allTags, name))
|
||
.filter((mid): mid is string => !!mid)
|
||
)
|
||
);
|
||
|
||
await this.getCategories(this.contentEl, true);
|
||
await this.getTags(this.contentEl, true);
|
||
|
||
// 诊断日志:回填失败时把「读到的属性 / 拉到的选项 / 匹配结果」一次性
|
||
// 打到控制台,避免只靠猜。正常勾上时不打扰。
|
||
const hasMeta = meta.categories.length > 0 || meta.tags.length > 0;
|
||
if (hasMeta) {
|
||
console.info("[typecho] 回填诊断", {
|
||
笔记路径: this.activeFilePath,
|
||
笔记分类: meta.categories,
|
||
笔记标签: meta.tags,
|
||
站点分类数: allCategories.length,
|
||
站点标签数: allTags.length,
|
||
匹配到分类: this.selectedCategories,
|
||
匹配到标签: this.selectedTags,
|
||
});
|
||
}
|
||
|
||
// 有属性却一个都没勾上:把「读到的属性」直接显示出来,方便一眼定位是
|
||
// 站点选错还是属性为空。以前只提示「没找到同名项」,看不到读到了什么。
|
||
if (
|
||
hasMeta &&
|
||
this.selectedCategories.length === 0 &&
|
||
this.selectedTags.length === 0
|
||
) {
|
||
new Notice(
|
||
`笔记分类[${meta.categories.join("/")}]、标签[${meta.tags.join("/")}]在当前网站没找到同名项。若刚切换过网站请重开发布框;否则检查上方网站是否正确。`,
|
||
10000
|
||
);
|
||
} else if (!hasMeta) {
|
||
// 读不到属性时也要留痕:区分「这篇笔记没发布过」和「读错了文件」
|
||
console.warn("[typecho] 回填时未读到分类/标签属性", {
|
||
笔记路径: this.activeFilePath,
|
||
候选路径: candidatePaths,
|
||
});
|
||
}
|
||
}
|
||
|
||
private async getSelectedFilePath(): Promise<string> {
|
||
const activeFile = this.app.workspace.getActiveFile();
|
||
return activeFile ? activeFile.path : "";
|
||
}
|
||
|
||
/**
|
||
* 打开「添加分类 / 标签」弹窗
|
||
*/
|
||
private openAddMeta(type: "tag" | "category") {
|
||
const refresh = async () => {
|
||
// preserveSelection=true:新增分类/标签后刷新列表,别把已勾选项清掉
|
||
if (type === "tag") {
|
||
await this.getTags(this.contentEl, true);
|
||
} else {
|
||
await this.getCategories(this.contentEl, true);
|
||
}
|
||
};
|
||
new addMetas(this.app, type, refresh).open();
|
||
}
|
||
|
||
private toggleSelection(list: string[], mid: string, checked: boolean) {
|
||
// 服务端 mid 可能是数字,回填时已统一成字符串;点击时同样归一化
|
||
const id = String(mid);
|
||
if (checked) {
|
||
if (!list.includes(id)) list.push(id);
|
||
} else {
|
||
const index = list.indexOf(id);
|
||
if (index > -1) list.splice(index, 1);
|
||
}
|
||
}
|
||
|
||
async getCategories(contentEl: HTMLElement, preserveSelection = false) {
|
||
if (!this.categoriesDom) {
|
||
this.categoriesDom = contentEl.createDiv({
|
||
attr: { style: "margin-bottom: 15px;" },
|
||
});
|
||
}
|
||
while (this.categoriesDom.firstChild) {
|
||
this.categoriesDom.removeChild(this.categoriesDom.firstChild);
|
||
}
|
||
if (!preserveSelection) {
|
||
this.selectedCategories = [];
|
||
}
|
||
|
||
const notice = new Notice(
|
||
`${i18n.t("common.get")}${i18n.t("field.category")}...`
|
||
);
|
||
try {
|
||
const categoriesResponse = await HttpUtils.get("/categories");
|
||
renderCategoryPanel(
|
||
this.categoriesDom,
|
||
categoriesResponse.data || [],
|
||
{
|
||
title: i18n.t("field.category"),
|
||
emptyText: i18n.t("sync.noCategories"),
|
||
addText: i18n.t("common.add"),
|
||
isSelected: (mid) => this.selectedCategories.includes(String(mid)),
|
||
onToggle: (mid, checked) =>
|
||
this.toggleSelection(this.selectedCategories, mid, checked),
|
||
onAdd: () => this.openAddMeta("category"),
|
||
}
|
||
);
|
||
} finally {
|
||
notice.hide();
|
||
}
|
||
}
|
||
|
||
async getTags(contentEl: HTMLElement, preserveSelection = false) {
|
||
if (!this.tagsDom) {
|
||
this.tagsDom = contentEl.createDiv({
|
||
attr: { style: "margin-bottom: 15px;" },
|
||
});
|
||
}
|
||
while (this.tagsDom.firstChild) {
|
||
this.tagsDom.removeChild(this.tagsDom.firstChild);
|
||
}
|
||
if (!preserveSelection) {
|
||
this.selectedTags = [];
|
||
}
|
||
|
||
const notice = new Notice(
|
||
`${i18n.t("common.get")}${i18n.t("field.tag")}...`
|
||
);
|
||
try {
|
||
const tagsResponse = await HttpUtils.get("/tags");
|
||
renderTagPanel(this.tagsDom, tagsResponse.data || [], {
|
||
title: i18n.t("field.tag"),
|
||
emptyText: i18n.t("sync.noTags"),
|
||
addText: i18n.t("common.add"),
|
||
// 标签通常成百上千个,开搜索框按模糊匹配筛
|
||
searchable: true,
|
||
searchPlaceholder: i18n.t("sync.tagSearchPlaceholder"),
|
||
noMatchText: i18n.t("sync.tagSearchNoMatch"),
|
||
selectionText: (selected, total) =>
|
||
i18n.t("sync.tagSelectedCount", {
|
||
selected: String(selected),
|
||
total: String(total),
|
||
}),
|
||
moreText: (rest) =>
|
||
i18n.t("sync.tagSearchMore", { count: rest }),
|
||
isSelected: (mid) => this.selectedTags.includes(String(mid)),
|
||
onToggle: (mid, checked) =>
|
||
this.toggleSelection(this.selectedTags, mid, checked),
|
||
onAdd: () => this.openAddMeta("tag"),
|
||
});
|
||
} finally {
|
||
notice.hide();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 根据分类 ID 列表获取分类名称列表
|
||
*/
|
||
private async getCategoryNamesByIds(ids: string[]): Promise<string[]> {
|
||
const response = await HttpUtils.get("/categories");
|
||
const categories = response.data || [];
|
||
const names: string[] = [];
|
||
for (const id of ids) {
|
||
const category = categories.find((c: any) => c.mid == id);
|
||
if (category) names.push(category.name);
|
||
}
|
||
return names;
|
||
}
|
||
|
||
/**
|
||
* 根据标签 ID 列表获取标签名称列表
|
||
*/
|
||
private async getTagNamesByIds(ids: string[]): Promise<string[]> {
|
||
const response = await HttpUtils.get("/tags");
|
||
const tags = response.data || [];
|
||
const names: string[] = [];
|
||
for (const id of ids) {
|
||
const tag = tags.find((t: any) => t.mid == id);
|
||
if (tag) names.push(tag.name);
|
||
}
|
||
return names;
|
||
}
|
||
|
||
onClose() {
|
||
this.contentEl.empty();
|
||
}
|
||
}
|