UNPKG

@selfcommunity/react-core

Version:

React Core Components useful for integrating UI Community components (react-ui).

282 lines (280 loc) • 12.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const api_services_1 = require("@selfcommunity/api-services"); const types_1 = require("@selfcommunity/types"); const utils_1 = require("@selfcommunity/utils"); const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js")); const react_1 = require("react"); const use_deep_compare_effect_1 = require("use-deep-compare-effect"); const SCPreferencesProvider_1 = require("../components/provider/SCPreferencesProvider"); const Errors_1 = require("../constants/Errors"); const Notification_1 = require("../constants/Notification"); const Preferences_1 = require("../constants/Preferences"); const event_1 = require("../utils/event"); const useSCCachingManager_1 = tslib_1.__importDefault(require("./useSCCachingManager")); /** :::info This custom hook is used to manage the events followed. ::: :::tip How to use it: Follow these steps: ```jsx 1. const scUserContext: SCUserContextType = useSCUser(); 2. const scSubscribedEventsManager: SCSubscribedEventsManagerType = scUserContext.manager.events; 3. scSubscribedEventsManager.isSubscribed(event) ``` ::: */ function useSCSubscribedEventsManager(user) { const { cache, updateCache, emptyCache, data, setData, loading, setLoading, setUnLoading, isLoading } = (0, useSCCachingManager_1.default)(); const { preferences, features } = (0, SCPreferencesProvider_1.useSCPreferences)(); const authUserId = user ? user.id : null; const eventsEnabled = (0, react_1.useMemo)(() => preferences && features && features.includes(types_1.SCFeatureName.TAGGING) && Preferences_1.CONFIGURATIONS_EVENTS_ENABLED in preferences && preferences[Preferences_1.CONFIGURATIONS_EVENTS_ENABLED].value, [preferences, features]); const notificationInvitedToJoinEvent = (0, react_1.useRef)(null); // const notificationRequestedToJoinEvent = useRef(null); // const notificationAcceptedToJoinEvent = useRef(null); const notificationAddedToEvent = (0, react_1.useRef)(null); /** * Subscribe to notification types user_follow, user_unfollow */ (0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(() => { notificationInvitedToJoinEvent.current = pubsub_js_1.default.subscribe(`${types_1.SCNotificationTopicType.INTERACTION}.${types_1.SCNotificationTypologyType.USER_INVITED_TO_JOIN_EVENT}`, notificationSubscriber); notificationAddedToEvent.current = pubsub_js_1.default.subscribe(`${types_1.SCNotificationTopicType.INTERACTION}.${types_1.SCNotificationTypologyType.USER_ADDED_TO_EVENT}`, notificationSubscriber); return () => { pubsub_js_1.default.unsubscribe(notificationInvitedToJoinEvent.current); pubsub_js_1.default.unsubscribe(notificationAddedToEvent.current); }; }, [data]); /** * Notification subscriber handler * @param msg * @param dataMsg */ const notificationSubscriber = (msg, dataMsg) => { if (dataMsg.data.event !== undefined) { let _status; switch (Notification_1.SCNotificationMapping[dataMsg.data.activity_type]) { case types_1.SCNotificationTypologyType.USER_INVITED_TO_JOIN_EVENT: _status = types_1.SCEventSubscriptionStatusType.INVITED; break; case types_1.SCNotificationTypologyType.USER_ADDED_TO_EVENT: _status = types_1.SCEventSubscriptionStatusType.SUBSCRIBED; break; } updateCache([dataMsg.data.event]); setData((prev) => getDataUpdated(prev, dataMsg.data.event, _status)); } }; /** * Memoized refresh all events * It makes a single request to the server and retrieves * all the events followed by the user in a single solution * It might be useful for multi-tab sync */ const refresh = (0, react_1.useMemo)(() => () => { emptyCache(); if (user) { // Only if user is authenticated api_services_1.http .request({ url: api_services_1.Endpoints.GetUserSubscribedEvents.url({ id: user.id }), method: api_services_1.Endpoints.GetUserSubscribedEvents.method, }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } const eventsIds = res.data.results.map((e) => e.id); updateCache(eventsIds); setData(res.data.results.map((e) => ({ [e.id]: e.subscription_status }))); return Promise.resolve(res.data); }) .catch((e) => { utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, 'Unable to refresh the authenticated user events.'); utils_1.Logger.error(Errors_1.SCOPE_SC_CORE, e); }); } }, [data, user, cache]); /** * Memoized toggleEventAttendance Event * Toggle action */ const toggleEventAttendance = (0, react_1.useMemo)(() => (event) => { setLoading(event.id); const requestConfig = !event.subscription_status || event.subscription_status === types_1.SCEventSubscriptionStatusType.INVITED ? { url: api_services_1.Endpoints.SubscribeToEvent.url({ id: event.id }), method: api_services_1.Endpoints.SubscribeToEvent.method, } : event.subscription_status === types_1.SCEventSubscriptionStatusType.GOING ? { url: api_services_1.Endpoints.RemoveGoingToEvent.url({ id: event.id }), method: api_services_1.Endpoints.RemoveGoingToEvent.method, } : { url: api_services_1.Endpoints.GoToEvent.url({ id: event.id }), method: api_services_1.Endpoints.GoToEvent.method, }; return api_services_1.http.request(requestConfig).then((res) => { if (res.status >= 300) { return Promise.reject(res); } let newStatus = (0, event_1.getEventStatus)(event, true); if (event.subscription_status === types_1.SCEventSubscriptionStatusType.NOT_GOING) { newStatus = (0, event_1.getEventStatus)(Object.assign({}, event, { subscription_status: types_1.SCEventSubscriptionStatusType.SUBSCRIBED }), true); } setData((prev) => getDataUpdated(prev, event.id, newStatus)); updateCache([event.id]); setUnLoading(event.id); return Promise.resolve(Object.assign({}, event, { subscription_status: newStatus })); }); }, [data, loading, cache]); /** * Memoized toggleEventNonattendance Event * Toggle action */ const toggleEventNonattendance = (0, react_1.useMemo)(() => (event) => { if (event.subscription_status !== types_1.SCEventSubscriptionStatusType.REQUESTED) { setLoading(event.id); const requestConfig = event.subscription_status === types_1.SCEventSubscriptionStatusType.NOT_GOING ? { url: api_services_1.Endpoints.RemoveNotGoingToEvent.url({ id: event.id }), method: api_services_1.Endpoints.RemoveNotGoingToEvent.method, } : { url: api_services_1.Endpoints.NotGoingToEvent.url({ id: event.id }), method: api_services_1.Endpoints.NotGoingToEvent.method, }; return api_services_1.http.request(requestConfig).then((res) => { if (res.status >= 300) { return Promise.reject(res); } let newStatus = (0, event_1.getEventStatus)(event, false); if (event.subscription_status === types_1.SCEventSubscriptionStatusType.GOING) { newStatus = (0, event_1.getEventStatus)(Object.assign({}, event, { subscription_status: types_1.SCEventSubscriptionStatusType.SUBSCRIBED }), false); } setData((prev) => getDataUpdated(prev, event.id, newStatus)); updateCache([event.id]); setUnLoading(event.id); return Promise.resolve(Object.assign({}, event, { subscription_status: newStatus })); }); } else { setLoading(event.id); return api_services_1.http .request({ url: api_services_1.Endpoints.UnsubscribeFromEvent.url({ id: event.id }), method: api_services_1.Endpoints.UnsubscribeFromEvent.method }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } updateCache([event.id]); setData((prev) => getDataUpdated(prev, event.id, null)); setUnLoading(event.id); return Promise.resolve(Object.assign({}, event, { subscription_status: null })); }); } }, [data, loading, cache]); /** * Check the authenticated user subscription status to the event * Update the events cached * Update events subscription statuses * @param event */ const checkEventSubscriptionStatus = (event) => { setLoading(event.id); return api_services_1.http .request({ url: api_services_1.Endpoints.GetEventSubscriptionStatus.url({ id: event.id }), method: api_services_1.Endpoints.GetEventSubscriptionStatus.method, }) .then((res) => { if (res.status >= 300) { return Promise.reject(res); } setData((prev) => getDataUpdated(prev, event.id, res.data.status)); updateCache([event.id]); setUnLoading(event.id); return Promise.resolve(res.data); }) .catch((e) => { setUnLoading(event.id); return Promise.reject(e); }); }; /** * Get updated data * @param data * @param eventId * @param subscriptionStatus */ const getDataUpdated = (data, eventId, subscriptionStatus) => { const _index = data.findIndex((k) => parseInt(Object.keys(k)[0]) === eventId); let _data; if (_index < 0) { _data = [...data, ...[{ [eventId]: subscriptionStatus }]]; } else { _data = data.map((k, i) => { if (parseInt(Object.keys(k)[0]) === eventId) { return { [Object.keys(k)[0]]: subscriptionStatus }; } return { [Object.keys(k)[0]]: data[i][Object.keys(k)[0]] }; }); } return _data; }; /** * Return current event subscription status if exists, * otherwise return null */ const getCurrentEventCacheStatus = (0, react_1.useMemo)(() => (event) => { const d = data.filter((k) => parseInt(Object.keys(k)[0]) === event.id); return d.length ? d[0][event.id] : !data.length ? event.subscription_status : null; }, [data]); /** * Bypass remote check if the event is subscribed */ const getSubscriptionStatus = (0, react_1.useMemo)(() => (event) => { updateCache([event.id]); setData((prev) => getDataUpdated(prev, event.id, event.subscription_status)); return event.subscription_status; }, [data, cache]); /** * Memoized subscriptionStatus * If event is already in cache -> check if the event is in events, * otherwise, check if user toggleEventAttendance the event */ const subscriptionStatus = (0, react_1.useMemo)(() => (event) => { // Cache is valid also for anonymous user if (cache.includes(event === null || event === void 0 ? void 0 : event.id)) { return getCurrentEventCacheStatus(event); } if (authUserId && event) { if ('subscription_status' in event) { return getSubscriptionStatus(event); } if (!isLoading(event)) { checkEventSubscriptionStatus(event); } } return null; }, [loading, cache, authUserId, getSubscriptionStatus, getCurrentEventCacheStatus]); /** * Empty cache on logout */ (0, react_1.useEffect)(() => { if (!authUserId) { emptyCache(); } }, [authUserId]); if (!eventsEnabled || !user) { return { events: data, loading, isLoading }; } return { events: data, loading, isLoading, toggleEventAttendance, toggleEventNonattendance, subscriptionStatus, refresh, emptyCache }; } exports.default = useSCSubscribedEventsManager;