56 lines
1.6 KiB
TypeScript
56 lines
1.6 KiB
TypeScript
import { App, FuzzySuggestModal, Notice, TFile } from 'obsidian';
|
|
import type { MetaItem } from './api';
|
|
|
|
export class MetaSuggestModal extends FuzzySuggestModal<MetaItem> {
|
|
private items: MetaItem[];
|
|
private metaKey: string;
|
|
private file: TFile;
|
|
private useSlug: boolean;
|
|
|
|
constructor(app: App, items: MetaItem[], metaKey: string, file: TFile, useSlug: boolean = true) {
|
|
super(app);
|
|
this.items = items;
|
|
this.metaKey = metaKey;
|
|
this.file = file;
|
|
this.useSlug = useSlug;
|
|
}
|
|
|
|
getItems(): MetaItem[] {
|
|
return this.items;
|
|
}
|
|
|
|
getItemText(item: MetaItem): string {
|
|
// 显示名称,如果有 slug,追加显示
|
|
if (item.slug && this.useSlug) {
|
|
return `${item.name} (${item.slug})`;
|
|
}
|
|
return item.name;
|
|
}
|
|
|
|
onChooseItem(item: MetaItem, evt: MouseEvent | KeyboardEvent) {
|
|
const valueToInsert = (this.useSlug && item.slug) ? item.slug : item.name;
|
|
|
|
void this.app.fileManager.processFrontMatter(this.file, (frontmatter: Record<string, unknown>) => {
|
|
const currentVal = frontmatter[this.metaKey];
|
|
if (this.metaKey === 'tags' || this.metaKey === 'tag') {
|
|
if (!currentVal) {
|
|
frontmatter[this.metaKey] = [valueToInsert];
|
|
} else if (Array.isArray(currentVal)) {
|
|
if (!currentVal.includes(valueToInsert)) {
|
|
currentVal.push(valueToInsert);
|
|
}
|
|
} else {
|
|
frontmatter[this.metaKey] = [currentVal, valueToInsert];
|
|
}
|
|
} else {
|
|
frontmatter[this.metaKey] = valueToInsert;
|
|
}
|
|
}).then(() => {
|
|
new Notice(`成功将 ${this.metaKey} 设为 ${valueToInsert}`);
|
|
}).catch(e => {
|
|
console.error(e);
|
|
new Notice(`设置 ${this.metaKey} 失败`);
|
|
});
|
|
}
|
|
}
|