| 1 | import { get, writable } from 'svelte/store'; |
| 2 | import { getAccountData, setAccountData } from './api'; |
| 3 | import { normaliseQuick, parseQuickReactions } from './quick-reactions-model'; |
| 4 | import type { QuickEntry, QuickReaction } from './types'; |
| 5 | |
| 6 | const EVENT_TYPE = 'dev.malice.quick_reactions'; |
| 7 | |
| 8 | export const DEFAULT_QUICK_REACTIONS: QuickReaction[] = [ |
| 9 | { key: '👍', shortcode: 'thumbsup' }, |
| 10 | { key: '❤️', shortcode: 'heart' }, |
| 11 | { key: '😂', shortcode: 'joy' }, |
| 12 | { key: '🎉', shortcode: 'tada' }, |
| 13 | { key: '😮', shortcode: 'open_mouth' }, |
| 14 | { key: '😢', shortcode: 'cry' } |
| 15 | ]; |
| 16 | |
| 17 | export const quickReactions = writable<QuickEntry[]>(DEFAULT_QUICK_REACTIONS); |
| 18 | |
| 19 | export async function loadQuickReactions(): Promise<void> { |
| 20 | try { |
| 21 | quickReactions.set(parseQuickReactions(await getAccountData(EVENT_TYPE)) ?? DEFAULT_QUICK_REACTIONS); |
| 22 | } catch { |
| 23 | quickReactions.set(DEFAULT_QUICK_REACTIONS); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | export async function saveQuickReactions(entries: QuickEntry[]): Promise<void> { |
| 28 | const reactions = normaliseQuick(entries); |
| 29 | const previous = get(quickReactions); |
| 30 | quickReactions.set(reactions); |
| 31 | try { |
| 32 | await setAccountData(EVENT_TYPE, { reactions }); |
| 33 | } catch (e) { |
| 34 | if (get(quickReactions) === reactions) quickReactions.set(previous); |
| 35 | throw e; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | export function resetQuickReactions(): void { |
| 40 | quickReactions.set(DEFAULT_QUICK_REACTIONS); |
| 41 | } |