atagen

malice

public
Star0
Watch0
d1818305ffd6912e4b9ac7b706c43eccd01bdd21
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/quick-reactions.tsTypescript55 lines1.8 KB
1
import { get, writable } from 'svelte/store';
2
import { getAccountData, setAccountData } from './api';
3
import type { QuickReaction } from './types';
4
5
const EVENT_TYPE = 'dev.malice.quick_reactions';
6
7
export const DEFAULT_QUICK_REACTIONS: QuickReaction[] = [
8
  { key: '👍', shortcode: 'thumbsup' },
9
  { key: '❤️', shortcode: 'heart' },
10
  { key: '😂', shortcode: 'joy' },
11
  { key: '🎉', shortcode: 'tada' },
12
  { key: '😮', shortcode: 'open_mouth' },
13
  { key: '😢', shortcode: 'cry' }
14
];
15
16
export const quickReactions = writable<QuickReaction[]>(DEFAULT_QUICK_REACTIONS);
17
18
function parse(raw: unknown): QuickReaction[] | null {
19
  if (typeof raw !== 'object' || raw === null) return null;
20
  const list = (raw as Record<string, unknown>)['reactions'];
21
  if (!Array.isArray(list)) return null;
22
  const seen = new Set<string>();
23
  const out: QuickReaction[] = [];
24
  for (const item of list) {
25
    if (typeof item !== 'object' || item === null) continue;
26
    const { key, shortcode } = item as Record<string, unknown>;
27
    if (typeof key !== 'string' || !key || seen.has(key)) continue;
28
    seen.add(key);
29
    out.push({ key, shortcode: typeof shortcode === 'string' ? shortcode : null });
30
  }
31
  return out;
32
}
33
34
export async function loadQuickReactions(): Promise<void> {
35
  try {
36
    quickReactions.set(parse(await getAccountData(EVENT_TYPE)) ?? DEFAULT_QUICK_REACTIONS);
37
  } catch {
38
    quickReactions.set(DEFAULT_QUICK_REACTIONS);
39
  }
40
}
41
42
export async function saveQuickReactions(reactions: QuickReaction[]): Promise<void> {
43
  const previous = get(quickReactions);
44
  quickReactions.set(reactions);
45
  try {
46
    await setAccountData(EVENT_TYPE, { reactions });
47
  } catch (e) {
48
    if (get(quickReactions) === reactions) quickReactions.set(previous);
49
    throw e;
50
  }
51
}
52
53
export function resetQuickReactions(): void {
54
  quickReactions.set(DEFAULT_QUICK_REACTIONS);
55
}