blob: 1b0aee90e44b4054dcd617b0c9fbb590364a449a (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
import { browser } from '$app/environment';
import type { UserIdentity } from '$lib/Data/AniList/identity';
import { writable } from 'svelte/store';
export const defaultIdentity: UserIdentity = {
name: '',
id: -2,
avatar: 'https://s4.anilist.co/file/anilistcdn/user/avatar/large/default.png'
};
const createStore = () => {
const { subscribe, set, update } = writable<UserIdentity>(
JSON.parse(
browser
? localStorage.getItem('identity') ?? JSON.stringify(defaultIdentity)
: JSON.stringify(defaultIdentity)
)
);
let state: UserIdentity;
subscribe((value) => (state = value));
return {
subscribe,
set,
update,
reset: () => set(defaultIdentity),
get: () => {
const keys = Object.keys(defaultIdentity);
const identityKeys = Object.keys(state);
const updatedIdentity = { ...state };
for (const key of keys)
if (!identityKeys.includes(key))
(updatedIdentity[key as keyof UserIdentity] as unknown) =
defaultIdentity[key as keyof UserIdentity];
if (browser) localStorage.setItem('identity', JSON.stringify(updatedIdentity));
return updatedIdentity;
},
setKey: (key: keyof UserIdentity, value: unknown) =>
update((identity) => ({ ...identity, [key]: value }))
};
};
const identity = createStore();
identity.subscribe((value) => {
if (browser) localStorage.setItem('identity', JSON.stringify(value));
});
export default identity;
|