Skip to content

Commit

Permalink
Merge pull request #237 from qqlexa/replace-moment-with-dayjs
Browse files Browse the repository at this point in the history
Replace moment with dayjs
  • Loading branch information
niravzi authored Sep 23, 2024
2 parents 307762f + 9901426 commit fedd811
Show file tree
Hide file tree
Showing 14 changed files with 101 additions and 106 deletions.
68 changes: 12 additions & 56 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@
"@types/react-dom": "^18.3.0",
"@types/styled-components": "^5.1.34",
"@types/styled-system": "^5.1.22",
"axios": "^0.27.2",
"clsx": "^1.2.0",
"dayjs": "^1.11.13",
"lodash-es": "^4.17.21",
"moment": "^2.29.4",
"react": "17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.2.0",
Expand Down
8 changes: 4 additions & 4 deletions src/api/fullList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import { PagedResponse } from '../models/PagedResponse';
import Http from "./index";

export const getAllLecturers = (): Promise<PagedResponse<Lecturer[]>> => {
return Http.get("/schedule/lecturer/list").then(({ data }) => data);
return Http.get("/schedule/lecturer/list");
};

export const getAllGroups = async (): Promise<PagedResponse<Group[]>> => {
const response = await Http.get<PagedResponse<Group[]>>("/schedule/groups")
const response = await Http.get("/schedule/groups");

return {
...response.data,
data: response.data.data.map(row => ({
...(response as PagedResponse<Group[]>),
data: (response as PagedResponse<Group[]>).data.map(row => ({
...row,
name: `${row.name.trim()} (${row.faculty.trim()})`,
id: row.id,
Expand Down
4 changes: 2 additions & 2 deletions src/api/getCurrentDateValues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ import { PagedResponse } from '../models/PagedResponse';
import Http from './index';

export const getCurrentDateValues = (): Promise<PagedResponse<CurrentTime>> => {
return Http.get('/time/current').then(res => res.data);
};
return Http.get('/time/current');
};
39 changes: 33 additions & 6 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
import axios from "axios";
let headers = {};
const BASE_URL = "https://api.campus.kpi.ua";

export const Http = axios.create({
baseURL: "https://api.campus.kpi.ua/",
headers,
});
const defaultHeaders = {
"Content-Type": "application/json",
};

interface FetchOptions extends RequestInit {
headers?: Record<string, string>;
}

const fetchWrapper = async (requestUrl: string, options: FetchOptions = {}) => {
const { headers = {}, ...restOptions } = options;

const requestOptions: RequestInit = {
...restOptions,
headers: {
...defaultHeaders,
...headers,
},
};

const url = BASE_URL + requestUrl;
const response = await fetch(url, requestOptions);

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status} in request to ${url}`);
}
return await response.json();
};

const Http = {
get: (url: string, options: FetchOptions = {}) =>
fetchWrapper(url, { ...options, method: 'GET' }),
};

export default Http;
11 changes: 4 additions & 7 deletions src/api/schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,13 @@ import { StudentLesson } from '../models/StudentLesson';
import Http from './index';

export const getScheduleByLecturer = (lecturerId: string): Promise<PagedResponse<LecturerLesson[]>> => {
return Http.get('/schedule/lecturer?lecturerId=' + lecturerId)
.then(res => res.data);
return Http.get('/schedule/lecturer?lecturerId=' + lecturerId);
}

export const getScheduleByGroup = (groupId: string): Promise<PagedResponse<StudentLesson[]>> => {
return Http.get('/schedule/lessons?groupId=' + groupId)
.then(res => res.data);
return Http.get('/schedule/lessons?groupId=' + groupId);
}

export const getExamsByGroup = (groupName: string): Promise<PagedResponse<Exam[]>> => {
return Http.get('/exams/group?groupId=' + groupName)
.then(res => res.data);
}
return Http.get('/exams/group?groupId=' + groupName);
}
4 changes: 2 additions & 2 deletions src/common/constants/scheduleParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ export const DAYS = [
];

export const TIME_POINTS = [
'8:30',
'08:30',
'10:25',
'12:20',
'14:15',
'16:10',
'18:30'
];
];
2 changes: 1 addition & 1 deletion src/common/hooks/useCurrentDateParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ export const useCurrentDateParams = () => {
}, []);

return dateParams;
};
};
9 changes: 5 additions & 4 deletions src/common/utils/generateScheduleMatrix.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import moment from "moment";
import dayjs from 'dayjs';
import { DAYS, TIME_POINTS } from "../../common/constants/scheduleParams";
import { getActiveTimePoint } from "../../common/utils/getActiveTimePoint";
import { getActiveTimePoint, parseTime } from "../../common/utils/getActiveTimePoint";
import { Schedule } from '../../models/Schedule';
import { Pair } from '../../models/Pair';

Expand All @@ -19,13 +19,14 @@ export const generateScheduleMatrix = <T extends Pair,>(weekSchedule: Schedule<T
.map(() => new Array(DAYS.length).fill(null));

const activePair: number = getActiveTimePoint();
const currentDay = moment().day();
const currentDay = dayjs().day();

weekSchedule.forEach((schedule) => {
const yIndex = DAYS.findIndex((item) => item === schedule.day);

schedule.pairs.forEach((pair) => {
const xIndex = TIME_POINTS.findIndex((item) => item === pair.time);
const normalizedPairTime = parseTime(pair.time).format('HH:mm');
const xIndex = TIME_POINTS.findIndex((item) => item === normalizedPairTime);
const cell = scheduleMatrix[xIndex][yIndex];
let newCell: ScheduleMatrixCell | ScheduleMatrixCell[] = {
...pair,
Expand Down
23 changes: 17 additions & 6 deletions src/common/utils/getActiveTimePoint.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
import moment from 'moment';
import dayjs from 'dayjs';
import { TIME_POINTS } from '../../common/constants/scheduleParams';

export const parseTime = (timeString: string) => {
const [hours, minutes] = timeString.split(':').map(Number);

const today = dayjs().startOf('day');

return today
.hour(hours)
.minute(minutes)
.second(0);
};


export const getActiveTimePoint = () => {
const PAIR_DURATION_IN_MINUTES = 95;
const now = moment();
const now = dayjs();

return TIME_POINTS.findIndex((timePoint) => {
const timeNumbers = timePoint.split('.').map(item => +item);
const pairStartDate = moment().set({ hours: timeNumbers[0], minutes: timeNumbers[1], seconds: 0 });
const pairEndDate = moment(pairStartDate).set({ minutes: timeNumbers[1] + PAIR_DURATION_IN_MINUTES })
const pairStartDate = parseTime(timePoint);
const pairEndDate = pairStartDate.add(PAIR_DURATION_IN_MINUTES, 'minute');

return now.isBetween(pairStartDate, pairEndDate);
});
};
};
10 changes: 5 additions & 5 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { FooterWrapper, FooterLogo, FooterSection } from './Footer.style'
import { FooterWrapper, FooterLogo, FooterSection } from './Footer.style';
import logo from '../../assets/footer-logo.svg';
import moment from 'moment';
import dayjs from 'dayjs';

export const Footer = () => {
return (
<FooterWrapper>
<FooterLogo src={logo} alt="footer logo" />
<FooterSection>
<p>
Національний технічний університет України"Київський політехнічний інститут імені Ігоря Сікорського" © 1998-{moment().year()}
Національний технічний університет України"Київський політехнічний інститут імені Ігоря Сікорського" © 1998-{dayjs().year()}
</p>
<p>
Адреса: Україна, 03056 м.Київ-56, проспект Перемоги, 37
Expand All @@ -24,9 +24,9 @@ export const Footer = () => {
</FooterSection>
<FooterSection>
<p>
Використання матеріалу сайту тільки з обов’язковим посиланням на schedule.kpi.ua
Використання матеріалу сайту тільки з обов’язковим посиланням на schedule.kpi.ua
</p>
</FooterSection>
</FooterWrapper>
)
);
};
11 changes: 5 additions & 6 deletions src/components/examSchedule/examSchedule.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { CardDate, CardMainData, CardWrapper, Divider, DividerRed, Location, Subject, Teacher, } from './exam.style';
import dayjs from 'dayjs';
import { CardDate, CardMainData, CardWrapper, Divider, DividerRed, Location, Subject, Teacher } from './exam.style';
import teacherIcon from '../../assets/icons/teacher.svg';
import locationIcon from '../../assets/icons/location.svg';
import clock from '../../assets/icons/clock.svg';
import { Flex, Pictogram } from '../../common/styles/styles';
import React from 'react';
import { Exam } from '../../models/Exam';
import moment from 'moment';

interface Props {
exam: Exam;
Expand All @@ -18,9 +18,8 @@ const ExamSchedule = ({ exam }: Props) => {
room,
} = exam;

const date = moment(exam.date);
const time = moment(exam.date).locale('en-US');
const daysLeft = moment.duration(date.diff(moment())).days();
const date = dayjs(exam.date);
const daysLeft = dayjs(date).diff(dayjs(), 'day');

return (
<div>
Expand All @@ -35,7 +34,7 @@ const ExamSchedule = ({ exam }: Props) => {
</Teacher>
<Teacher>
<Pictogram src={clock} alt="time"/>
{time.format('h:mm A')}
{date.format('h:mm A')}
</Teacher>
<Location>
<Pictogram src={locationIcon} alt="location"/>
Expand Down
3 changes: 1 addition & 2 deletions src/components/timeDivider/timeDivider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import moment from 'moment';
import {
Container,
Divider,
Expand All @@ -9,7 +8,7 @@ import {
const TimeDivider = ({ value }: { value: string }) => (
<Container>
<InnerContainer>
<TimeCell>{moment(value, 'H:mm').format('HH:mm')}</TimeCell>
<TimeCell>{value}</TimeCell>
<Divider />
</InnerContainer>
</Container>
Expand Down
Loading

0 comments on commit fedd811

Please sign in to comment.