367 lines
11 KiB
TypeScript
367 lines
11 KiB
TypeScript
|
|
import { App, TFile } from "obsidian";
|
|||
|
|
import { formatBeijingTime } from "./datetime";
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 笔记属性里使用的字段名。
|
|||
|
|
*
|
|||
|
|
* 旧版本把元数据写成嵌套的 `typecho:` 对象,Obsidian 属性面板里会折叠成一行,
|
|||
|
|
* 看不出具体内容。现在改为平铺的独立属性,逐条展开显示。
|
|||
|
|
*
|
|||
|
|
* 统一加 `ty-` 短前缀:既比 `typecho-` 简洁,又能和笔记自己的
|
|||
|
|
* `tags` / `categories` / `updated` 等同名属性区分开,不会互相覆盖。
|
|||
|
|
*/
|
|||
|
|
export const FM_KEYS = {
|
|||
|
|
cid: "ty-cid",
|
|||
|
|
slug: "ty-slug",
|
|||
|
|
url: "ty-url",
|
|||
|
|
categories: "ty-categories",
|
|||
|
|
tags: "ty-tags",
|
|||
|
|
title: "ty-title",
|
|||
|
|
created: "ty-created",
|
|||
|
|
updated: "ty-updated",
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 更早几版用过的键名 → 当前字段,只用于读取兼容和写入时清理,
|
|||
|
|
* 保证老笔记下次发布会自动迁移成新键名。
|
|||
|
|
*/
|
|||
|
|
const LEGACY_FLAT_KEYS: Record<string, string> = {
|
|||
|
|
"typecho-cid": "cid",
|
|||
|
|
"typecho-slug": "slug",
|
|||
|
|
"typecho-url": "url",
|
|||
|
|
"typecho-categories": "categories",
|
|||
|
|
"typecho-tags": "tags",
|
|||
|
|
"typecho-original-title": "original-title",
|
|||
|
|
"typecho-updated": "updated",
|
|||
|
|
"ty-original-title": "original-title",
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 已废弃的键,读取时不认、写入时直接清掉。
|
|||
|
|
* `ty-site` 和 `ty-url` 内容重复(都是站点 API / 文章地址),已弃用。
|
|||
|
|
*/
|
|||
|
|
const OBSOLETE_KEYS = ["ty-site"];
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 中间一版用过的无前缀键名。只做读取兜底,写入时也会清理,
|
|||
|
|
* 因为这些是插件自己写坏的残留,不清掉属性面板会出现两套。
|
|||
|
|
*/
|
|||
|
|
const PLAIN_KEYS = [
|
|||
|
|
"cid",
|
|||
|
|
"slug",
|
|||
|
|
"url",
|
|||
|
|
"categories",
|
|||
|
|
"tags",
|
|||
|
|
"original-title",
|
|||
|
|
"updated",
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
export interface TypechoMeta {
|
|||
|
|
cid: number | null;
|
|||
|
|
slug: string | null;
|
|||
|
|
url: string | null;
|
|||
|
|
categories: string[];
|
|||
|
|
tags: string[];
|
|||
|
|
title: string | null;
|
|||
|
|
created: string | null;
|
|||
|
|
updated: string | null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export function emptyMeta(): TypechoMeta {
|
|||
|
|
return {
|
|||
|
|
cid: null,
|
|||
|
|
slug: null,
|
|||
|
|
url: null,
|
|||
|
|
categories: [],
|
|||
|
|
tags: [],
|
|||
|
|
title: null,
|
|||
|
|
created: null,
|
|||
|
|
updated: null,
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function toCid(value: unknown): number | null {
|
|||
|
|
const n = typeof value === "number" ? value : parseInt(String(value ?? ""), 10);
|
|||
|
|
return Number.isFinite(n) && n > 0 ? n : null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function toText(value: unknown): string | null {
|
|||
|
|
if (value === null || value === undefined) return null;
|
|||
|
|
const s = String(value).trim();
|
|||
|
|
return s === "" ? null : s;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function toList(value: unknown): string[] {
|
|||
|
|
if (Array.isArray(value)) {
|
|||
|
|
return value.map((v) => String(v).trim()).filter((v) => v !== "");
|
|||
|
|
}
|
|||
|
|
const s = toText(value);
|
|||
|
|
if (!s) return [];
|
|||
|
|
return s
|
|||
|
|
.split(/[,,]/)
|
|||
|
|
.map((v) => v.trim())
|
|||
|
|
.filter((v) => v !== "");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 把任意来源的字段表转成 TypechoMeta(统一兼容几代旧写法)。
|
|||
|
|
*/
|
|||
|
|
function metaFromFields(fm: any): TypechoMeta {
|
|||
|
|
const meta = emptyMeta();
|
|||
|
|
if (!fm) return meta;
|
|||
|
|
|
|||
|
|
// 最早:typecho: { cid, slug, ... } 嵌套写法
|
|||
|
|
const legacy: any =
|
|||
|
|
fm.typecho && typeof fm.typecho === "object" ? fm.typecho : {};
|
|||
|
|
|
|||
|
|
// 带前缀的平铺写法(typecho-* 与 ty-original-title)
|
|||
|
|
const legacyFlat: any = {};
|
|||
|
|
for (const [key, field] of Object.entries(LEGACY_FLAT_KEYS)) {
|
|||
|
|
if (fm[key] !== undefined) legacyFlat[field] = fm[key];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 无前缀的平铺写法
|
|||
|
|
const plain: any = {};
|
|||
|
|
for (const key of PLAIN_KEYS) {
|
|||
|
|
if (fm[key] !== undefined) plain[key] = fm[key];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
meta.cid = toCid(fm[FM_KEYS.cid] ?? plain.cid ?? legacyFlat.cid ?? legacy.cid);
|
|||
|
|
meta.slug = toText(
|
|||
|
|
fm[FM_KEYS.slug] ?? plain.slug ?? legacyFlat.slug ?? legacy.slug
|
|||
|
|
);
|
|||
|
|
meta.url = toText(fm[FM_KEYS.url] ?? plain.url ?? legacyFlat.url ?? legacy.url);
|
|||
|
|
meta.categories = toList(
|
|||
|
|
fm[FM_KEYS.categories] ??
|
|||
|
|
plain.categories ??
|
|||
|
|
legacyFlat.categories ??
|
|||
|
|
legacy.categories
|
|||
|
|
);
|
|||
|
|
meta.tags = toList(
|
|||
|
|
fm[FM_KEYS.tags] ?? plain.tags ?? legacyFlat.tags ?? legacy.tags
|
|||
|
|
);
|
|||
|
|
meta.title = toText(
|
|||
|
|
fm[FM_KEYS.title] ??
|
|||
|
|
plain["original-title"] ??
|
|||
|
|
legacyFlat["original-title"] ??
|
|||
|
|
legacy.original_title ??
|
|||
|
|
fm.original_title
|
|||
|
|
);
|
|||
|
|
meta.created = toText(fm[FM_KEYS.created]);
|
|||
|
|
meta.updated = toText(
|
|||
|
|
fm[FM_KEYS.updated] ??
|
|||
|
|
plain.updated ??
|
|||
|
|
legacyFlat.updated ??
|
|||
|
|
legacy.updated
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
return meta;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 读取笔记里的 Typecho 元数据,同时兼容几代旧写法。
|
|||
|
|
*/
|
|||
|
|
export function readTypechoMeta(app: App, filePath: string): TypechoMeta {
|
|||
|
|
if (!filePath) return emptyMeta();
|
|||
|
|
const file = app.vault.getFileByPath(filePath);
|
|||
|
|
if (!file) return emptyMeta();
|
|||
|
|
return metaFromFields(app.metadataCache.getFileCache(file)?.frontmatter);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 去掉 YAML 标量两端多余引号 */
|
|||
|
|
function unquote(value: string): string {
|
|||
|
|
const s = value.trim();
|
|||
|
|
if (/^".*"$/.test(s) || /^'.*'$/.test(s)) return s.slice(1, -1);
|
|||
|
|
return s;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** 解析 `[a, b, "c"]` 形式的 flow 数组;不是数组则返回 null */
|
|||
|
|
function parseFlowList(value: string): string[] | null {
|
|||
|
|
const s = value.trim();
|
|||
|
|
if (!s.startsWith("[") || !s.endsWith("]")) return null;
|
|||
|
|
return s
|
|||
|
|
.slice(1, -1)
|
|||
|
|
.split(",")
|
|||
|
|
.map((part) => unquote(part))
|
|||
|
|
.filter((part) => part !== "");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 直接从笔记文本解析顶层 frontmatter 字段。
|
|||
|
|
*
|
|||
|
|
* 不依赖 metadataCache——发布回写后 metadataCache 可能还是旧值,
|
|||
|
|
* 导致「属性面板明明有 ty-categories / ty-tags,发布框却读不到」。
|
|||
|
|
* 只解析插件自己写的平铺键(含 flow 数组和块状数组),够用且不会误伤正文。
|
|||
|
|
*/
|
|||
|
|
export function parseFrontmatterFields(content: string): Record<string, any> {
|
|||
|
|
const fields: Record<string, any> = {};
|
|||
|
|
const match = content.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/);
|
|||
|
|
if (!match) return fields;
|
|||
|
|
|
|||
|
|
const lines = match[1].split(/\r?\n/);
|
|||
|
|
for (let i = 0; i < lines.length; i++) {
|
|||
|
|
const line = lines[i];
|
|||
|
|
// 顶层键(无缩进);缩进行只作为上一个键的块状数组元素处理
|
|||
|
|
const head = line.match(/^([A-Za-z][\w-]*):[ \t]*(.*)$/);
|
|||
|
|
if (!head) continue;
|
|||
|
|
const key = head[1];
|
|||
|
|
const raw = head[2].trim();
|
|||
|
|
if (raw !== "") {
|
|||
|
|
const list = parseFlowList(raw);
|
|||
|
|
fields[key] = list === null ? unquote(raw) : list;
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
// 块状数组:`key:\n - item`
|
|||
|
|
const items: string[] = [];
|
|||
|
|
while (i + 1 < lines.length) {
|
|||
|
|
const item = lines[i + 1].match(/^[ \t]+-[ \t]?(.*)$/);
|
|||
|
|
if (!item) break;
|
|||
|
|
i++;
|
|||
|
|
const value = unquote(item[1]);
|
|||
|
|
if (value !== "") items.push(value);
|
|||
|
|
}
|
|||
|
|
fields[key] = items;
|
|||
|
|
}
|
|||
|
|
return fields;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 读元数据的最新版本:先读文件文本(权威),再与 metadataCache 结果合并,
|
|||
|
|
* 兼容旧笔记里 metadataCache 才有、文本解析不覆盖的嵌套写法。
|
|||
|
|
*/
|
|||
|
|
export async function readTypechoMetaFresh(
|
|||
|
|
app: App,
|
|||
|
|
filePath: string
|
|||
|
|
): Promise<TypechoMeta> {
|
|||
|
|
const cached = readTypechoMeta(app, filePath);
|
|||
|
|
const file = app.vault.getFileByPath(filePath);
|
|||
|
|
if (!file) return cached;
|
|||
|
|
try {
|
|||
|
|
// 必须用 read() 直接读磁盘,不能用 cachedRead():
|
|||
|
|
// 发布回写 frontmatter 后 vault 的内容缓存可能还是旧值,cachedRead
|
|||
|
|
// 会拿到还没有 ty-categories/ty-tags 的旧文本,导致回填时属性为空。
|
|||
|
|
// 这正是「slug 有(走 slugMapping 兜底)、分类标签却勾不上」的根因之一。
|
|||
|
|
const fields = parseFrontmatterFields(await app.vault.read(file));
|
|||
|
|
const fresh = metaFromFields(fields);
|
|||
|
|
const merged = emptyMeta();
|
|||
|
|
merged.cid = fresh.cid ?? cached.cid;
|
|||
|
|
merged.slug = fresh.slug ?? cached.slug;
|
|||
|
|
merged.url = fresh.url ?? cached.url;
|
|||
|
|
merged.categories = fresh.categories.length ? fresh.categories : cached.categories;
|
|||
|
|
merged.tags = fresh.tags.length ? fresh.tags : cached.tags;
|
|||
|
|
merged.title = fresh.title ?? cached.title;
|
|||
|
|
merged.created = fresh.created ?? cached.created;
|
|||
|
|
merged.updated = fresh.updated ?? cached.updated;
|
|||
|
|
return merged;
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error("read fresh frontmatter failed:", error);
|
|||
|
|
return cached;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export interface TypechoMetaWrite {
|
|||
|
|
cid: number;
|
|||
|
|
slug?: string | null;
|
|||
|
|
url?: string | null;
|
|||
|
|
categories?: string[];
|
|||
|
|
tags?: string[];
|
|||
|
|
title?: string | null;
|
|||
|
|
created?: string | null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/** flow 数组里需要加引号的字符(YAML 特殊符号或会破坏方括号结构) */
|
|||
|
|
const NEEDS_QUOTE = /[,[\]{}:#&*!|>'"%@`]|^\s|\s$/;
|
|||
|
|
|
|||
|
|
/** 把单个值转成 YAML flow 数组里的安全标量 */
|
|||
|
|
function yamlScalar(raw: string): string {
|
|||
|
|
const v = raw.trim();
|
|||
|
|
if (v === "") return '""';
|
|||
|
|
if (/^".*"$/.test(v) || /^'.*'$/.test(v)) return v;
|
|||
|
|
if (NEEDS_QUOTE.test(v)) return JSON.stringify(v);
|
|||
|
|
return v;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 把指定字段的块状数组压成单行 flow 写法:
|
|||
|
|
*
|
|||
|
|
* ty-categories: → ty-categories: [插件, 随笔]
|
|||
|
|
* - 插件
|
|||
|
|
* - 随笔
|
|||
|
|
*
|
|||
|
|
* processFrontMatter 内部固定用块状风格序列化,没有开关可调,
|
|||
|
|
* 所以写完之后只针对这两个字段做一次文本级压缩,其余属性一字不动。
|
|||
|
|
*/
|
|||
|
|
export function compactArrayFields(content: string): string {
|
|||
|
|
const keys = [FM_KEYS.categories, FM_KEYS.tags].map((k) =>
|
|||
|
|
k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
|||
|
|
);
|
|||
|
|
const re = new RegExp(
|
|||
|
|
`^(${keys.join("|")}):[ \\t]*\\r?\\n((?:[ \\t]*-[ \\t]?[^\\r\\n]*\\r?\\n?)+)`,
|
|||
|
|
"gm"
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
return content.replace(re, (_match, key: string, block: string) => {
|
|||
|
|
const items = block
|
|||
|
|
.split(/\r?\n/)
|
|||
|
|
.map((line) => line.replace(/^[ \t]*-[ \t]?/, "").trim())
|
|||
|
|
.filter((line) => line !== "");
|
|||
|
|
if (items.length === 0) return `${key}: []\n`;
|
|||
|
|
return `${key}: [${items.map(yamlScalar).join(", ")}]\n`;
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 把发布结果写回笔记属性(平铺,方便在属性面板逐条查看)。
|
|||
|
|
*
|
|||
|
|
* 使用 Obsidian 官方的 processFrontMatter,避免手写 YAML 时把用户
|
|||
|
|
* 自己的其他属性(数组、嵌套对象)解析坏掉。
|
|||
|
|
*/
|
|||
|
|
export async function writeTypechoMeta(
|
|||
|
|
app: App,
|
|||
|
|
file: TFile,
|
|||
|
|
data: TypechoMetaWrite
|
|||
|
|
): Promise<void> {
|
|||
|
|
await app.fileManager.processFrontMatter(file, (fm: any) => {
|
|||
|
|
// 迁移旧写法:删掉空壳 `typecho:`、各代旧键、废弃键,
|
|||
|
|
// 避免属性面板里出现两套重复属性
|
|||
|
|
if (fm.typecho !== undefined) delete fm.typecho;
|
|||
|
|
for (const key of Object.keys(LEGACY_FLAT_KEYS)) delete fm[key];
|
|||
|
|
for (const key of OBSOLETE_KEYS) delete fm[key];
|
|||
|
|
for (const key of PLAIN_KEYS) delete fm[key];
|
|||
|
|
|
|||
|
|
fm[FM_KEYS.cid] = Number(data.cid);
|
|||
|
|
|
|||
|
|
const apply = (key: string, value: any) => {
|
|||
|
|
const isEmpty =
|
|||
|
|
value === null ||
|
|||
|
|
value === undefined ||
|
|||
|
|
value === "" ||
|
|||
|
|
(Array.isArray(value) && value.length === 0);
|
|||
|
|
if (isEmpty) {
|
|||
|
|
delete fm[key];
|
|||
|
|
} else {
|
|||
|
|
fm[key] = value;
|
|||
|
|
}
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
apply(FM_KEYS.slug, data.slug);
|
|||
|
|
apply(FM_KEYS.url, data.url);
|
|||
|
|
apply(FM_KEYS.categories, data.categories);
|
|||
|
|
apply(FM_KEYS.tags, data.tags);
|
|||
|
|
apply(FM_KEYS.title, data.title);
|
|||
|
|
|
|||
|
|
// 发布时间要排在更新时间上面。已有属性直接改值是改不动顺序的,
|
|||
|
|
// js-yaml 会把新加的 key 追加到末尾,所以先删后按顺序重写。
|
|||
|
|
const previousCreated = toText(fm[FM_KEYS.created]);
|
|||
|
|
delete fm[FM_KEYS.created];
|
|||
|
|
delete fm[FM_KEYS.updated];
|
|||
|
|
|
|||
|
|
const created = toText(data.created) || previousCreated;
|
|||
|
|
if (created) fm[FM_KEYS.created] = created;
|
|||
|
|
fm[FM_KEYS.updated] = formatBeijingTime();
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// 分类、标签压成单行,方便一眼看完
|
|||
|
|
await app.vault.process(file, (content) => compactArrayFields(content));
|
|||
|
|
}
|