Updated airport data, fixed loader/header

This commit is contained in:
2023-12-21 14:19:17 -05:00
parent 8438acc68b
commit 0b2ef94b99
26 changed files with 472068 additions and 62093 deletions

View File

@@ -1,7 +1,5 @@
'use client';
import { login, register, refreshLoggedIn } from '@/api/auth';
import { User } from '@/api/auth.types';
import {
Modal,
Container,
@@ -16,16 +14,15 @@ import {
Text
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
interface HeaderModalProps {
type?: string;
toggle: any;
setUser: (user: User) => void;
setRefreshId: (id: NodeJS.Timeout) => void;
login: ({ email, password }: { email: string, password: string }) => Promise<boolean>;
register: ({ firstName, lastName, email, password }: { firstName: string, lastName: string, email: string, password: string }) => Promise<boolean>;
}
export function HeaderModal({ type, toggle, setUser, setRefreshId }: HeaderModalProps) {
export function HeaderModal({ type, toggle, login, register }: HeaderModalProps) {
function passwordValidator(value: string) {
if (value.trim().length < 10) {
return 'Password must be at least 10 characters';
@@ -129,52 +126,9 @@ export function HeaderModal({ type, toggle, setUser, setRefreshId }: HeaderModal
<Paper withBorder shadow='md' p={30} mt={30} radius='md'>
<form
onSubmit={registerForm.onSubmit(async (values) => {
const id = notifications.show({
loading: true,
title: `Creating account`,
message: `Please wait...`,
autoClose: false,
withCloseButton: false
});
const registerResponse = await register({
first_name: values.firstName,
last_name: values.lastName,
email: values.email,
password: values.password
});
if (registerResponse) {
const loginResponse = await login(values.email, values.password);
if (loginResponse) {
setUser(loginResponse.user);
setRefreshId(refreshLoggedIn());
onClose();
notifications.update({
id,
title: `Account created`,
message: `Welcome ${loginResponse.user.first_name}!`,
color: 'green',
autoClose: 2000,
loading: false
});
} else {
notifications.update({
id,
title: `Unable to Login`,
message: `Please try again.`,
color: 'red',
autoClose: 2000,
loading: false
});
}
} else {
notifications.update({
id,
title: `Unable to Register`,
message: `Please try again.`,
color: 'error',
autoClose: 2000,
loading: false
});
const success = await register(values);
if (success) {
onClose();
}
})}
>
@@ -219,18 +173,9 @@ export function HeaderModal({ type, toggle, setUser, setRefreshId }: HeaderModal
<Paper withBorder shadow='md' p={30} mt={30} radius='md'>
<form
onSubmit={loginForm.onSubmit(async (values) => {
const response = await login(values.email, values.password);
if (response) {
setUser(response.user);
setRefreshId(refreshLoggedIn());
const success = await login(values);
if (success) {
onClose();
} else {
notifications.show({
title: `Unable to Login`,
message: `Please try again.`,
color: 'red',
autoClose: 2000
});
}
})}
>

View File

@@ -1,55 +1,31 @@
'use client';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useState } from 'react';
import { getAirport, getAirports } from '@/api/airport';
import { Autocomplete, Avatar, Button, Card, FileButton, Grid, Group, Menu, Text, UnstyledButton } from '@mantine/core';
import './header.css';
import { refresh, refreshLoggedIn, logout } from '@/api/auth';
import Cookies from 'js-cookie';
import { useRecoilState } from 'recoil';
import { userState } from '@/state/auth';
import { getFavorites, getPicture, setPicture } from '@/api/users';
import { SetterOrUpdater, useRecoilState } from 'recoil';
import { setPicture } from '@/api/users';
import { useToggle } from '@mantine/hooks';
import { HeaderModal } from './HeaderModal';
import { favoritesState } from '@/state/user';
import { coordinatesState, zoomState } from '@/state/map';
import { coordinatesState } from '@/state/map';
import { User } from '@/api/auth.types';
export default function Header() {
const [loading, setLoading] = useState(true);
interface HeaderProps {
user: User | undefined;
profilePicture: File | undefined;
setProfilePicture: SetterOrUpdater<File | undefined>;
login: ({ email, password }: { email: string, password: string }) => Promise<boolean>;
logout: () => Promise<void>;
register: ({ firstName, lastName, email, password }: { firstName: string, lastName: string, email: string, password: string }) => Promise<boolean>;
}
export default function Header({ user, profilePicture, setProfilePicture, login, logout, register }: HeaderProps) {
const [searchValue, setSearchValue] = useState('');
const [airports, setAirports] = useState<{ key: string; value: string; label: string }[]>([]);
const [modalType, toggle] = useToggle([undefined, 'login', 'register', 'reset']);
const [user, setUser] = useRecoilState(userState);
const [favorites, setFavorites] = useRecoilState(favoritesState);
const [refreshId, setRefreshId] = useState<NodeJS.Timeout | undefined>(undefined);
const [profilePicture, setProfilePicture] = useState<File | null>(null);
const [coordinates, setCoordinates] = useRecoilState(coordinatesState);
const [zoom, setZoom] = useRecoilState(zoomState);
useEffect(() => {
if (!user || !Cookies.get('logged_in')) {
refresh().then((response) => {
if (response) {
setRefreshId(refreshLoggedIn());
setUser(response.user);
getFavorites().then((response) => {
if (response) {
setFavorites(response);
}
});
if (response.user.profile_picture) {
getPicture().then((response) => {
if (response) {
setProfilePicture(response as File);
}
});
}
}
});
}
setLoading(false);
}, [user]);
const [_, setCoordinates] = useRecoilState(coordinatesState);
async function onChange(value: string) {
setSearchValue(value);
@@ -91,160 +67,130 @@ export default function Header() {
</div>
</div>
<UserSection
user={user}
profilePicture={profilePicture}
setProfilePicture={setProfilePicture}
toggle={toggle}
setFavorites={setFavorites}
refreshId={refreshId}
loading={loading}
logout={logout}
/>
</nav>
<HeaderModal
type={modalType}
toggle={toggle}
setUser={(u) => {
setUser(u);
getFavorites().then((response) => {
if (response) {
setFavorites(response);
}
});
if (u.profile_picture) {
getPicture().then((response) => {
if (response) {
setProfilePicture(response as File);
}
});
}
}}
setRefreshId={setRefreshId}
login={login}
register={register}
/>
</>
);
}
interface UserSectionProps {
profilePicture: File | null;
setProfilePicture: (picture: File | null) => void;
user: User | undefined;
profilePicture: File | undefined;
setProfilePicture: SetterOrUpdater<File | undefined>;
toggle: (type: string) => void;
setFavorites: (favorites: string[]) => void;
refreshId: NodeJS.Timeout | undefined;
loading: boolean;
logout: () => Promise<void>;
}
function UserSection({ profilePicture, setProfilePicture, setFavorites, refreshId, toggle, loading }: UserSectionProps) {
const [user, setUser] = useRecoilState(userState);
function UserSection({ user, profilePicture, setProfilePicture, logout, toggle }: UserSectionProps) {
return (
<div className='user-section'>
{loading ? (
<></>
) : (
<>
{user ? (
<Menu shadow='md' width={200} openDelay={100} closeDelay={400}>
<Menu.Target>
<UnstyledButton className='user user-button'>
<Group>
<Avatar src={profilePicture ? URL.createObjectURL(profilePicture) : undefined} />
<div style={{ flex: 1 }}>
<Text size='sm' fw={500}>
{user.first_name} {user.last_name}
</Text>
<Text c='dimmed' size='xs' style={{ textTransform: 'uppercase' }}>
{user.role}
</Text>
</div>
</Group>
</UnstyledButton>
</Menu.Target>
<Menu.Dropdown p={0}>
<Card>
<Card.Section h={140} style={{ backgroundColor: '#4481e3' }} />
<FileButton
onChange={(payload) => {
if (payload) {
setPicture(payload).then((response) => {
if (response) {
setProfilePicture(payload);
}
});
}
}}
accept='image/png,image/jpeg,image/jpg'
multiple={false}
>
{(props) => (
<Avatar
{...props}
component='button'
size={80}
radius={80}
mx={'auto'}
mt={-30}
style={{ cursor: 'pointer' }}
bg={profilePicture ? 'transparent' : 'white'}
src={profilePicture ? URL.createObjectURL(profilePicture) : undefined}
/>
)}
</FileButton>
<Text ta='center' fz='lg' fw={500} mt='sm'>
{user.first_name} {user.last_name}
</Text>
<Text ta='center' fz='sm' c='dimmed' style={{ textTransform: 'uppercase' }}>
{user.role}
</Text>
<Grid mt='xl'>
<Grid.Col span={6}>
<Link href='/profile'>
<>
{user ? (
<Menu shadow='md' width={200} openDelay={100} closeDelay={400}>
<Menu.Target>
<UnstyledButton className='user user-button'>
<Group>
<Avatar src={profilePicture ? URL.createObjectURL(profilePicture) : undefined} />
<div style={{ flex: 1 }}>
<Text size='sm' fw={500}>
{user.first_name} {user.last_name}
</Text>
<Text c='dimmed' size='xs' style={{ textTransform: 'uppercase' }}>
{user.role}
</Text>
</div>
</Group>
</UnstyledButton>
</Menu.Target>
<Menu.Dropdown p={0}>
<Card>
<Card.Section h={140} style={{ backgroundColor: '#4481e3' }} />
<FileButton
onChange={(payload) => {
if (payload) {
setPicture(payload).then((response) => {
if (response) {
setProfilePicture(payload);
}
});
}
}}
accept='image/png,image/jpeg,image/jpg'
multiple={false}
>
{(props) => (
<Avatar
{...props}
component='button'
size={80}
radius={80}
mx={'auto'}
mt={-30}
style={{ cursor: 'pointer' }}
bg={profilePicture ? 'transparent' : 'white'}
src={profilePicture ? URL.createObjectURL(profilePicture) : undefined}
/>
)}
</FileButton>
<Text ta='center' fz='lg' fw={500} mt='sm'>
{user.first_name} {user.last_name}
</Text>
<Text ta='center' fz='sm' c='dimmed' style={{ textTransform: 'uppercase' }}>
{user.role}
</Text>
<Grid mt='xl'>
<Grid.Col span={6}>
<Link href='/profile'>
<Button fullWidth radius='md' size='xs' variant='default'>
Profile
</Button>
</Link>
</Grid.Col>
<Grid.Col span={6}>
<Button
fullWidth
radius='md'
size='xs'
variant='default'
onClick={logout}
>
Logout
</Button>
</Grid.Col>
{user.role == 'admin' && (
<Grid.Col span={12}>
<Link href='/admin'>
<Button fullWidth radius='md' size='xs' variant='default'>
Profile
Administration
</Button>
</Link>
</Grid.Col>
<Grid.Col span={6}>
<Button
fullWidth
radius='md'
size='xs'
variant='default'
onClick={async () => {
await logout();
Cookies.remove('logged_in');
setUser(undefined);
setFavorites([]);
setProfilePicture(null);
if (refreshId) {
clearInterval(refreshId);
}
}}
>
Logout
</Button>
</Grid.Col>
{user.role == 'admin' && (
<Grid.Col span={12}>
<Link href='/admin'>
<Button fullWidth radius='md' size='xs' variant='default'>
Administration
</Button>
</Link>
</Grid.Col>
)}
</Grid>
</Card>
</Menu.Dropdown>
</Menu>
) : (
<Group className='user'>
<Button onClick={() => toggle('login')}>Login</Button>
<Button variant='outline' onClick={() => toggle('register')}>
Sign up
</Button>
</Group>
)}
</>
)}
)}
</Grid>
</Card>
</Menu.Dropdown>
</Menu>
) : (
<Group className='user'>
<Button onClick={() => toggle('login')}>Login</Button>
<Button variant='outline' onClick={() => toggle('register')}>
Sign up
</Button>
</Group>
)}
</>
</div>
)
}

View File

@@ -0,0 +1,149 @@
'use client';
import { useEffect, useState } from "react";
import Header from "./Header";
import { useRecoilState } from "recoil";
import { refreshIdState, userState } from "@/state/auth";
import { login, logout, refresh, refreshLoggedIn, register } from "@/api/auth";
import { getFavorites, getPicture } from "@/api/users";
import Cookies from "js-cookie";
import { favoritesState, profilePictureState } from "@/state/user";
import { notifications } from "@mantine/notifications";
export default function Loader({ children }: { children: any }) {
const [loading, setLoading] = useState(true);
const [user, setUser] = useRecoilState(userState);
const [refreshId, setRefreshId] = useRecoilState(refreshIdState);
const [_, setFavorites] = useRecoilState(favoritesState);
const [profilePicture, setProfilePicture] = useRecoilState(profilePictureState);
useEffect(() => {
setLoading(true);
if (!user || !Cookies.get("logged_in")) {
refreshUser();
}
setLoading(false);
}, [user]);
function refreshUser() {
refresh().then((response) => {
if (response) {
setRefreshId(refreshLoggedIn());
setUser(response.user);
getFavorites().then((response) => {
if (response) {
setFavorites(response);
}
});
if (response.user.profile_picture) {
getPicture().then((response) => {
if (response) {
setProfilePicture(response as File);
}
});
}
}
});
}
async function loginUser({ email, password }: { email: string, password: string}): Promise<boolean> {
const loginResponse = await login(email, password);
if (loginResponse) {
setUser(loginResponse.user);
setRefreshId(refreshLoggedIn());
notifications.show({
title: `Welcome back ${loginResponse.user.first_name}!`,
message: `You have been logged in.`,
color: 'green',
autoClose: 2000,
loading: false
});
return true;
} else {
notifications.show({
title: `Unable to Login`,
message: `Please try again.`,
color: 'red',
autoClose: 2000,
loading: false
});
}
return false
}
async function logoutUser(): Promise<void> {
await logout();
Cookies.remove("logged_in");
setUser(undefined);
setFavorites([]);
setProfilePicture(undefined);
if (refreshId) {
clearInterval(refreshId);
setRefreshId(undefined);
}
}
async function registerUser({ firstName, lastName, email, password }: { firstName: string, lastName: string, email: string, password: string }): Promise<boolean> {
const id = notifications.show({
loading: true,
title: `Creating account`,
message: `Please wait...`,
autoClose: false,
withCloseButton: false
});
const registerResponse = await register({
first_name: firstName,
last_name: lastName,
email: email,
password: password
});
if (registerResponse) {
const loginResponse = await login(email, password);
if (loginResponse) {
setUser(loginResponse.user);
setRefreshId(refreshLoggedIn());
notifications.update({
id,
title: `Account created`,
message: `Welcome ${loginResponse.user.first_name}!`,
color: 'green',
autoClose: 2000,
loading: false
});
return true;
} else {
notifications.update({
id,
title: `Unable to Login`,
message: `Please try again.`,
color: 'red',
autoClose: 2000,
loading: false
});
}
} else {
notifications.update({
id,
title: `Unable to Register`,
message: `Please try again.`,
color: 'error',
autoClose: 2000,
loading: false
});
}
return false;
}
return (
<>
{loading ? (
<></>
) : (
<>
<Header user={user} profilePicture={profilePicture} setProfilePicture={setProfilePicture} login={loginUser} logout={logoutUser} register={registerUser} />
{children}
</>
)}
</>
)
}

View File

@@ -3,12 +3,10 @@
import { getAirports } from '@/api/airport';
import { Airport, AirportOrderField } from '@/api/airport.types';
import { getMetars } from '@/api/metar';
import { DivIcon, LatLngBounds } from 'leaflet';
import { LatLngBounds, icon } from 'leaflet';
import { useEffect, useState } from 'react';
import ReactDOMServer from 'react-dom/server';
import { Marker, TileLayer, Tooltip, useMap, useMapEvents } from 'react-leaflet';
import MetarModal from './MetarModal';
import { Avatar, MantineProvider } from '@mantine/core';
import { useRecoilState, useRecoilValue } from 'recoil';
import { coordinatesState, zoomState } from '@/state/map';
@@ -72,31 +70,20 @@ export default function MapTiles() {
}
function metarIcon(airport: Airport) {
function innerIcon({ tag, color, size = 'xs' }: { tag: string; color: string; size?: string }) {
return new DivIcon({
html: ReactDOMServer.renderToString(
<MantineProvider>
<Avatar variant='filled' color={color} radius={'xl'} size={size}>
{tag}
</Avatar>
</MantineProvider>
),
className: 'metar-marker-icon'
});
}
let iconUrl = '/icons/unkn.svg';
if (airport.latest_metar?.flight_category == 'VFR') {
return innerIcon({ tag: 'V', color: 'green' });
} else if (airport.latest_metar?.flight_category == 'MVFR') {
return innerIcon({ tag: 'M', color: 'blue' });
iconUrl = '/icons/vfr.svg';
} else if (airport.latest_metar?.flight_category == 'MVFR') {
iconUrl = '/icons/mvfr.svg';
} else if (airport.latest_metar?.flight_category == 'IFR') {
return innerIcon({ tag: 'I', color: 'red' });
iconUrl = '/icons/ifr.svg';
} else if (airport.latest_metar?.flight_category == 'LIFR') {
return innerIcon({ tag: 'L', color: 'purple' });
} else if (airport.latest_metar?.flight_category == 'UNKN') {
return innerIcon({ tag: 'U', color: 'black', size: 'xs' });
} else {
return innerIcon({tag: ' ', color: 'grey', size: 'xs' });
iconUrl = '/icons/lifr.svg';
}
return icon({
iconUrl: iconUrl,
iconSize: [20, 20]
})
}
useEffect(() => {