-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalendar-overview.tsx
More file actions
540 lines (506 loc) · 20.1 KB
/
calendar-overview.tsx
File metadata and controls
540 lines (506 loc) · 20.1 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
'use client'
import { useEffect, useRef, useState } from 'react'
import {
format,
startOfWeek,
endOfWeek,
eachDayOfInterval,
parseISO,
isSameDay,
isValid,
addWeeks,
subWeeks,
isBefore,
isAfter,
isWithinInterval,
} from 'date-fns'
import {
Calendar,
ChevronLeft,
ChevronRight,
Clock,
MapPin,
Plus,
Repeat,
Sparkles,
User,
Users,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader } from '@/components/ui/card'
import { CalendarEvent } from '@/types/types'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from './ui/dialog'
import { ScrollArea } from './ui/scroll-area'
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area'
import Link from 'next/link'
import slotifyClient from '@/hooks/fetch'
import { errorToast, toast } from '@/hooks/use-toast'
import { CreateManualEventDialog } from '@/components/calendar/create-manual-event-dialog'
import { CreateEvent } from '@/components/calendar/create-event'
export function CalendarOverview() {
const [isDayEventsDialogOpen, setIsDayEventsDialogOpen] = useState(false)
const [calendar, setCalendar] = useState<Array<CalendarEvent>>([])
const [currentWeek, setCurrentWeek] = useState(new Date())
const [selectedEvent, setSelectedEvent] = useState<CalendarEvent | null>(null)
const [isManualCreateEventOpen, setisManualCreateEventOpen] = useState(false)
const [selectedDate, setSelectedDate] = useState<Date | null>(null)
// new create event dialogue vars
const [isCreateEventOpen, setIsCreateEventOpen] = useState(false)
const weekStart = startOfWeek(currentWeek, { weekStartsOn: 1 }) // Monday
const weekEnd = endOfWeek(currentWeek, { weekStartsOn: 1 })
const days = eachDayOfInterval({ start: weekStart, end: weekEnd })
// Display rows for 24 hours.
const totalHours = 24
const handlePreviousWeek = () => setCurrentWeek(subWeeks(currentWeek, 1))
const handleNextWeek = () => setCurrentWeek(addWeeks(currentWeek, 1))
const handleToday = () => setCurrentWeek(new Date())
const viewportRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (viewportRef.current) {
const el = viewportRef.current
el.scrollTop = el.scrollHeight * 0.375
}
}, [])
useEffect(() => {
const fetchCalendar = async () => {
const startFormatted = weekStart.toISOString().slice(0, 19) + 'Z'
const endFormatted = weekEnd.toISOString().slice(0, 19) + 'Z'
try {
const calenData = await slotifyClient.GetAPICalendarMe({
queries: {
start: startFormatted,
end: endFormatted,
},
})
setCalendar(calenData)
} catch (error) {
console.error(error)
errorToast(error)
}
}
fetchCalendar()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentWeek])
const handleEventClick = (event: CalendarEvent) => {
setSelectedEvent(event)
setIsDayEventsDialogOpen(true)
}
/**
* Checks if an event overlaps the given day (even partially).
*/
function eventOverlapsDay(event: CalendarEvent, day: Date) {
if (!event.startTime || !event.endTime) return false
const start = parseISO(event.startTime)
const end = parseISO(event.endTime)
if (!isValid(start) || !isValid(end)) return false
const dayStart = new Date(day)
dayStart.setHours(0, 0, 0, 0)
const dayEnd = new Date(day)
dayEnd.setHours(23, 59, 59, 999)
return (
isWithinInterval(start, { start: dayStart, end: dayEnd }) ||
isWithinInterval(end, { start: dayStart, end: dayEnd }) ||
(isBefore(start, dayStart) && isAfter(end, dayEnd))
)
}
/**
* Return all events that overlap this specific day.
*/
function getEventsForDay(day: Date) {
return calendar.filter(event => eventOverlapsDay(event, day))
}
/**
* Convert date/time to a “fractional hour” if you want partial-hour alignment.
* For simplicity, we can just use getHours() as an integer.
*/
function getHourFraction(date: Date) {
const h = date.getHours()
const m = date.getMinutes()
return h + m / 60
}
/**
* Extract text content from an HTML string.
*/
function extractTextFromHTML(htmlString: string) {
if (!htmlString) return ''
const parser = new DOMParser()
const doc = parser.parseFromString(htmlString, 'text/html')
return (doc.body.textContent || '').trim()
}
const handleReschedule = async (
selectedEventID: string,
ownerEmail: string,
) => {
if (!selectedEventID) return
if (!ownerEmail) return
try {
await slotifyClient.PostAPIRescheduleRequestSingle({
msftMeetingID: selectedEventID,
ownerEmail: ownerEmail,
})
toast({
title: 'Reschedule sent',
description: 'Sent reschedule request to the organizer',
})
} catch (error) {
console.error(error)
errorToast(error)
}
}
return (
<div>
<Card>
<CardHeader>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<h2 className='text-lg font-semibold'>
{format(weekStart, 'MMMM yyyy')}
</h2>
<span className='text-muted-foreground'>
week {format(weekStart, 'w')}
</span>
</div>
<div className='flex items-center gap-2'>
<Button
onClick={() => {
setIsCreateEventOpen(!isCreateEventOpen)
console.log('Create super event: ', isCreateEventOpen)
}}
className='bg-focusColor hover:bg-focusColor/90'
>
<Sparkles className='h-4 w-4 mr-2' />
Create super event
</Button>
<Button
onClick={() => {
setSelectedDate(new Date())
setisManualCreateEventOpen(true)
}}
variant={'outline'}
>
<Plus className='h-4 w-4 mr-2' />
Create Event Manually
</Button>
<Button variant='outline' onClick={handleToday}>
Today
</Button>
<Button
variant='outline'
size='icon'
onClick={handlePreviousWeek}
>
<ChevronLeft className='h-4 w-4' />
</Button>
<Button variant='outline' size='icon' onClick={handleNextWeek}>
<ChevronRight className='h-4 w-4' />
</Button>
</div>
</div>
</CardHeader>
<CardContent className='p-0'>
<ScrollAreaPrimitive.Root className='h-[66vh]'>
<ScrollAreaPrimitive.Viewport
className='h-full w-full'
ref={viewportRef}
>
{/* First, render day headers in a 7-column grid */}
<div className='grid grid-cols-[auto_1fr]'>
{/* Empty top-left corner or label for "Time" */}
<div className='border-b' />
{/* Day headers (7 columns) */}
<div className='grid grid-cols-7 divide-x border-b pl-20'>
{days.map(day => (
<div key={day.toString()} className='h-14 p-2 text-center'>
<div className='text-sm font-medium'>
{format(day, 'EEE')}
</div>
<div
className={cn(
'text-sm mt-1 w-6 h-6 mx-auto flex items-center justify-center rounded-full',
isSameDay(day, new Date()) &&
'bg-focusColor text-primary-foreground',
)}
>
{format(day, 'd')}
</div>
</div>
))}
</div>
</div>
{/* Main area:
- Left column for hours (24 rows)
- Right: 7 columns for days (each 24 rows)
*/}
<div className='grid grid-cols-[auto_1fr]'>
{/* Left time column */}
<div
className='relative border-r w-20'
style={{
display: 'grid',
gridTemplateRows: `repeat(${totalHours}, 1fr)`,
}}
>
{Array.from({ length: totalHours }, (_, i) => {
// Could also display half-hour marks if desired.
const timeLabel = format(
new Date(0, 0, 0, i), // any day, just hours = i
'HH:mm',
)
return (
<div
key={i}
style={{
gridRowStart: i + 1,
gridRowEnd: i + 2,
}}
className='text-xs flex justify-center items-start h-20'
>
{timeLabel}
</div>
)
})}
</div>
{/* 7-day columns */}
<div className='grid grid-cols-7 divide-x'>
{days.map(day => {
const eventsForDay = getEventsForDay(day)
return (
<div
key={day.toString()}
className='relative'
style={{
// 24 rows for the day
display: 'grid',
gridTemplateRows: `repeat(${totalHours}, 1fr)`,
}}
>
{/* Optional horizontal lines for each hour */}
{Array.from({ length: totalHours }, (_, i) => (
<div
key={i}
className='absolute left-0 right-0 border-t border-dashed border-muted-foreground opacity-30'
style={{
top: `${(i / totalHours) * 100}%`,
zIndex: 0, // Ensure lines stay in the background
}}
/>
))}
{/* Render each event once, spanning rows */}
{eventsForDay.map(event => {
if (!event.startTime || !event.endTime) return null
const eventStart = parseISO(event.startTime)
const eventEnd = parseISO(event.endTime)
if (!isValid(eventStart) || !isValid(eventEnd))
return null
// Clamp the event to the day
const dayStart = new Date(day)
dayStart.setHours(0, 0, 0, 0)
const dayEnd = new Date(day)
dayEnd.setHours(23, 59, 59, 999)
const actualStart = isBefore(eventStart, dayStart)
? dayStart
: eventStart
const actualEnd = isAfter(eventEnd, dayEnd)
? dayEnd
: eventEnd
// Get fractional hours
const startHour = getHourFraction(actualStart)
const endHour = getHourFraction(actualEnd)
// Calculate position
const eventTop = (startHour / totalHours) * 100
const eventHeight =
((endHour - startHour) / totalHours) * 100
return (
<div
key={event.id}
onClick={() => handleEventClick(event)}
className='absolute p-2 rounded-md bg-accent hover:bg-gray-200 text-accent-foreground cursor-pointer overflow-hidden w-full hover:text-focusColor font-medium duration-300 hover:font-bold hover:scale-105 border'
style={{
top: `${eventTop}%`,
height: `${eventHeight}%`,
zIndex: 10,
}}
>
<div className='text-sm truncate'>
{event.subject
? event.subject.charAt(0).toUpperCase() +
event.subject.slice(1)
: '(No Name)'}
</div>
{event.body ? (
<div className='text-xs truncate overflow-hidden text-gray-500 font-normal'>
{extractTextFromHTML(
event.body?.toString() || '',
)}
</div>
) : null}
{event.locations?.length ? (
<div className='flex flex-row items-center'>
<MapPin className='mr-2 h-4 w-4 text-focusColor' />
<div className='text-xs truncate opacity-90 overflow-hidden text-black font-normal'>
{event.locations?.[0]?.name}
</div>
</div>
) : null}
</div>
)
})}
</div>
)
})}
</div>
</div>
</ScrollAreaPrimitive.Viewport>
<ScrollAreaPrimitive.Scrollbar
className='flex touch-none select-none bg-gray-100 p-0.5 transition-colors duration-[160ms] ease-out hover:bg-gray-200 data-[orientation=horizontal]:h-2.5 data-[orientation=vertical]:w-2.5 data-[orientation=horizontal]:flex-col'
orientation='vertical'
>
<ScrollAreaPrimitive.Thumb className='relative flex-1 rounded-[10px] bg-gray-500 before:absolute before:left-1/2 before:top-1/2 before:size-full before:min-h-11 before:min-w-11 before:-translate-x-1/2 before:-translate-y-1/2' />
</ScrollAreaPrimitive.Scrollbar>
<ScrollAreaPrimitive.Corner className='bg-focusColor' />
</ScrollAreaPrimitive.Root>
</CardContent>
</Card>
<CreateManualEventDialog
open={isManualCreateEventOpen}
onOpenChangeAction={setisManualCreateEventOpen}
selectedDate={selectedDate}
/>
<CreateEvent
open={isCreateEventOpen}
onOpenChangeAction={setIsCreateEventOpen}
closeCreateEventDialogOpen={() => setIsCreateEventOpen(false)}
initialTitle={''}
initialDuration={'1hr'}
initialParticipants={[]}
initialSelectedRange={null}
inputsDisabled={false}
/>
<Dialog
open={isDayEventsDialogOpen}
onOpenChange={setIsDayEventsDialogOpen}
>
<DialogContent className='max-w-3xl min-h-[400px]'>
{selectedEvent && (
<div className='flex flex-col justify-between'>
<div className='flex flex-col'>
<DialogHeader className='mb-5'>
<DialogTitle className='mb-4'>
{selectedEvent.subject
? selectedEvent.subject.charAt(0).toUpperCase() +
selectedEvent.subject.slice(1)
: '(No Name)'}
</DialogTitle>
{selectedEvent.body && (
<ScrollArea className='h-[100px] pb-3 border-b'>
<DialogDescription className='pb-4 whitespace-pre-wrap break-words'>
{extractTextFromHTML(selectedEvent.body)}
</DialogDescription>
</ScrollArea>
)}
</DialogHeader>
<div className='space-y-2 pb-5 mb-10 border-b'>
<div className='flex items-center text-sm'>
<Clock className='mr-2 h-4 w-4 text-focusColor' />
{selectedEvent.startTime && selectedEvent.endTime && (
<>
{format(parseISO(selectedEvent.startTime), 'HH:mm')} -{' '}
{format(parseISO(selectedEvent.endTime), 'HH:mm')}
</>
)}
</div>
{selectedEvent.locations?.map(loc => (
<div key={loc.id} className='flex items-center text-sm'>
<MapPin className='mr-2 h-4 w-4 text-focusColor' />
{loc.name}
</div>
))}
{selectedEvent.organizer && (
<div className='flex items-center text-sm'>
<User className='mr-2 h-4 w-4 text-focusColor' />
Organizer: {selectedEvent.organizer}
</div>
)}
{selectedEvent.attendees?.length ? (
<div className='flex items-start text-sm'>
<Users className='mr-2 h-4 w-4 mt-1 text-focusColor' />
<div>
<div>Attendees:</div>
<ul className='list-disc list-inside pl-4'>
{selectedEvent.attendees.map((attendee, index) => (
<li key={index}>
{attendee.email || attendee.attendeeType} (
{attendee.responseStatus})
</li>
))}
</ul>
</div>
</div>
) : null}
</div>
</div>
<div className='flex flex-row justify-between mb-5 pl-20 pr-20'>
{selectedEvent.joinURL && (
<Button
asChild
className='bg-focusColor hover:bg-focusColor/90'
>
<Link
href={selectedEvent.joinURL}
target='_blank'
rel='noopener noreferrer'
>
<Calendar className='mr-2 h-4 w-4' />
Join Meeting
</Link>
</Button>
)}
{selectedEvent.webLink && (
<Button
asChild
className='bg-focusColor hover:bg-focusColor/90'
>
<Link
href={selectedEvent.webLink}
target='_blank'
rel='noopener noreferrer'
>
<Calendar className='mr-2 h-4 w-4' />
View In Outlook
</Link>
</Button>
)}
<Button
variant='destructive'
onClick={() => {
console.log(
'Reschedule event: ',
selectedEvent.iCalUId!.toString(),
)
handleReschedule(
selectedEvent.iCalUId!.toString(),
selectedEvent.organizer!.toString(),
)
setIsDayEventsDialogOpen(false)
}}
>
<div className='flex justify-center items-center'>
<Repeat className='mr-2 h-4 w-4' />
Reschedule
</div>
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
)
}