Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add calendar to mentor attendance view #475

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
337 changes: 230 additions & 107 deletions csm_web/frontend/src/components/section/MentorSectionAttendance.tsx

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion csm_web/frontend/src/components/section/Section.tsx
Original file line number Diff line number Diff line change
@@ -64,7 +64,7 @@ export function SectionSidebar({ links }: SectionSidebarProps) {
return (
<nav id="section-detail-sidebar">
{links.map(([label, href]) => (
<NavLink end to={href} key={href}>
<NavLink end to={`${href}`} key={href}>
{label}
</NavLink>
))}
40 changes: 32 additions & 8 deletions csm_web/frontend/src/components/section/StudentSection.tsx
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ import {
useStudentAttendances,
useStudentSubmitWordOfTheDayMutation
} from "../../utils/queries/sections";
import { Mentor, Override, Role, Spacetime } from "../../utils/types";
import { AttendancePresence, Mentor, Override, Role, Spacetime } from "../../utils/types";
import LoadingSpinner from "../LoadingSpinner";
import Modal from "../Modal";
import { ATTENDANCE_LABELS, InfoCard, SectionDetail, SectionSpacetime } from "./Section";
@@ -184,12 +184,32 @@ function StudentSectionAttendance({ associatedProfileId, id }: StudentSectionAtt

useEffect(() => {
if (attendancesLoaded) {
const firstAttendance = [...attendances]
// only allow choosing from dates with blank attendances
.filter(attendance => attendance.presence === "")
// sort and get the first attendance
.sort((a, b) => dateSortISO(a.date, b.date))[0];
setSelectedAttendanceId(firstAttendance?.id ?? -1);
const now = DateTime.now().setZone(DEFAULT_TIMEZONE);
const sortedAttendances = attendances
// only consider dates that have no attendance yet
.filter(attendance => attendance.presence === AttendancePresence.EMPTY)
.sort((a, b) => dateSortISO(a.date, b.date));

const pastAttendances = sortedAttendances.filter(
attendance => DateTime.fromISO(attendance.date, { zone: DEFAULT_TIMEZONE }) <= now.endOf("day")
);
const futureAttendances = sortedAttendances.filter(
attendance => DateTime.fromISO(attendance.date, { zone: DEFAULT_TIMEZONE }) > now.endOf("day")
);

const mostRecentPastAttendanceId = pastAttendances[0]?.id ?? null;
const mostRecentFutureAttendanceId = futureAttendances[futureAttendances.length - 1]?.id ?? null;

if (mostRecentPastAttendanceId !== null) {
// reassign to the most recent attendance in the past
setSelectedAttendanceId(mostRecentPastAttendanceId);
} else if (mostRecentFutureAttendanceId !== null) {
// if no empty attendances in the past, reassign to the most recent attendance in the future
setSelectedAttendanceId(mostRecentFutureAttendanceId);
} else {
// worst-case, we assigng to -1 to indicate that there is no possible attendance left to choose from
setSelectedAttendanceId(-1);
}
}
}, [attendancesLoaded]);

@@ -258,7 +278,7 @@ function StudentSectionAttendance({ associatedProfileId, id }: StudentSectionAtt
<div className="word-of-the-day-action-container">
<div className="word-of-the-day-input-container">
<select
value={selectedAttendanceId}
value={selectedAttendanceId === -1 ? undefined : selectedAttendanceId.toString()}
className="form-select"
name="word-of-the-day-date"
onChange={handleSelectedAttendanceIdChange}
@@ -274,6 +294,10 @@ function StudentSectionAttendance({ associatedProfileId, id }: StudentSectionAtt
{formatDateLocaleShort(occurrence.date)}
</option>
))}
{selectedAttendanceId === -1 && (
// if no current attendance, add an empty option to make this visible in the UI
<option value="" disabled></option>
)}
</select>
<input
className="form-input"
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
import { DateTime, Info } from "luxon";
import React, { useEffect, useState } from "react";

import { DEFAULT_TIMEZONE } from "../../../utils/datetime";

import LeftArrow from "../../../../static/frontend/img/angle-left-solid.svg";
import RightArrow from "../../../../static/frontend/img/angle-right-solid.svg";

import "../../../css/calendar-month.scss";

interface CalendarMonthProps {
// List of dates that have occurrences, in ISO format
occurrenceDates: string[];
// Mapping between occurrence dates and text to display for that occurrence.
// Keys should match items in `occurrenceDates` exactly; some elements can be omitted.
occurrenceTextMap: Map<string, string>;
// Mapping between occurrence dates and a react component (usually an icon) to display
// in the top-right corner of the container for that occurrence.
// Keys should match items in `occurrenceDates` exactly; some elements can be omitted.
occurrenceIconMap: Map<string, React.ReactNode>;
// currently selected occurrence in the calendar
selectedOccurrence?: string;
// click handler; the date in ISO format is passed in as an argument
onClickDate: (day: string) => void;
}

export const CalendarMonth = ({
occurrenceDates,
occurrenceTextMap,
occurrenceIconMap,
selectedOccurrence,
onClickDate
}: CalendarMonthProps) => {
/**
* Current ISO month number.
*/
const [curMonth, setCurMonth] = useState<number>(DateTime.now().month);
/**
* Current year.
*/
const [curYear, setCurYear] = useState<number>(DateTime.now().year);

useEffect(() => {
if (selectedOccurrence != null) {
// upon change of the selected occurence, make sure the calendar also matches
const selectedDateTime = DateTime.fromISO(selectedOccurrence, { zone: DEFAULT_TIMEZONE });
if (curMonth !== selectedDateTime.month) {
setCurMonth(selectedDateTime.month);
}
if (curYear != selectedDateTime.year) {
setCurYear(selectedDateTime.year);
}
}
}, [selectedOccurrence]);

const modifyMonth = (diff: number) => {
const curDate = DateTime.fromObject({ year: curYear, month: curMonth });
const nextDate = curDate.plus({ months: diff });

setCurMonth(nextDate.month);
setCurYear(nextDate.year);
};

/**
* Navigate to the current month.
*/
const handleToday = () => {
const today = DateTime.now();
setCurMonth(today.month);
setCurYear(today.year);
};

/**
* Compute the weekday index from an ISO weekday number (1-7).
* This accounts for any shifting that we need to perform to display days in the calendar.
*/
const weekdayIndexFromISO = (weekday: number) => {
return weekday % 7;
};

const weekdayISOFromIndex = (idx: number) => {
return ((idx + 6) % 7) + 1;
};

const curMonthFirstDay = DateTime.fromObject({ year: curYear, month: curMonth, day: 1 });
const nextMonthFirstDay = curMonthFirstDay.plus({ months: 1 });

const monthGrid: React.ReactNode[][] = [];
// push empty days until the first day of the month
const firstWeekPadding = [...Array(weekdayIndexFromISO(curMonthFirstDay.weekday))].map((_, idx) => (
<CalendarMonthDay key={-idx} year={-1} month={-1} day={-1} isoDate="" hasOccurrence={false} selected={false} />
));
monthGrid.push(firstWeekPadding);

for (let date = curMonthFirstDay; date < nextMonthFirstDay; date = date.plus({ days: 1 })) {
// get last week in month grid
const curWeek = monthGrid[monthGrid.length - 1];

const curDay = (
<CalendarMonthDay
key={date.day}
year={date.year}
month={date.month}
day={date.day}
isoDate={date.toISODate() ?? ""}
hasOccurrence={occurrenceDates.includes(date.toISODate()!)}
text={occurrenceTextMap.get(date.toISODate()!)}
icon={occurrenceIconMap.get(date.toISODate()!)}
selected={date.toISODate() === selectedOccurrence}
onClickDate={onClickDate}
/>
);

if (curWeek.length < 7) {
curWeek.push(curDay);
} else {
monthGrid.push([curDay]);
}
}

return (
<div className="calendar-month-container">
<div className="calendar-month-header">
<div className="calendar-month-header-left">
<span className="calendar-month-title">
{Info.months()[curMonth - 1]} {curYear}
</span>
</div>
<div className="calendar-month-header-right">
<button className="calendar-month-today-btn" onClick={handleToday}>
Today
</button>
<LeftArrow className="icon calendar-month-nav-icon" onClick={() => modifyMonth(-1)} />
<RightArrow className="icon calendar-month-nav-icon" onClick={() => modifyMonth(1)} />
</div>
</div>
<div className="calendar-month-weekday-headers">
{[...Array(7)].map((_, idx) => (
<div key={idx} className="calendar-month-weekday-header">
{Info.weekdays("short")[weekdayISOFromIndex(idx) - 1]}
</div>
))}
</div>
<div className="calendar-month-grid">
{monthGrid.map((monthGridWeek, idx) => (
<div key={idx} className="calendar-month-week">
{monthGridWeek}
</div>
))}
</div>
</div>
);
};

interface CalendarMonthDayProps {
year: number;
month: number;
day: number;
isoDate: string;
// Text to be displayed in the calendar day
text?: string;
// Icon to be displayed in the calendar day
icon?: React.ReactNode;
hasOccurrence: boolean;
selected: boolean;
onClickDate?: (date: string) => void;
}

/**
* Calendar month day component.
*
* If `day` is -1, displays an empty box.
*/
export const CalendarMonthDay = ({
year,
month,
day,
isoDate,
text,
icon,
hasOccurrence,
selected,
onClickDate
}: CalendarMonthDayProps) => {
const today = DateTime.now();
const curDate = DateTime.fromObject({ year, month, day });
const isTransparent = day === -1;
const classes = ["calendar-month-day"];
if (isTransparent) {
// transparent higher priority than disabled
classes.push("transparent");
} else if (selected) {
classes.push("selected");
} else if (hasOccurrence) {
classes.push("with-occurrence");
}

if (year === today.year && month === today.month && day == today.day) {
classes.push("today");
} else if (curDate < today) {
classes.push("past");
}

const handleClick = () => {
if (onClickDate != null && !selected && hasOccurrence) {
onClickDate(isoDate);
}
};

return (
<div className={classes.join(" ")} onClick={handleClick}>
{isTransparent ? (
<span></span>
) : (
<>
<span className="calendar-month-day-number">{day}</span>
<span className="calendar-month-day-icon">{icon}</span>
<span className="calendar-month-day-text">{text}</span>
</>
)}
</div>
);
};
6 changes: 6 additions & 0 deletions csm_web/frontend/src/css/base/_variables.scss
Original file line number Diff line number Diff line change
@@ -43,6 +43,12 @@ $calendar-hover-event: #d2ffd2;
$calendar-hover-shadow: #ccc;
$calendar-select-event: #90ee90;

/// month calendar colors
$calendar-day-occurrence: #d2ffd2;
$calendar-day-occurrence-hover: #bce6bc;
$calendar-day-selected: #9bdaff;
$calendar-day-today: #444;

/// Fonts
$default-font: "Montserrat", sans-serif;

Loading
Loading