All files / app layout.tsx

0% Statements 0/226
100% Branches 1/1
100% Functions 1/1
0% Lines 0/226

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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client';
 
import 'bootstrap/dist/css/bootstrap.min.css';
import './globals.css';
import { GoogleAnalytics } from '@next/third-parties/google';
import {
  useCallback, useEffect, useState
} from 'react';
import Alert from 'react-bootstrap/Alert';
import Container from 'react-bootstrap/Container';
import { Variant } from 'react-bootstrap/esm/types';
 
import {
  FrontendUserObject, FrontendUserState, GetUserApi, validDepartments
} from '@/types/api/users';
import { getLogger } from '@/utils/common/logger';
import {
  AddAlertContext, DarkModeContext, LocationContext, LoggedInUserContext, RefreshLoggedInUserContext
} from '@/utils/frontend/clientContexts';
import { typeFetch } from '@/utils/frontend/typeFetch';
import './envConfig';
 
const logger = getLogger('layout');
 
function useDarkMode() {
  const [
    isDarkMode,
    setIsDarkMode,
  ] = useState<boolean>();
 
  useEffect(() => {
    setIsDarkMode(window.matchMedia('(prefers-color-scheme: dark)').matches);
 
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleChange = (event: MediaQueryListEvent) => {
      setIsDarkMode(event.matches);
    };
 
    mediaQuery.addEventListener('change', handleChange);
 
    return () => {
      mediaQuery.removeEventListener('change', handleChange);
    };
  }, []);
 
  return isDarkMode;
}
 
function useLocation() {
  const [
    loc,
    setLoc,
  ] = useState<Location | null>(null);
 
  useEffect(() => {
    setLoc(window.location);
 
    window.addEventListener('popstate', () => {
      setLoc(window.location);
    });
  }, []);
 
  return loc;
}
 
const localStorageUserKey = 'cofrn-user';
 
function useUser(addAlert: (type: Variant, message: string) => void): [
  FrontendUserState | null,
  () => Promise<void>
] {
  const [
    user,
    setUser,
  ] = useState<FrontendUserState | null>(null);
 
  async function getUserFromApi() {
    try {
      const [
        code,
        apiResult,
      ] = await typeFetch<GetUserApi>({
        path: '/api/v2/users/{id}/',
        method: 'GET',
        params: {
          id: 'current',
        },
      });
 
      if (
        code !== 200 ||
        apiResult === null ||
        'message' in apiResult
      ) {
        throw {
          code,
          apiResult,
        };
      }
 
      localStorage.setItem(localStorageUserKey, JSON.stringify(apiResult));
      setUser({
        fromApi: true,
        isFinal: true,
        isUser: true,
        isDistrictAdmin: false,
        isAdmin: validDepartments.some(dep => apiResult[dep]?.active && apiResult[dep].admin),
        ...apiResult,
      });
    } catch (e) {
      addAlert('danger', 'Failed to update the current user\'s information');
      logger.error('Failed to fetch current user', e);
    }
  }
 
  useEffect(() => {
    if (user?.fromApi) {
      return;
    }
 
    // Parse information out of the cookies
    const cookies: {
      [key: string]: string | null;
    } = {};
    document.cookie.split('; ').forEach(cookie => {
      const eqSign = cookie.indexOf('=');
      if (eqSign === -1) {
        cookies[cookie] = null;
        return;
      }
 
      cookies[cookie.slice(0, eqSign)] = decodeURIComponent(cookie.slice(eqSign + 1));
    });
 
    // Check the cookies for an active user
    if (
      !cookies['cofrn-token'] ||
      !cookies['cofrn-user']
    ) {
      localStorage.removeItem(localStorageUserKey);
      setUser({
        fromApi: false,
        isFinal: true,
        isUser: false,
        isAdmin: false,
        isDistrictAdmin: false,
      });
      return;
    }
 
    // Start the process of fetching the user info from the API
    getUserFromApi();
 
    // Check localStorage for a user
    const lsUserStr = localStorage.getItem(localStorageUserKey);
    if (lsUserStr === null) {
      setUser({
        fromApi: false,
        isFinal: false,
        isUser: false,
        isAdmin: false,
        isDistrictAdmin: false,
      });
      return;
    }
 
    try {
      const initUser: FrontendUserObject = JSON.parse(lsUserStr);
      logger.log('Initial User:', initUser);
      setUser({
        fromApi: false,
        isFinal: false,
        isUser: true,
        isDistrictAdmin: true,
        isAdmin: validDepartments.some(dep => initUser[dep]?.active && initUser[dep].admin),
        ...initUser,
      });
    } catch (e) {
      addAlert('danger', 'Invalid user information was found, attempting to refresh the user');
      logger.error('Failed to parse localStorage user', e);
      localStorage.removeItem(localStorageUserKey);
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps
 
  return [
    user,
    getUserFromApi,
  ];
}
 
function randomKey() {
  const vals = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  const key = Array.from(Array(10), () => vals[Math.floor(Math.random() * vals.length)])
    .join('');
 
  return key;
}
 
interface AlertConfig {
  type: Variant;
  message: string;
  id: string;
}
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const [
    alerts,
    setAlerts,
  ] = useState<AlertConfig[]>([]);
  const addAlert = useCallback((type: Variant, message: string) => {
    const id = randomKey();
    setAlerts(cur => [
      ...cur,
      {
        type,
        message,
        id,
      },
    ]);
 
    setTimeout(() => setAlerts(cur => cur.filter(a => a.id !== id)), 5000);
  }, []);
 
  const isDarkMode = useDarkMode();
  const loc = useLocation();
  const [
    user,
    refreshUser,
  ] = useUser(addAlert);
 
  if (
    typeof isDarkMode === 'undefined' ||
    typeof location === 'undefined' ||
    user === null
  ) {
    return <html>
      <head><link rel='icon' type='image/png' href='/favicon.png' /></head>
      <body data-bs-theme={'dark'}></body>
    </html>;
  }
 
  const modeName = isDarkMode ? 'dark' : 'light';
  return (
    <html lang='en'>
      <head><link rel='icon' type='image/png' href='/favicon.png' /></head>
      <body data-bs-theme={modeName}>
        {alerts.length > 0 && <Container
          style={{
            position: 'fixed',
            top: '60px',
            left: '50%',
            transform: 'translate(-50%, 0%)',
            zIndex: 1000,
          }}
        >
          {alerts.map(alertConf => <Alert
            dismissible
            key={alertConf.id}
            className='alert-fixed'
            variant={alertConf.type}
            onClose={() => setAlerts(cur => cur.filter(a => a.id !== alertConf.id))}
          >{alertConf.message}</Alert>)}
        </Container>}
 
        <DarkModeContext.Provider value={modeName}>
          <LocationContext.Provider value={loc}>
            <LoggedInUserContext.Provider value={user}>
              <RefreshLoggedInUserContext.Provider value={refreshUser}>
                <AddAlertContext.Provider value={addAlert}>
                  {children}
                </AddAlertContext.Provider>
              </RefreshLoggedInUserContext.Provider>
            </LoggedInUserContext.Provider>
          </LocationContext.Provider>
        </DarkModeContext.Provider>
      </body>
      <GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GA_ID as string} />
    </html>
  );
}