databag/net/web/src/session/useSession.hook.js

84 lines
2.0 KiB
JavaScript
Raw Normal View History

2022-08-13 18:24:49 +00:00
import { useContext, useState, useEffect, useRef } from 'react';
import { CardContext } from 'context/CardContext';
import { StoreContext } from 'context/StoreContext';
2022-08-05 22:06:53 +00:00
export function useSession() {
const [state, setState] = useState({
2022-08-13 18:24:49 +00:00
cardUpdated: false,
2022-08-05 22:06:53 +00:00
conversation: false,
details: false,
cards: false,
contact: false,
profile: false,
2022-08-15 20:10:09 +00:00
stats: false,
2022-08-05 22:06:53 +00:00
});
2022-08-13 18:24:49 +00:00
const card = useContext(CardContext);
const store = useContext(StoreContext);
const storeStatus = useRef(null);
const cardStatus = useRef(null);
2022-08-05 22:06:53 +00:00
const updateState = (value) => {
setState((s) => ({ ...s, ...value }));
}
useEffect(() => {
2022-08-13 18:24:49 +00:00
const contacts = Array.from(card.state.cards.values());
let updated;
contacts.forEach(contact => {
if (!updated || updated < contact?.data?.cardDetail?.statusUpdated) {
updated = contact?.data?.cardDetail?.statusUpdated;
}
});
if (state.cards) {
cardStatus.current = updated;
storeStatus.current = updated;
store.actions.setValue('cards:updated', updated);
}
updateState({ cardUpdated: cardStatus.current > storeStatus.current });
}, [card]);
useEffect(() => {
storeStatus.current = store.actions.getValue('cards:updated');
updateState({ cardUpdated: cardStatus.current > storeStatus.current });
}, [store]);
2022-08-05 22:06:53 +00:00
const actions = {
closeDetails: () => {
updateState({ details: false });
},
2022-08-07 06:41:09 +00:00
openCards: () => {
updateState({ cards: true });
},
2022-08-05 22:06:53 +00:00
closeCards: () => {
updateState({ cards: false });
},
closeContact: () => {
updateState({ contact: false });
},
2022-08-07 06:41:09 +00:00
openProfile: () => {
updateState({ profile: true });
},
2022-08-05 22:06:53 +00:00
closeProfile: () => {
updateState({ profile: false });
},
2022-08-15 20:10:09 +00:00
openStats: () => {
updateState({ stats: true });
},
closeStats: () => {
updateState({ stats: false });
},
2022-08-05 22:06:53 +00:00
closeConversation: () => {
updateState({ conversation: false });
},
};
return { state, actions };
}