obsidian-book-tracker/src/views/goodreads-search-modal.ts

53 lines
1.2 KiB
TypeScript

import GoodreadsSearch from "@components/GoodreadsSearch.svelte";
import { type SearchResult } from "@data-sources/goodreads";
import { App, Modal, Notice } from "obsidian";
import { mount, unmount } from "svelte";
export class GoodreadsSearchModal extends Modal {
private component: ReturnType<typeof GoodreadsSearch> | undefined;
constructor(
app: App,
private readonly onSearch: (error: any, results: SearchResult[]) => void
) {
super(app);
}
onOpen() {
this.component = mount(GoodreadsSearch, {
target: this.contentEl,
props: {
onError(error) {
this.onSearch(error, []);
this.close();
},
onSearch: (results: SearchResult[]) => {
this.onSearch(null, results);
this.close();
},
},
});
}
onClose() {
if (this.component) {
unmount(this.component);
this.component = undefined;
}
}
static createAndOpen(app: App): Promise<SearchResult[]> {
return new Promise((resolve, reject) => {
const modal = new GoodreadsSearchModal(app, (error, results) => {
if (error) {
new Notice(`Error: ${error.message}`);
reject(error);
} else {
resolve(results);
}
});
modal.open();
});
}
}