atagen

malice

public
Star0
Watch0
ed3363baaf0183507124a2397eaa37604e1a0fa0
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/quick-reactions.tsTypescript57 lines1.9 KB
1
import { get, writable } from 'svelte/store';
2
import { getAccountData, setAccountData } from './api';
3
import { MAX_QUICK_REACTIONS } from './types';
4
import type { 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<QuickReaction[]>(DEFAULT_QUICK_REACTIONS);
18
19
function parse(raw: unknown): QuickReaction[] | null {
20
  if (typeof raw !== 'object' || raw === null) return null;
21
  const list = (raw as Record<string, unknown>)['reactions'];
22
  if (!Array.isArray(list)) return null;
23
  const seen = new Set<string>();
24
  const out: QuickReaction[] = [];
25
  for (const item of list) {
26
    if (typeof item !== 'object' || item === null) continue;
27
    const { key, shortcode } = item as Record<string, unknown>;
28
    if (typeof key !== 'string' || !key || seen.has(key)) continue;
29
    seen.add(key);
30
    out.push({ key, shortcode: typeof shortcode === 'string' ? shortcode : null });
31
  }
32
  return out.slice(0, MAX_QUICK_REACTIONS);
33
}
34
35
export async function loadQuickReactions(): Promise<void> {
36
  try {
37
    quickReactions.set(parse(await getAccountData(EVENT_TYPE)) ?? DEFAULT_QUICK_REACTIONS);
38
  } catch {
39
    quickReactions.set(DEFAULT_QUICK_REACTIONS);
40
  }
41
}
42
43
export async function saveQuickReactions(list: QuickReaction[]): Promise<void> {
44
  const reactions = list.slice(0, MAX_QUICK_REACTIONS);
45
  const previous = get(quickReactions);
46
  quickReactions.set(reactions);
47
  try {
48
    await setAccountData(EVENT_TYPE, { reactions });
49
  } catch (e) {
50
    if (get(quickReactions) === reactions) quickReactions.set(previous);
51
    throw e;
52
  }
53
}
54
55
export function resetQuickReactions(): void {
56
  quickReactions.set(DEFAULT_QUICK_REACTIONS);
57
}