| 1 | import { get, writable } from 'svelte/store'; |
| 2 | import { getAccountData, setAccountData } from './api'; |
| 3 | import { parseDisabledPackImages, withImageEnabled } from './pack-preferences-model'; |
| 4 | import type { DisabledPackImages } from './pack-preferences-model'; |
| 5 | |
| 6 | const EVENT_TYPE = 'dev.malice.pack_preferences'; |
| 7 | |
| 8 | export const disabledPackImages = writable<DisabledPackImages>({}); |
| 9 | |
| 10 | let loadGeneration = 0; |
| 11 | let accountGeneration = 0; |
| 12 | let pendingSaves = 0; |
| 13 | let persistedPreferences: DisabledPackImages = {}; |
| 14 | let saveQueue: Promise<void> = Promise.resolve(); |
| 15 | |
| 16 | export async function loadPackPreferences(): Promise<void> { |
| 17 | if (pendingSaves > 0) return; |
| 18 | const generation = ++loadGeneration; |
| 19 | const epoch = accountGeneration; |
| 20 | try { |
| 21 | const preferences = parseDisabledPackImages(await getAccountData(EVENT_TYPE)); |
| 22 | if (generation !== loadGeneration || epoch !== accountGeneration || pendingSaves > 0) return; |
| 23 | persistedPreferences = preferences; |
| 24 | disabledPackImages.set(preferences); |
| 25 | } catch {} |
| 26 | } |
| 27 | |
| 28 | export function setPackImageEnabled(packId: string, shortcode: string, enabled: boolean): Promise<void> { |
| 29 | const previous = get(disabledPackImages); |
| 30 | const next = withImageEnabled(previous, packId, shortcode, enabled); |
| 31 | if (next === previous) return Promise.resolve(); |
| 32 | |
| 33 | const epoch = accountGeneration; |
| 34 | loadGeneration += 1; |
| 35 | pendingSaves += 1; |
| 36 | disabledPackImages.set(next); |
| 37 | |
| 38 | const save = saveQueue.then(async () => { |
| 39 | if (epoch !== accountGeneration) return; |
| 40 | await setAccountData(EVENT_TYPE, { disabled: next }); |
| 41 | if (epoch === accountGeneration) persistedPreferences = next; |
| 42 | }); |
| 43 | saveQueue = save.catch(() => undefined); |
| 44 | return save.catch((error: unknown) => { |
| 45 | if (epoch === accountGeneration && get(disabledPackImages) === next) { |
| 46 | loadGeneration += 1; |
| 47 | disabledPackImages.set(persistedPreferences); |
| 48 | } |
| 49 | throw error; |
| 50 | }).finally(() => { |
| 51 | if (epoch === accountGeneration) pendingSaves -= 1; |
| 52 | }); |
| 53 | } |
| 54 | |
| 55 | export function resetPackPreferences(): void { |
| 56 | accountGeneration += 1; |
| 57 | loadGeneration += 1; |
| 58 | pendingSaves = 0; |
| 59 | persistedPreferences = {}; |
| 60 | disabledPackImages.set({}); |
| 61 | } |