chore: update

This commit is contained in:
huzibaca 2024-09-26 12:20:57 +08:00
parent 7a9fd118a3
commit 053754fea8
No known key found for this signature in database
GPG Key ID: D4364EE4851DC302

View File

@ -1,34 +1,31 @@
import { listen, UnlistenFn, EventCallback } from "@tauri-apps/api/event";
import { event } from "@tauri-apps/api";
import { useRef } from "react";
export const useListen = () => {
let unlistenFns: UnlistenFn[] = [];
const unlistenFns = useRef<UnlistenFn[]>([]);
const addListener = async function <T>(
const addListener = async <T>(
eventName: string,
handler: EventCallback<T>
) {
) => {
const unlisten = await listen(eventName, handler);
unlistenFns.push(unlisten);
unlistenFns.current.push(unlisten);
return unlisten;
};
const removeAllListeners = async function () {
for (const unlisten of unlistenFns) {
Promise.resolve(unlisten()).catch(console.error);
}
unlistenFns = [];
const removeAllListeners = () => {
unlistenFns.current.forEach((unlisten) => unlisten());
unlistenFns.current = [];
};
const setupCloseListener = async function () {
await event.once("tauri://close-requested", async () => {
console.log("Window close requested.");
await removeAllListeners();
removeAllListeners();
});
};
return {
addListener,
removeAllListeners,
setupCloseListener,
};
};