Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 27 additions & 22 deletions src/App/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import AuthProvider from './providers/AuthProvider';
import CommandProvider from './providers/CommandProvider';
import DateProvider from './providers/DateProvider';
import EnumsProvider from './providers/EnumsProvider';
import GoogleCalendarProvider from './providers/GoogleCalendarProvider';
import LocalStorageProvider from './providers/LocalStorageProvider';
import NavbarProvider from './providers/NavbarProvider';
import SizeProvider from './providers/SizeProvider';
Expand Down Expand Up @@ -83,28 +84,32 @@ function App() {
<PwaPrompt />
<UrqlProvider value={gqlClient}>
<QueryClientProvider client={queryClient}>
<AuthProvider>
<DateProvider>
<NavbarProvider>
<SizeProvider>
<LocalStorageProvider>
<ThemeProvider>
<EnumsProvider>
<CommandProvider>
<RouteContext.Provider value={wrappedRoutes}>
<RouterProvider
router={router}
fallbackElement={fallbackElement}
/>
</RouteContext.Provider>
</CommandProvider>
</EnumsProvider>
</ThemeProvider>
</LocalStorageProvider>
</SizeProvider>
</NavbarProvider>
</DateProvider>
</AuthProvider>
<GoogleCalendarProvider>
<AuthProvider>
<DateProvider>
<NavbarProvider>
<SizeProvider>
<LocalStorageProvider>
<ThemeProvider>
<EnumsProvider>
<CommandProvider>
<RouteContext.Provider
value={wrappedRoutes}
>
<RouterProvider
router={router}
fallbackElement={fallbackElement}
/>
</RouteContext.Provider>
</CommandProvider>
</EnumsProvider>
</ThemeProvider>
</LocalStorageProvider>
</SizeProvider>
</NavbarProvider>
</DateProvider>
</AuthProvider>
</GoogleCalendarProvider>
</QueryClientProvider>
</UrqlProvider>
</>
Expand Down
171 changes: 171 additions & 0 deletions src/App/providers/GoogleCalendarProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import {
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import {
googleLogout,
useGoogleLogin,
} from '@react-oauth/google';
import { useQueryClient } from '@tanstack/react-query';

import GoogleCalendarContext, {
type GoogleCalendarContextValue,
type GoogleCalendarEvent,
} from '#contexts/googleCalendar';

const STORAGE_KEY = 'timur-google-calendar-token';
const CALENDAR_SCOPE = 'https://www.googleapis.com/auth/calendar.readonly';
const CALENDAR_API_BASE = 'https://www.googleapis.com/calendar/v3';
const GCAL_QUERY_KEY = 'googleCalendarEvents';

interface StoredToken {
accessToken: string;
expiresAt: number;
}

function getStoredToken(): StoredToken | null {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return null;
return JSON.parse(raw) as StoredToken;
} catch {
return null;
}
}

function isTokenValid(token: StoredToken | null): token is StoredToken {
if (!token) return false;
return Date.now() < token.expiresAt - 60_000;
}

interface Props {
children: React.ReactNode;
}

function GoogleCalendarProvider(props: Props) {
const { children } = props;
const queryClient = useQueryClient();
const clientId = import.meta.env.APP_GOOGLE_OAUTH_CLIENT_ID as string | undefined;

const [storedToken, setStoredToken] = useState<StoredToken | null>(() => getStoredToken());

const isConnected = isTokenValid(storedToken);

useEffect(() => {
if (!storedToken) return undefined;
const msUntilExpiry = storedToken.expiresAt - Date.now();
if (msUntilExpiry <= 0) {
setStoredToken(null);
return undefined;
}
const timeout = window.setTimeout(() => setStoredToken(null), msUntilExpiry);
return () => window.clearTimeout(timeout);
}, [storedToken]);

const saveToken = useCallback((accessToken: string, expiresIn: number) => {
const token: StoredToken = {
accessToken,
expiresAt: Date.now() + expiresIn * 1000,
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(token));
setStoredToken(token);
}, []);

const clearToken = useCallback(() => {
localStorage.removeItem(STORAGE_KEY);
setStoredToken(null);
}, []);

const login = useGoogleLogin({
scope: CALENDAR_SCOPE,
onSuccess: (response) => {
saveToken(response.access_token, response.expires_in);
},
onError: () => {
clearToken();
},
});

const connect = useCallback(() => {
login();
}, [login]);

const disconnect = useCallback(() => {
googleLogout();
clearToken();
queryClient.removeQueries({ queryKey: [GCAL_QUERY_KEY] });
}, [clearToken, queryClient]);

const fetchEventsForDateRange = useCallback(async (
startDate: string,
endDate: string,
options?: { fullDayOnly?: boolean },
): Promise<GoogleCalendarEvent[]> => {
if (!isConnected || !storedToken) return [];

const rangeStart = new Date(startDate);
rangeStart.setHours(0, 0, 0, 0);

const rangeEnd = new Date(endDate);
rangeEnd.setHours(23, 59, 59, 999);

const params = new URLSearchParams({
timeMin: rangeStart.toISOString(),
timeMax: rangeEnd.toISOString(),
singleEvents: 'true',
orderBy: 'startTime',
});

const response = await fetch(
`${CALENDAR_API_BASE}/calendars/primary/events?${params}`,
{ headers: { Authorization: `Bearer ${storedToken.accessToken}` } },
);

if (!response.ok) {
if (response.status === 401) clearToken();
return [];
}

const data = await response.json() as { items?: GoogleCalendarEvent[] };
const items = data.items ?? [];
if (options?.fullDayOnly) {
return items.filter((event) => !!event.start.date && !event.start.dateTime);
}
return items;
}, [isConnected, storedToken, clearToken]);

const fetchEvents = useCallback(
(date: string, options?: { fullDayOnly?: boolean }) => (
fetchEventsForDateRange(date, date, options)
),
[fetchEventsForDateRange],
);

const value = useMemo<GoogleCalendarContextValue>(() => ({
isAvailable: !!clientId,
isConnected,
expiresAt: storedToken?.expiresAt,
connect,
disconnect,
fetchEvents,
fetchEventsForDateRange,
}), [
clientId,
isConnected,
storedToken?.expiresAt,
connect,
disconnect,
fetchEvents,
fetchEventsForDateRange,
]);

return (
<GoogleCalendarContext.Provider value={value}>
{children}
</GoogleCalendarContext.Provider>
);
}

export default GoogleCalendarProvider;
45 changes: 45 additions & 0 deletions src/components/AdminEditLink/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { useContext } from 'react';

import UserContext from '#contexts/user';

import styles from './styles.module.css';

type AdminEntity = 'project' | 'deadline' | 'event' | 'contract';

const entityAdminPath: Record<AdminEntity, string> = {
project: 'project/project',
deadline: 'project/deadline',
event: 'common/event',
contract: 'track/contract',
};

interface Props {
entity: AdminEntity;
id: string;
children: React.ReactNode;
}

function AdminEditLink(props: Props) {
const { entity, id, children } = props;
const { userAuth } = useContext(UserContext);

if (!userAuth?.isStaff) {
return children;
}

const href = `${import.meta.env.APP_GRAPHQL_DOMAIN}/admin/${entityAdminPath[entity]}/${id}/change/`;

return (
<a
className={styles.adminEditLink}
href={href}
target="_blank"
rel="noopener noreferrer"
title={`Edit ${entity} in admin`}
>
{children}
</a>
);
}

export default AdminEditLink;
9 changes: 9 additions & 0 deletions src/components/AdminEditLink/styles.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.admin-edit-link {
cursor: pointer;
text-decoration: none;
color: inherit;

&:hover {
text-decoration: underline;
}
}
16 changes: 12 additions & 4 deletions src/components/UpcomingEventsList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { compareNumber } from '@togglecorp/fujs';
import { type EventTypeEnum } from '#generated/types/graphql';
import { type GeneralEventType } from '#utils/types';

import AdminEditLink from '../AdminEditLink';
import GeneralEventOutput from '../GeneralEvent';

import styles from './styles.module.css';
Expand Down Expand Up @@ -57,6 +58,7 @@ function UpcomingEventsList(props: Props) {
() => [
...(deadlines?.map((deadline) => ({
key: `DEADLINE-${deadline.id}`,
id: deadline.id,
type: 'DEADLINE' as const,
typeDisplay: 'Deadline',
icon: deadline.isExternal ? <FcHighPriority /> : <FcMediumPriority />,
Expand All @@ -65,6 +67,7 @@ function UpcomingEventsList(props: Props) {
})) ?? []),
...(events?.map((event) => ({
key: `${event.type}-${event.id}`,
id: event.id,
type: event.type,
typeDisplay: event.typeDisplay,
icon: eventIcons[event.type],
Expand All @@ -83,10 +86,15 @@ function UpcomingEventsList(props: Props) {

return (
<Fragment key={item.key}>
<GeneralEventOutput
generalEvent={item}
hideDaysRemaining={hideDaysRemaining}
/>
<AdminEditLink
entity={item.type === 'DEADLINE' ? 'deadline' : 'event'}
id={item.id}
>
<GeneralEventOutput
generalEvent={item}
hideDaysRemaining={hideDaysRemaining}
/>
</AdminEditLink>
{item.remainingDays < 0
&& nextItem
&& nextItem.remainingDays >= 0
Expand Down
55 changes: 55 additions & 0 deletions src/contexts/googleCalendar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { createContext } from 'react';

export interface GoogleCalendarEvent {
id: string;
summary?: string;
description?: string;
location?: string;
status: string;
htmlLink?: string;
start: {
dateTime?: string;
date?: string;
timeZone?: string;
};
end: {
dateTime?: string;
date?: string;
timeZone?: string;
};
}

export interface GoogleCalendarContextValue {
isAvailable: boolean;
isConnected: boolean;
expiresAt: number | undefined;
connect: () => void;
disconnect: () => void;
fetchEvents: (
date: string,
options?: { fullDayOnly?: boolean },
) => Promise<GoogleCalendarEvent[]>;
fetchEventsForDateRange: (
startDate: string,
endDate: string,
options?: { fullDayOnly?: boolean },
) => Promise<GoogleCalendarEvent[]>;
}

const GoogleCalendarContext = createContext<GoogleCalendarContextValue>({
isAvailable: false,
isConnected: false,
expiresAt: undefined,
connect: () => {
// eslint-disable-next-line no-console
console.warn('GoogleCalendarContext::connect called without provider');
},
disconnect: () => {
// eslint-disable-next-line no-console
console.warn('GoogleCalendarContext::disconnect called without provider');
},
fetchEvents: () => Promise.resolve([]),
fetchEventsForDateRange: () => Promise.resolve([]),
});

export default GoogleCalendarContext;
Loading
Loading