From 5a0f961cd16665c6b5f09418f1cc89b8284dfdd6 Mon Sep 17 00:00:00 2001 From: Roland Date: Wed, 4 Jan 2023 11:16:40 -0700 Subject: [PATCH] Preserving loading state of Refresh button by creating global event subscription functions. --- app/src/Events.js | 24 ++++++++++++++++++++- app/src/components/Archive.js | 4 ++-- app/src/components/Files.js | 35 ++++++++++++++++++------------- app/src/components/VideoPlayer.js | 2 +- 4 files changed, 47 insertions(+), 18 deletions(-) diff --git a/app/src/Events.js b/app/src/Events.js index 132c6d8f..b3066fc1 100644 --- a/app/src/Events.js +++ b/app/src/Events.js @@ -3,6 +3,7 @@ import {toast} from "react-semantic-toasts"; import {useRecurringTimeout} from "./hooks/customHooks"; import {getEvents} from "./api"; +const apiEventName = 'apiEvent'; function eventToast(title, description, type = 'success', time = 5000) { toast({type: type, title: title, description: description, time: time}); @@ -13,7 +14,7 @@ function handleEvents(events) { events.forEach(e => { const {event, message, subject, dt} = e; - console.debug('event', e); + document.dispatchEvent(new CustomEvent(apiEventName, {detail: e})); if (subject && newestEvents[subject] && newestEvents[subject] > dt) { console.debug(`Already handled newer event of "${subject}".`); @@ -65,3 +66,24 @@ export function useEventsInterval() { return {events, fetchEvents} } + +export function useSubscribeEvents(listener) { + // Subscribe to all API sent events. + document.addEventListener(apiEventName, listener); + const unsubscribe = () => document.removeEventListener(apiEventName, listener); + + useEffect(() => { + return unsubscribe; + }, []); +} + +export function useSubscribeEventName(name, listener) { + // Subscribe to only API sent events that match `name`. + const localListener = (event) => { + if (event && event.detail['event'] === name) { + listener(event); + } + } + + useSubscribeEvents(localListener); +} diff --git a/app/src/components/Archive.js b/app/src/components/Archive.js index 8a5071d5..5009417a 100644 --- a/app/src/components/Archive.js +++ b/app/src/components/Archive.js @@ -394,14 +394,14 @@ function Archives() { />