All files / src/providers AchievementProvider.tsx

89.65% Statements 78/87
72.72% Branches 24/33
89.65% Functions 26/29
89.87% Lines 71/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 2122x 2x   2x 2x 2x                 2x 2x 2x 2x               2x   2x 19x 19x     19x       2x 2x   2x         2x 76x             76x     2x                 37x 37x 37x 69x 69x 69x 37x 37x     37x 7x     37x 23x 46x 46x   26x 26x 74x             26x 26x       7x 7x             37x 36x 7x 7x                                         7x         37x 13x 6x 6x         37x 23x       37x 8x 7x 7x               37x 22x   8x   9x 8x   8x     37x     2x       2x         1x 1x   1x 1x                                                   2x
import React, { useEffect, useCallback, useState, useMemo, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { RootState, AppDispatch } from '../redux/store';
import { initialize, setMetrics, resetAchievements, unlockAchievement, clearNotifications } from '../redux/achievementSlice';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import {
    AchievementDetails,
    AchievementMetricValue,
    AchievementConfiguration,
    AchievementProviderProps,
    AchievementMetrics,
    AchievementState
} from '../types';
import BadgesButton from '../components/BadgesButton';
import BadgesModal from '../components/BadgesModal';
import ConfettiWrapper from '../components/ConfettiWrapper';
import { defaultStyles } from '../defaultStyles';
 
export interface AchievementContextType {
    updateMetrics: (metrics: AchievementMetrics | ((prev: AchievementMetrics) => AchievementMetrics)) => void;
    unlockedAchievements: string[];
    resetStorage: () => void;
}
 
export const AchievementContext = React.createContext<AchievementContextType | null>(null);
 
export const useAchievementContext = () => {
    const context = React.useContext(AchievementContext);
    Iif (!context) {
        throw new Error('useAchievementContext must be used within an AchievementProvider');
    }
    return context;
};
 
// Helper function to serialize dates for Redux actions
const serializeMetrics = (metrics: AchievementMetrics): AchievementMetrics => {
    return Object.entries(metrics).reduce((acc, [key, values]) => ({
        ...acc,
        [key]: values.map(value => value instanceof Date ? value.toISOString() : value)
    }), {} as AchievementMetrics);
};
 
// Helper function to parse potential date strings
const deserializeValue = (value: string | number | boolean): AchievementMetricValue => {
    Iif (typeof value === 'string') {
        // Try to parse ISO date string
        const date = new Date(value);
        Iif (!isNaN(date.getTime()) && value === date.toISOString()) {
            return date;
        }
    }
    return value;
};
 
const AchievementProvider: React.FC<AchievementProviderProps> = ({
    children,
    config,
    initialState = {},
    storageKey = 'react-achievements',
    badgesButtonPosition = 'top-right',
    styles = {},
    icons = {},
}) => {
    const dispatch: AppDispatch = useDispatch();
    const configRef = useRef(config);
    const isMountedRef = useRef(false);
    const metrics = useSelector((state: RootState) => state.achievements.metrics);
    const unlockedAchievementIds = useSelector((state: RootState) => state.achievements.unlockedAchievements);
    const pendingNotifications = useSelector((state: RootState) => state.achievements.pendingNotifications);
    const [showBadges, setShowBadges] = useState(false);
    const [showConfetti, setShowConfetti] = useState(false);
 
    // Update config ref when it changes
    useEffect(() => {
        configRef.current = config;
    }, [config]);
 
    const checkAchievements = useCallback(() => {
        Object.entries(configRef.current).forEach(([metricName, conditions]) => {
            const metricValues = metrics[metricName];
            if (!metricValues) return;
 
            const latestValue = deserializeValue(metricValues[metricValues.length - 1]);
            const state: AchievementState = {
                metrics: Object.entries(metrics).reduce((acc, [key, values]) => ({
                    ...acc,
                    [key]: values.map(deserializeValue)
                }), {}),
                unlockedAchievements: unlockedAchievementIds
            };
 
            conditions.forEach((condition) => {
                if (
                    condition.isConditionMet(latestValue, state) &&
                    !unlockedAchievementIds.includes(condition.achievementDetails.achievementId)
                ) {
                    dispatch(unlockAchievement(condition.achievementDetails));
                    setShowConfetti(true);
                }
            });
        });
    }, [metrics, unlockedAchievementIds, dispatch]);
 
    // Handle notifications
    useEffect(() => {
        if (pendingNotifications.length > 0) {
            pendingNotifications.forEach((notification) => {
                toast.success(
                    <div>
                        <h4 style={{ margin: '0 0 8px 0' }}>Achievement Unlocked! 🎉</h4>
                        <strong>{notification.achievementTitle}</strong>
                        <p style={{ margin: '4px 0 0 0' }}>{notification.achievementDescription}</p>
                        {notification.achievementIconKey && icons[notification.achievementIconKey] && (
                            <div style={{ fontSize: '24px', marginTop: '8px' }}>
                                {icons[notification.achievementIconKey]}
                            </div>
                        )}
                    </div>,
                    {
                        position: "top-right",
                        autoClose: 5000,
                        hideProgressBar: false,
                        closeOnClick: true,
                        pauseOnHover: true,
                        draggable: true,
                    }
                );
            });
            dispatch(clearNotifications());
        }
    }, [pendingNotifications, dispatch, icons]);
 
    // Reset confetti after delay
    useEffect(() => {
        if (showConfetti) {
            const timer = setTimeout(() => setShowConfetti(false), 5000);
            return () => clearTimeout(timer);
        }
    }, [showConfetti]);
 
    // Check for achievements when metrics change
    useEffect(() => {
        checkAchievements();
    }, [metrics, checkAchievements]);
 
    // Initialize on mount, but don't store config in Redux
    useEffect(() => {
        if (!isMountedRef.current) {
            isMountedRef.current = true;
            dispatch(initialize({
                initialState,
                storageKey,
            }));
        }
    }, [dispatch, initialState, storageKey]);
 
    // Convert achievement IDs to details using config from ref
    const achievementDetails = useMemo(() => {
        return unlockedAchievementIds
            .map(id => {
                const achievement = Object.values(configRef.current)
                    .flat()
                    .find(condition => condition.achievementDetails.achievementId === id);
                return achievement?.achievementDetails;
            })
            .filter((a): a is AchievementDetails => !!a);
    }, [unlockedAchievementIds]);
 
    return (
        <AchievementContext.Provider value={{
            updateMetrics: (newMetrics) => {
                Iif (typeof newMetrics === 'function') {
                    const updatedMetrics = newMetrics(metrics);
                    dispatch(setMetrics(serializeMetrics(updatedMetrics)));
                } else {
                    dispatch(setMetrics(serializeMetrics(newMetrics)));
                }
            },
            unlockedAchievements: unlockedAchievementIds,
            resetStorage: () => {
                if (storageKey) {
                    localStorage.removeItem(storageKey);
                }
                dispatch(resetAchievements());
                dispatch(initialize({ 
                    storageKey,
                    initialState: undefined  // Force empty state
                }));
            },
        }}>
            {children}
            <ToastContainer />
            <ConfettiWrapper show={showConfetti} />
            <BadgesButton
                onClick={() => setShowBadges(true)}
                position={badgesButtonPosition}
                styles={styles.badgesButton || defaultStyles.badgesButton}
                unlockedAchievements={achievementDetails}
            />
            <BadgesModal
                isOpen={showBadges}
                achievements={achievementDetails}
                onClose={() => setShowBadges(false)}
                styles={styles.badgesModal || defaultStyles.badgesModal}
                icons={icons}
            />
        </AchievementContext.Provider>
    );
};
 
export { AchievementProvider };