refactored frontend events for code conciseness
This commit is contained in:
@@ -1,27 +1,16 @@
|
||||
import { writable } from "svelte/store";
|
||||
import { events, type UserStatusPayload } from "$lib/bindings";
|
||||
import {
|
||||
createListenersSubscription,
|
||||
removeFromStore,
|
||||
setupHmrCleanup,
|
||||
} from "./listener-utils";
|
||||
import { createEventSource, removeFromStore } from "./listener-utils";
|
||||
|
||||
export const friendsPresenceStates = writable<
|
||||
Record<string, UserStatusPayload>
|
||||
>({});
|
||||
export const currentPresenceState = writable<UserStatusPayload | null>(null);
|
||||
|
||||
const subscription = createListenersSubscription();
|
||||
|
||||
/**
|
||||
* Starts listening for user status changes and friend status updates.
|
||||
*/
|
||||
export async function startUserStatus() {
|
||||
if (subscription.isListening()) return;
|
||||
|
||||
try {
|
||||
const unlistenStatus = await events.friendUserStatusChanged.listen(
|
||||
(event) => {
|
||||
export const { start: startUserStatus, stop: stopUserStatus } =
|
||||
createEventSource(async (addEventListener) => {
|
||||
addEventListener(
|
||||
await events.friendUserStatusChanged.listen((event) => {
|
||||
const { userId, status } = event.payload;
|
||||
|
||||
const hasValidName =
|
||||
@@ -35,36 +24,21 @@ export async function startUserStatus() {
|
||||
...current,
|
||||
[userId]: status,
|
||||
}));
|
||||
},
|
||||
}),
|
||||
);
|
||||
subscription.addUnlisten(unlistenStatus);
|
||||
|
||||
const unlistenUserStatusChanged = await events.userStatusChanged.listen(
|
||||
(event) => {
|
||||
addEventListener(
|
||||
await events.userStatusChanged.listen((event) => {
|
||||
currentPresenceState.set(event.payload);
|
||||
},
|
||||
}),
|
||||
);
|
||||
subscription.addUnlisten(unlistenUserStatusChanged);
|
||||
|
||||
const unlistenFriendDisconnected = await events.friendDisconnected.listen(
|
||||
(event) => {
|
||||
addEventListener(
|
||||
await events.friendDisconnected.listen((event) => {
|
||||
const { userId } = event.payload;
|
||||
friendsPresenceStates.update((current) =>
|
||||
removeFromStore(current, userId),
|
||||
);
|
||||
},
|
||||
}),
|
||||
);
|
||||
subscription.addUnlisten(unlistenFriendDisconnected);
|
||||
|
||||
subscription.setListening(true);
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize user status listeners", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function stopUserStatus() {
|
||||
subscription.stop();
|
||||
}
|
||||
|
||||
setupHmrCleanup(stopUserStatus);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user