From a38615241734a2308c3885bc95b580d0a447865b Mon Sep 17 00:00:00 2001 From: Adrian Edwards <17362949+MoralCode@users.noreply.github.com> Date: Sat, 26 Dec 2020 08:24:05 -0800 Subject: [PATCH 1/3] rearrange dependencies from the manual merge of unit testing branch --- package.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index bdb9a11..961d108 100644 --- a/package.json +++ b/package.json @@ -60,6 +60,7 @@ "devDependencies": { "@babel/helper-builder-react-jsx": "^7.10.4", "@babel/helper-regex": "^7.10.5", + "@types/fetch-mock": "^7.3.2", "@types/jest": "^24.0.18", "@types/jsonapi-serializer": "^3.6.2", "@types/lodash.clonedeep": "^4.5.6", @@ -68,21 +69,20 @@ "@types/react": "^16.9.2", "@types/react-dom": "^16.9.0", "@types/react-redux": "^7.1.0", + "@types/react-test-renderer": "^16.9.0", "@types/redux-first-routing": "^0.3.0", "@types/redux-logger": "^3.0.7", - "@types/fetch-mock": "^7.3.2", - "@types/react-test-renderer": "^16.9.0", "@types/redux-mock-store": "^1.0.1", + "fetch-mock": "^8.1.0", "lodash.find": "^4.6.0", + "mockdate": "^2.0.5", + "node-fetch": "^2.6.0", "prettier": "1.18.2", + "react-test-renderer": "16.8.6", "redux-logger": "^3.0.6", + "redux-mock-store": "^1.5.4", "tslint": "^5.18.0", "tslint-config-prettier": "^1.18.0", - "tslint-react": "^4.0.0", - "fetch-mock": "^8.1.0", - "mockdate": "^2.0.5", - "node-fetch": "^2.6.0", - "react-test-renderer": "16.8.6", - "redux-mock-store": "^1.5.4" + "tslint-react": "^4.0.0" } } From 7500dba1f5d831c0ca74d25912f3e070c8951b05 Mon Sep 17 00:00:00 2001 From: Adrian Edwards <17362949+MoralCode@users.noreply.github.com> Date: Sat, 26 Dec 2020 08:24:58 -0800 Subject: [PATCH 2/3] install luxon --- package.json | 2 ++ yarn.lock | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/package.json b/package.json index 961d108..839ba8c 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "date-fns": "^1.30.1", "jsonapi-serializer": "^3.6.6", "lodash.clonedeep": "^4.5.0", + "luxon": "^1.25.0", "react": "^16.8.6", "react-dom": "^16.8.6", "react-redux": "^7.1.0", @@ -65,6 +66,7 @@ "@types/jsonapi-serializer": "^3.6.2", "@types/lodash.clonedeep": "^4.5.6", "@types/lodash.find": "^4.6.6", + "@types/luxon": "^1.25.0", "@types/node": "^12.7.3", "@types/react": "^16.9.2", "@types/react-dom": "^16.9.0", diff --git a/yarn.lock b/yarn.lock index aaf1a12..ab4b522 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1607,6 +1607,11 @@ resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.165.tgz#74d55d947452e2de0742bad65270433b63a8c30f" integrity sha512-tjSSOTHhI5mCHTy/OOXYIhi2Wt1qcbHmuXD1Ha7q70CgI/I71afO4XtLb/cVexki1oVYchpul/TOuu3Arcdxrg== +"@types/luxon@^1.25.0": + version "1.25.0" + resolved "https://registry.yarnpkg.com/@types/luxon/-/luxon-1.25.0.tgz#3d6fe591fac874f48dd225cb5660b2b785a21a05" + integrity sha512-iIJp2CP6C32gVqI08HIYnzqj55tlLnodIBMCcMf28q9ckqMfMzocCmIzd9JWI/ALLPMUiTkCu1JGv3FFtu6t3g== + "@types/minimatch@*": version "3.0.3" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" @@ -6791,6 +6796,11 @@ lru-cache@^6.0.0: dependencies: yallist "^4.0.0" +luxon@^1.25.0: + version "1.25.0" + resolved "https://registry.yarnpkg.com/luxon/-/luxon-1.25.0.tgz#d86219e90bc0102c0eb299d65b2f5e95efe1fe72" + integrity sha512-hEgLurSH8kQRjY6i4YLey+mcKVAWXbDNlZRmM6AgWDJ1cY3atl8Ztf5wEY7VBReFbmGnwQPz7KYJblL8B2k0jQ== + make-dir@^2.0.0, make-dir@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-2.1.0.tgz#5f0310e18b8be898cc07009295a30ae41e91e6f5" From 9df2a40997f04c836decc6a89786588c4d251d2c Mon Sep 17 00:00:00 2001 From: Adrian Edwards <17362949+MoralCode@users.noreply.github.com> Date: Sat, 26 Dec 2020 10:51:49 -0800 Subject: [PATCH 3/3] replace uses of Date and Time with Luxon --- src/@types/bellschedule.test.ts | 1 - src/@types/bellschedule.ts | 27 +++++++------- src/@types/classperiod.ts | 24 ++++++------- src/@types/school.ts | 25 +++++++------ src/components/Calendar/Calendar.tsx | 54 ++++++++++++---------------- src/pages/App.tsx | 15 ++++---- src/services/classclock.ts | 8 +++-- src/store/schools/actions.ts | 3 +- src/utils/helpers.test.ts | 1 - src/utils/helpers.tsx | 41 ++++++++++----------- src/utils/testconstants.ts | 47 ++++++++++++------------ 11 files changed, 118 insertions(+), 128 deletions(-) diff --git a/src/@types/bellschedule.test.ts b/src/@types/bellschedule.test.ts index 1d6c460..1cc43b4 100644 --- a/src/@types/bellschedule.test.ts +++ b/src/@types/bellschedule.test.ts @@ -1,5 +1,4 @@ import BellSchedule from "./bellschedule"; -import Time from "./time"; import { bellSchedule as schedule, bellScheduleJSON, classPeriod, bellScheduleEndpoint, bellScheduleName, bellScheduleDisplayName, bellScheduleId, startTime, beforeClass, duringClass, endTime, afterClass, bellScheduleClasses } from "../utils/testconstants"; describe("BellSchedule", () => { diff --git a/src/@types/bellschedule.ts b/src/@types/bellschedule.ts index aec748e..5f3c412 100644 --- a/src/@types/bellschedule.ts +++ b/src/@types/bellschedule.ts @@ -1,8 +1,7 @@ import ClassPeriod from "./classperiod"; -import Time from "./time"; +import { DateTime } from "luxon"; import { TimeComparisons } from "../utils/enums"; import { getValueIfKeyInList, sortClassesByStartTime } from "../utils/helpers"; -import { parse, isSameDay } from "date-fns"; export default class BellSchedule { public static fromJson(json: any) { @@ -10,7 +9,7 @@ export default class BellSchedule { getValueIfKeyInList(["id", "identifier"], json), getValueIfKeyInList(["name", "full_name", "fullName"], json), getValueIfKeyInList(["endpoint"], json), - getValueIfKeyInList(["dates"], json).map((date: string) => parse(date)), + getValueIfKeyInList(["dates"], json).map((date: string) => DateTime.fromISO(date)), getValueIfKeyInList(["classes", "meeting_times"], json).map( (meetingTime: any) => ClassPeriod.fromJson(meetingTime) ), @@ -23,18 +22,18 @@ export default class BellSchedule { private name: string; private endpoint: string; private displayName?: string; - private dates: Date[]; + private dates: DateTime[]; private classes: ClassPeriod[]; - private lastUpdatedDate: Date; + private lastUpdatedDate: DateTime; private color?: string; constructor( id: string, name: string, endpoint: string, - dates: Date[], + dates: DateTime[], classes: ClassPeriod[], - lastUpdatedDate: Date, + lastUpdatedDate: DateTime, displayName?: string ) { this.id = id; @@ -84,20 +83,20 @@ export default class BellSchedule { * inaccuracies due to incorrect milliseconds .etc. * */ - public getDate(date: Date) { + public getDate(date: DateTime) { for (const scheduleDate of this.getDates()) { - if (isSameDay(scheduleDate, date)) { + if (scheduleDate.hasSame(date, "day")) { return scheduleDate; } } return; } - public addDate(date: Date) { + public addDate(date: DateTime) { this.dates.push(date); } - public removeDate(date: Date) { + public removeDate(date: DateTime) { const actualDate = this.getDate(date); if (!actualDate){ return false; @@ -110,7 +109,7 @@ export default class BellSchedule { return this.classes; } - public getClassPeriodForTime(time: Time) { + public getClassPeriodForTime(time: DateTime) { for (const classPeriod of sortClassesByStartTime(this.classes)) { if (classPeriod.stateForTime(time) === TimeComparisons.IS_DURING_OR_EXACTLY) { return classPeriod; @@ -148,7 +147,7 @@ export default class BellSchedule { return this.lastUpdatedDate; } - public hasChangedSince(date: Date) { - return date.getTime() < this.lastUpdatedDate.getTime(); + public hasChangedSince(date: DateTime) { + return date.toMillis() < this.lastUpdatedDate.toMillis(); } } diff --git a/src/@types/classperiod.ts b/src/@types/classperiod.ts index 0989be5..f2afc7e 100644 --- a/src/@types/classperiod.ts +++ b/src/@types/classperiod.ts @@ -1,4 +1,4 @@ -import Time from "./time"; +import { DateTime, Interval } from "luxon"; import { checkTimeRange, getValueIfKeyInList } from "../utils/helpers"; export default class ClassPeriod { @@ -7,17 +7,17 @@ export default class ClassPeriod { const end = getValueIfKeyInList(["endTime", "end_time"], json); return new ClassPeriod( getValueIfKeyInList(["name", "classPeriodName", "class_period_name"], json), - start instanceof Time ? start : Time.fromString(start), - end instanceof Time ? end : Time.fromString(end), - new Date(getValueIfKeyInList(["creationDate", "creation_date"], json)) + start instanceof DateTime ? start : DateTime.fromISO(start), + end instanceof DateTime ? end : DateTime.fromISO(end), + DateTime.fromISO(getValueIfKeyInList(["creationDate", "creation_date"], json)) ); } private name: string; - private startTime: Time; - private endTime: Time; - private creationDate: Date; + private startTime: DateTime; + private endTime: DateTime; + private creationDate: DateTime; - constructor(name: string, startTime: Time, endTime: Time, creationDate: Date) { + constructor(name: string, startTime: DateTime, endTime: DateTime, creationDate: DateTime) { this.name = name; this.startTime = startTime; this.endTime = endTime; @@ -36,7 +36,7 @@ export default class ClassPeriod { return this.startTime; } - public setStartTime(time: Time) { + public setStartTime(time: DateTime) { this.startTime = time; } @@ -44,12 +44,12 @@ export default class ClassPeriod { return this.endTime; } - public setEndTime(time: Time) { + public setEndTime(time: DateTime) { this.endTime = time; } public getDuration() { - return this.startTime.getTimeDeltaTo(this.endTime); + return Interval.fromDateTimes(this.startTime, this.endTime); } public getCreationDate() { @@ -57,7 +57,7 @@ export default class ClassPeriod { } //remove me - public stateForTime(time: Time) { + public stateForTime(time: DateTime) { return checkTimeRange(time, this.startTime, this.endTime); } } diff --git a/src/@types/school.ts b/src/@types/school.ts index 28ca918..593a016 100644 --- a/src/@types/school.ts +++ b/src/@types/school.ts @@ -3,7 +3,7 @@ import { getValueIfKeyInList, sortClassesByStartTime } from "../utils/helpers"; -import Time from "./time"; +import { DateTime } from "luxon"; import { TimeComparisons } from "../utils/enums"; import BellSchedule from "./bellschedule"; import find from 'lodash.find' @@ -35,8 +35,8 @@ export default class School { private timeZone?: string; private schedules?: BellSchedule[]; private passingPeriodName?: string; - private creationDate?: Date; - private lastUpdatedDate?: Date; + private creationDate?: DateTime; + private lastUpdatedDate?: DateTime; constructor( id: string, @@ -47,8 +47,8 @@ export default class School { timeZone?: string, schedules?: BellSchedule[], passingPeriodName?: string, - creationDate?: Date, - lastUpdatedDate?: Date + creationDate?: DateTime, + lastUpdatedDate?: DateTime ) { this.id = id; this.ownerId = ownerId; @@ -110,23 +110,23 @@ export default class School { return this.lastUpdatedDate; } - public hasChangedSince(date: Date) { + public hasChangedSince(date: DateTime) { if (this.lastUpdatedDate !== undefined) { - return date.getTime() < this.lastUpdatedDate.getTime(); + return date.toMillis() < this.lastUpdatedDate.toMillis(); } else { return undefined; } } //can also be used as isNoSchoolDay() by checking for undefined - public getScheduleForDate(date: Date) { + public getScheduleForDate(date: DateTime) { if (this.schedules) { for (const schedule of this.schedules) { if ( schedule .getDates() - .map((d: Date) => d.toDateString()) - .includes(date.toDateString()) + .includes(date) + // .map((d: Date) => d.toDateString()) ) { return schedule; } @@ -143,8 +143,7 @@ export default class School { //change input to a time //seems like te current schedule depends on this - public isInSession(date: Date, toLocalTime = false) { - const currentTime = Time.fromDate(date, toLocalTime); + public isInSession(date: DateTime) { const currentSchedule = this.getScheduleForDate(date); if (!currentSchedule) { return false; @@ -155,7 +154,7 @@ export default class School { const lastClass = sortedClasses[currentSchedule.numberOfClasses()] return ( checkTimeRange( - currentTime, + date, firstClass.getStartTime(), lastClass.getEndTime() ) == TimeComparisons.IS_DURING_OR_EXACTLY diff --git a/src/components/Calendar/Calendar.tsx b/src/components/Calendar/Calendar.tsx index d59be35..cc35aa2 100644 --- a/src/components/Calendar/Calendar.tsx +++ b/src/components/Calendar/Calendar.tsx @@ -1,9 +1,10 @@ import React, { useState, useEffect } from "react"; import "./Calendar.css"; -import dateFns from "date-fns"; import SelectHeader from "../SelectHeader"; import BellSchedule from "../../@types/bellschedule"; import find from "lodash.find"; +import { DateTime } from "luxon"; + export interface ICalendarProps { schedules?: BellSchedule[]; @@ -14,27 +15,26 @@ const Calendar = (props: ICalendarProps) => { // const initialOptions: { [key: string]: number[] } = {}; const getSelectedMonth = () => { const persisted = sessionStorage.getItem('selectedMonth'); - return persisted ? new Date(parseInt(persisted, 10)) : new Date(); + return persisted ? DateTime.fromMillis(parseInt(persisted, 10)) : DateTime.local(); }; const [selectedMonth, setSelectedMonth] = useState(getSelectedMonth); useEffect(function persistForm() { - sessionStorage.setItem('selectedMonth', selectedMonth.getTime().toString()); + sessionStorage.setItem('selectedMonth', selectedMonth.toMillis().toString()); }); - const config = { weekStartsOn: 1 }; - const startDate = dateFns.startOfWeek(dateFns.startOfMonth(selectedMonth), config); - const endDate = dateFns.endOfWeek(dateFns.endOfMonth(selectedMonth), config); + const startDate = selectedMonth.startOf('month').startOf('week') + const endDate = selectedMonth.endOf('month').endOf('week') // https://felixgerschau.com/react-rerender-components/#force-an-update-in-react-hooks - const [, updateState] = React.useState(); + const [, updateState] = React.useState({}); const forceUpdate = React.useCallback(() => updateState({}), []); const onDateClick = (event: React.MouseEvent) => { - const dateValue: Date = new Date(parseInt(event.currentTarget.dataset.date!, 10)); - if (isValidDate(dateValue)) { + const dateValue: DateTime = DateTime.fromMillis(parseInt(event.currentTarget.dataset.date!, 10)); + if (dateValue.isValid) { const currentSchedule = getScheduleForDate(dateValue); const selectedSchedule = getScheduleById(props.selectedScheduleId); let value = selectedSchedule; @@ -61,7 +61,7 @@ const Calendar = (props: ICalendarProps) => { } } - const setScheduleForDate = (date: Date, schedule?: BellSchedule) => { + const setScheduleForDate = (date: DateTime, schedule?: BellSchedule) => { const currentSchedule = getScheduleForDate(date); if (currentSchedule && schedule) { @@ -83,12 +83,7 @@ const Calendar = (props: ICalendarProps) => { forceUpdate(); }; - //https://stackoverflow.com/a/1353711 - const isValidDate = (d: Date) => { - return d instanceof Date && !isNaN(d.getTime()); - }; - - const getScheduleForDate = (date: Date): BellSchedule | undefined => { + const getScheduleForDate = (date: DateTime): BellSchedule | undefined => { if (props.schedules) { for (const schedule of props.schedules) { if (schedule.getDate(date)){ @@ -103,7 +98,7 @@ const Calendar = (props: ICalendarProps) => { const dayNames = []; for (let i = 0; i < 7; i++) { - dayNames.push(dateFns.format(dateFns.addDays(startDate, i), "ddd")); + dayNames.push(startDate.plus({ days: i }).toFormat("ddd")); } return dayNames; }; @@ -114,15 +109,12 @@ const Calendar = (props: ICalendarProps) => { for ( let dateIndex = 0; - dateIndex <= dateFns.differenceInDays(endDate, startDate); + dateIndex <= endDate.diff(startDate).days; dateIndex++ ) { - const date = dateFns.addDays(startDate, dateIndex); - const firstDayOfWeek = dateFns.startOfWeek(date, config); - const firstDayOfWeekTomorrow = dateFns.startOfWeek( - dateFns.addDays(date, 1), - config - ); + const date = startDate.plus({ days: dateIndex }); + const firstDayOfWeek = date.startOf('week') + const firstDayOfWeekTomorrow = date.plus({ days: 1 }).startOf('week') const schedule = getScheduleForDate(date); //show the schedule's assigned color if it is selected @@ -136,20 +128,20 @@ const Calendar = (props: ICalendarProps) => {
onDateClick(event)} className={ - dateFns.getMonth(date) !== dateFns.getMonth(selectedMonth) + date.get('month') !== selectedMonth.get('month') ? "disabled" : undefined } - data-date={date.getTime()} + data-date={date.toMillis()} style={bgColor} title={name} > - {date.getDate()} + {date.get('day')}
); - if (!dateFns.isEqual(firstDayOfWeek, firstDayOfWeekTomorrow)) { + if (!firstDayOfWeek.equals(firstDayOfWeekTomorrow)) { monthGrid.push({tempRowData}); tempRowData = []; } @@ -164,13 +156,13 @@ const Calendar = (props: ICalendarProps) => { - setSelectedMonth(dateFns.subMonths(selectedMonth, 1)) + setSelectedMonth(selectedMonth.minus({ month: 1 })) } nextAction={() => - setSelectedMonth(dateFns.addMonths(selectedMonth, 1)) + setSelectedMonth(selectedMonth.plus({month: 1})) } > - {dateFns.format(selectedMonth, "MMMM YYYY")} + {selectedMonth.toFormat("MMMM YYYY")} diff --git a/src/pages/App.tsx b/src/pages/App.tsx index d0db808..7f94539 100644 --- a/src/pages/App.tsx +++ b/src/pages/App.tsx @@ -5,7 +5,7 @@ import "../global.css"; import Link from "../components/Link"; import Icon from "../components/Icon"; import Block from "../components/Block/Block"; -import Time from "../@types/time"; +import { DateTime } from "luxon"; import School from "../@types/school"; import { pages } from "../utils/constants"; import BellSchedule from "../@types/bellschedule"; @@ -60,9 +60,7 @@ export const App = (props: IAppProps) => { ? nextImportantInfo : [undefined, undefined]; - const currentClass = currentSchedule.getClassPeriodForTime( - Time.fromDate(currentDate) - ); + const currentClass = currentSchedule.getClassPeriodForTime(currentDate); content = ( <> @@ -94,9 +92,8 @@ export const App = (props: IAppProps) => {

{nextImportantTime - ? Time.fromDate(currentDate) - .getTimeDeltaTo(nextImportantTime) - .getFormattedString() + ? currentDate.until(nextImportantTime) + .toFormat("H:mm") : "No Class"}

@@ -123,12 +120,12 @@ export const App = (props: IAppProps) => {

It is currently:

- {Time.fromDate(currentDate).getFormattedString()} + {currentDate.toLocaleString(DateTime.TIME_SIMPLE)}

on{" "} - {currentDate.toLocaleDateString("en-US", { + {currentDate.toLocaleString({ weekday: "long", year: "numeric", month: "short", diff --git a/src/services/classclock.ts b/src/services/classclock.ts index 12e2591..1a310d9 100644 --- a/src/services/classclock.ts +++ b/src/services/classclock.ts @@ -1,8 +1,10 @@ import BellSchedule from "../@types/bellschedule"; import { format } from 'date-fns' import { objectKeysToSnakeCase } from "../utils/helpers"; +import { DateTime } from "luxon"; + export default class ClassClockService { - public static baseURL: string = "https://api.classclock.app/v0"; + public static baseURL: string = (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') ? "http://localhost:8000/v0" : "https://api.classclock.app/v0";; static getSchoolsList = async (params?: any): Promise => { return await fetch( @@ -101,8 +103,8 @@ export default class ClassClockService { // return format(value, 'yyyy-MM-dd'); } else if (key == 'dates') { - return value.map((currentValue: Date) => { - return format(currentValue, 'YYYY-MM-DD'); + return value.map((currentValue: DateTime) => { + return currentValue.toFormat('YYYY-MM-DD'); // Date-fns v2 // return format(value, 'yyyy-MM-dd'); }) diff --git a/src/store/schools/actions.ts b/src/store/schools/actions.ts index 8a1d0dc..def781a 100644 --- a/src/store/schools/actions.ts +++ b/src/store/schools/actions.ts @@ -10,6 +10,7 @@ import { Dispatch } from "redux"; import ClassClockService from "../../services/classclock"; import School from "../../@types/school"; import BellSchedule from "../../@types/bellschedule"; +import { DateTime } from "luxon"; function requestSchool(): SchoolActionTypes { return { @@ -27,7 +28,7 @@ function receiveSchool(json: any): SchoolActionTypes { return { type: RECEIVE_SCHOOL, school: School.fromJson(json), - receivedAt: Date.now() + receivedAt: DateTime.local().toMillis() }; } diff --git a/src/utils/helpers.test.ts b/src/utils/helpers.test.ts index 5994fcf..8b5b25f 100644 --- a/src/utils/helpers.test.ts +++ b/src/utils/helpers.test.ts @@ -7,7 +7,6 @@ import { checkTimeRange } from "./helpers"; import ClassPeriod from "../@types/classperiod"; -import Time from "../@types/time"; import { classPeriod2, classPeriod, beforeSchoolHours, school, betweenClass, inClass, noSchool, afterSchoolHours, bellScheduleClasses, duringClass, startTime, endTime, startTime2, beforeClass, endTime2, afterClass } from "./testconstants"; import { TimeStates, TimeComparisons } from "./enums"; diff --git a/src/utils/helpers.tsx b/src/utils/helpers.tsx index 0f60cae..d44b372 100644 --- a/src/utils/helpers.tsx +++ b/src/utils/helpers.tsx @@ -1,5 +1,6 @@ -import Time from "../@types/time"; +import { DateTime, Interval } from "luxon"; import School from "../@types/school"; +//todo, replace timeComparisons with luxon Interval import { TimeComparisons, TimeStates } from "./enums"; import ClassPeriod from "../@types/classperiod"; import BellSchedule from "../@types/bellschedule"; @@ -58,17 +59,17 @@ export function toSnakeCase(input: string) { export function getCurrentDate() { - return new Date(); + return DateTime.local(); } export function sortClassesByStartTime(classes: ClassPeriod[]) { - return classes.sort((a, b) => -a.getStartTime().getMillisecondsTo(b.getStartTime())); + return classes.sort((a, b) => -a.getStartTime().diff(b.getStartTime()).get("milliseconds")); } /** * @returns a flag that represents the current chunk of time categorically */ -export function getTimeStateForDateAtSchool(date: Date, school: School) { +export function getTimeStateForDateAtSchool(date: DateTime, school: School) { const currentBellSchedule = school.getScheduleForDate(date); //there is no schedule that applies today @@ -76,9 +77,7 @@ export function getTimeStateForDateAtSchool(date: Date, school: School) { return TimeStates.DAY_OFF; } - const currentClassPeriod = currentBellSchedule.getClassPeriodForTime( - Time.fromDate(date) - ); + const currentClassPeriod = currentBellSchedule.getClassPeriodForTime(date); //it is a school day but it is not school hours if (!school.isInSession(date)) { @@ -100,9 +99,9 @@ export function getTimeStateForDateAtSchool(date: Date, school: School) { * @returns the next relevent time to count down to */ export function getNextImportantInfo( - date: Date, + date: DateTime, school: School -): [ClassPeriod, Time] | undefined { +): [ClassPeriod, DateTime] | undefined { const currentBellSchedule = school.getScheduleForDate(date); //there is no schedule that applies today @@ -114,9 +113,9 @@ export function getNextImportantInfo( //loop through all classes in order until you get to the first time that has not passed for (let i = 0; i < classes.length; i++) { for (const time of [classes[i].getStartTime(), classes[i].getEndTime()]) { - if (Time.fromDate(date).getMillisecondsTo(time) >= 0) { + if (date.diff(time).get("milliseconds") >= 0) { const nextClass = - classes[i].stateForTime(Time.fromDate(date)) === + classes[i].stateForTime(date) === TimeComparisons.IS_DURING_OR_EXACTLY ? classes[i + 1] : classes[i]; @@ -136,16 +135,18 @@ export function getNextImportantInfo( * * @returns -1 if checkTime is before range, 0 if checkTime is within range, 1 if checkTime is after range */ -export function checkTimeRange(checkTime: Time, startTime: Time, endTime: Time) { - if (startTime.getMillisecondsTo(endTime) <= 0) { - //theres a problem - } - const startCheck = checkTime.getMillisecondsTo(startTime); - const endCheck = checkTime.getMillisecondsTo(endTime); - - if (startCheck > 0 && endCheck > 0) { +export function checkTimeRange(checkTime: DateTime, startTime: DateTime, endTime: DateTime) { + const interval = Interval.fromDateTimes(startTime,endTime) + + // if (startTime.getMillisecondsTo(endTime) <= 0) { + // //theres a problem + // } + // const startCheck = checkTime.getMillisecondsTo(startTime); + // const endCheck = checkTime.getMillisecondsTo(endTime); + + if (interval.isAfter(checkTime)) { return TimeComparisons.IS_BEFORE; - } else if (startCheck < 0 && endCheck < 0) { + } else if (interval.isBefore(checkTime)) { return TimeComparisons.IS_AFTER; } else { return TimeComparisons.IS_DURING_OR_EXACTLY; diff --git a/src/utils/testconstants.ts b/src/utils/testconstants.ts index 9885a3d..c1c4c7f 100644 --- a/src/utils/testconstants.ts +++ b/src/utils/testconstants.ts @@ -1,6 +1,5 @@ // This is not actually a unit test, just a central place to hold frequently-used constants that are often reused across tests - -import Time from "../@types/time"; +import { DateTime, Duration } from "luxon"; import School from "../@types/school"; import BellSchedule from "../@types/bellschedule"; import ClassPeriod from "../@types/classperiod"; @@ -26,21 +25,23 @@ export const bellScheduleEndpoint = export const bellScheduleDisplayName = "Display Name"; -export const currentDate = new Date("2019-07-28T07:37:50.634Z"); +export const currentDate = DateTime.fromISO("2019-07-28T07:37:50.634Z"); export const className = "First Period"; +const timeStringFormat = "H:mm" -export const beforeClass = new Time(8, 0); export const beforeClassString = "8:00" -export const startTime = new Time(8, 25); +export const beforeClass = DateTime.fromFormat(beforeClassString, timeStringFormat); export const startTimeString = "8:25"; -export const classDuration = new Time(1, 30); -export const duringClass = new Time(9, 0); +export const startTime = DateTime.fromFormat(startTimeString, timeStringFormat); +export const classDuration = Duration.fromObject({hours:1, minutes:30}); export const duringClassString = "9:00"; -export const endTime = new Time(9, 55); +export const duringClass = DateTime.fromFormat(duringClassString, timeStringFormat); export const endTimeString = "9:55"; -export const afterClass = new Time(10, 0); +export const endTime = DateTime.fromFormat(endTimeString, timeStringFormat); export const afterClassString = "10:00"; +export const afterClass = DateTime.fromFormat(afterClassString, timeStringFormat); + export const classPeriod = new ClassPeriod( className, @@ -59,13 +60,13 @@ export const classPeriodJSON = { export const class2Name = "Second Period"; -export const startTime2 = new Time(10, 5); export const startTime2String = "10:05"; -export const class2Duration = new Time(1, 30); -export const duringClass2 = new Time(11, 0); -export const endTime2 = new Time(11, 35); +export const startTime2 = DateTime.fromFormat(startTime2String, timeStringFormat); +export const class2Duration = classDuration +export const duringClass2 = DateTime.fromObject({ hour: 11, minute: 0}) export const endTime2String = "11:35"; -export const afterClass2 = new Time(11, 40); +export const endTime2 = DateTime.fromFormat(endTime2String, timeStringFormat); +export const afterClass2 = DateTime.fromObject({ hour: 11, minute: 40}) export const classPeriod2 = new ClassPeriod( class2Name, @@ -82,14 +83,14 @@ export const classPeriod2JSON = { }; -// export const schoolInSession = new Date("2019-07-28T07:37:50.634Z"); -export const noSchool = new Date("2019-07-27T07:37:50.634Z"); -export const beforeSchoolHours = new Date("2019-07-28T0" + beforeClassString + ":00.000Z"); +// export const schoolInSession = DateTime.fromISO("2019-07-28T07:37:50.634Z"); +export const noSchool = DateTime.fromISO("2019-07-27T07:37:50.634Z"); +export const beforeSchoolHours = DateTime.fromISO("2019-07-28T0" + beforeClassString + ":00.000Z"); //start of class? -export const betweenClass = new Date("2019-07-28T" + afterClassString + ":50.634Z"); -export const inClass = new Date("2019-07-28T0" + duringClassString + ":50.634Z"); +export const betweenClass = DateTime.fromISO("2019-07-28T" + afterClassString + ":50.634Z"); +export const inClass = DateTime.fromISO("2019-07-28T0" + duringClassString + ":50.634Z"); //end of class? -export const afterSchoolHours = new Date("2019-07-28T12:00:50.634Z"); +export const afterSchoolHours = DateTime.fromISO("2019-07-28T12:00:50.634Z"); export const bellScheduleClasses = [classPeriod, classPeriod2]; @@ -101,9 +102,9 @@ export const bellSchedule = new BellSchedule( bellScheduleName, bellScheduleEndpoint, [ - new Date("2019-07-28T07:37:50.634Z"), - new Date("2019-07-29T07:38:10.979Z"), - new Date("2019-07-23T07:38:28.263Z") + DateTime.fromISO("2019-07-28T07:37:50.634Z"), + DateTime.fromISO("2019-07-29T07:38:10.979Z"), + DateTime.fromISO("2019-07-23T07:38:28.263Z") ], bellScheduleClasses, currentDate