import { defineStore } from 'pinia'; import { invoke } from '@tauri-apps/api/core'; import { listen } from '@tauri-apps/api/event'; import { Package, Profile } from './types'; import { pkgKey } from './util'; type InstallStatus = { pkg: string; }; export const usePkgStore = defineStore('pkg', { state: (): { pkg: { [key: string]: Package }; prf: Profile | null } => { return { pkg: {}, prf: null, }; }, getters: { fromDepString: (state) => (str: string) => state.pkg[str] ?? null, fromName: (state) => (namespace: string, name: string) => state.pkg[`${namespace}-${name}`] ?? null, all: (state) => Object.values(state), allLocal: (state) => Object.values(state.pkg).filter((p) => p.loc), allRemote: (state) => Object.values(state.pkg).filter((p) => p.rmt), profile: (state) => state.prf, isEnabled: (state) => (pkg: Package | undefined) => pkg !== undefined && state.prf?.mods.includes(pkgKey(pkg)), }, actions: { setupListeners() { listen('install-start', async (ev) => { await this.reload(ev.payload.pkg); }); listen('install-end', async (ev) => { await this.reload(ev.payload.pkg); await this.reloadProfile(); }); }, async reloadAll() { await invoke('reload_all_packages'); const data = (await invoke('get_all_packages')) as { [key: string]: Package; }; for (const k of Object.keys(this)) { delete this.pkg[k]; } Object.assign(this.pkg, data); if (this.prf !== null) for (const [k, v] of Object.entries(this)) { if (this.prf.mods.includes(k)) { if (v.loc) { v.loc.enabled = true; } else { console.error(`${k} enabled but not present`); } } } }, async reload(pkgOrKey: string | Package) { const key = typeof pkgOrKey === 'string' ? pkgOrKey : pkgKey(pkgOrKey); const rv: Package = await invoke('get_package', { key, }); if (this.pkg[key] === undefined) { this.pkg[key] = {} as Package; } else { this.pkg[key].loc = null; this.pkg[key].rmt = null; } Object.assign(this.pkg[key], rv); }, async initProfile(exePath: string) { this.prf = await invoke('init_profile', { exePath }); }, async saveProfile() { await invoke('save_profile'); }, async reloadProfile() { this.prf = await invoke('get_current_profile'); }, async fetch() { await invoke('fetch_listings'); await this.reloadAll(); }, async toggle(pkg: Package | undefined, enable: boolean) { if (pkg === undefined) { return; } await invoke('toggle_package', { key: pkgKey(pkg), enable }); await this.reload(pkg); await this.saveProfile(); }, }, });