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
54
55
56
57
58
59
60
61
62
63
64
65
|
import { writable } from 'svelte/store';
import { get, set } from 'idb-keyval';
import type { VideoThumbnail } from '$lib/api/youtube';
export interface Subscription {
channelId: string;
channelName: string;
thumbnail: string;
}
const STORAGE_KEY = 'actualyt-subscriptions';
function createSubscriptionStore() {
const { subscribe, set: setStore, update } = writable<Subscription[]>([]);
let initialized = false;
async function init() {
if (initialized) return;
try {
const stored = await get<Subscription[]>(STORAGE_KEY);
if (stored) {
setStore(stored);
}
initialized = true;
} catch (e) {
console.error('Failed to load subscriptions:', e);
}
}
async function persist(subs: Subscription[]) {
try {
await set(STORAGE_KEY, subs);
} catch (e) {
console.error('Failed to save subscriptions:', e);
}
}
return {
subscribe,
init,
add: async (channelId: string, channelName: string, thumbnails: VideoThumbnail[]) => {
update(subs => {
if (subs.some(s => s.channelId === channelId)) {
return subs;
}
const thumbnail = thumbnails[0]?.url || '';
const newSubs = [...subs, { channelId, channelName, thumbnail }];
persist(newSubs);
return newSubs;
});
},
remove: async (channelId: string) => {
update(subs => {
const newSubs = subs.filter(s => s.channelId !== channelId);
persist(newSubs);
return newSubs;
});
},
isSubscribed: (subs: Subscription[], channelId: string): boolean => {
return subs.some(s => s.channelId === channelId);
}
};
}
export const subscriptions = createSubscriptionStore();
|