import { Credentials, DoorsSaved, SiteConfigModel } from "@/lib/api"; import { ADVENT22 } from "@/plugins/advent22"; import { AxiosBasicCredentials } from "axios"; import { acceptHMRUpdate, defineStore } from "pinia"; const check_touch_device = () => window.matchMedia("(any-hover: none)").matches; const empty_creds = () => ["", ""] as Credentials; export const advent22Store = defineStore({ id: "advent22", state: () => ({ api_creds: empty_creds(), is_touch_device: check_touch_device(), is_admin: false, site_config: { title: "Adventskalender", subtitle: "Lorem Ipsum", content: "", footer: "", } as SiteConfigModel, user_doors: [] as DoorsSaved, next_door_target: null as number | null, }), getters: { axios_creds: (state): AxiosBasicCredentials => { const [username, password] = state.api_creds; return { username: username, password: password }; }, }, actions: { init(): void { ADVENT22.api_get_blob("user/favicon") .then((favicon_src) => { const link: HTMLLinkElement = document.querySelector("link[rel*='icon']") || document.createElement("link"); link.rel = "shortcut icon"; link.type = "image/x-icon"; link.href = favicon_src; if (link.parentElement === null) document.getElementsByTagName("head")[0].appendChild(link); }) .catch(() => {}); Promise.all([ ADVENT22.api_get("user/site_config"), ADVENT22.api_get("user/doors"), ADVENT22.api_get("user/next_door"), ]) .then(([site_config, user_doors, next_door]) => { document.title = site_config.title; if (site_config.subtitle !== "") document.title += " – " + site_config.subtitle; this.site_config = site_config; this.user_doors = user_doors; if (next_door !== null) this.next_door_target = Date.now() + next_door; }) .catch(ADVENT22.alert_user_error); }, login(creds: Credentials = empty_creds()): Promise { this.api_creds = creds; return new Promise((resolve, reject) => { ADVENT22.api_get("admin/is_admin") .then((is_admin) => { this.is_admin = is_admin; resolve(is_admin); }) .catch(reject); }); }, logout(): Promise { return this.login(); }, set_touch_device(state: boolean = check_touch_device()): void { this.is_touch_device = state; }, toggle_touch_device(): void { this.is_touch_device = !this.is_touch_device; }, }, }); if (import.meta.webpackHot) { import.meta.webpackHot.accept( acceptHMRUpdate(advent22Store, import.meta.webpackHot), ); }