-
Notifications
You must be signed in to change notification settings - Fork 1
/
renderer.ts
86 lines (78 loc) · 2.63 KB
/
renderer.ts
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
import { Event } from "./event";
const CELL_HEIGHT = 50;
const HOURS_IN_A_DAY = 24;
const DAYS_IN_A_WEEK = 7;
export class Renderer {
private calendarCells: NodeListOf<HTMLElement>;
private cellArray: (HTMLElement | undefined)[][];
private onEventClickFn: (id: number, event: Event) => void;
constructor(root: HTMLElement) {
this.calendarCells = root.querySelectorAll(".main-calendar__body__cells");
this.cellArray = new Array<HTMLElement[] | undefined>(HOURS_IN_A_DAY)
.fill(undefined)
.map(() => new Array<HTMLElement | undefined>(DAYS_IN_A_WEEK));
for (let i = 0; i < HOURS_IN_A_DAY; i++) {
for (let j = 0; j < DAYS_IN_A_WEEK; j++) {
this.cellArray[i][j] = this.calendarCells[i * DAYS_IN_A_WEEK + j];
}
}
this.onEventClickFn = () => {};
}
renderEvent(event: Event) {
for (let [start, end] of this.calcEventRanges(event)) {
const eventDataContainer = document.createElement("div");
eventDataContainer.addEventListener("click", () =>
this.onEventClickFn(event.id, event)
);
eventDataContainer.setAttribute("class", "event");
eventDataContainer.innerText = `${event.title}, ${event.startDate
.toTimeString()
.slice(0, 5)} - ${event.endDate.toTimeString().slice(0, 5)}`;
this.setEventStyles(start, end, eventDataContainer);
this.cellArray[start.getHours()][start.getDay()]?.appendChild(
eventDataContainer
);
}
}
private setEventStyles(
startDate: Date,
endDate: Date,
eventDataContainer: HTMLElement
) {
Object.assign(eventDataContainer.style, {
top: (CELL_HEIGHT * startDate.getMinutes()) / 60 + "px",
height:
((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60)) *
CELL_HEIGHT +
"px",
});
}
private calcEventRanges({
startDate,
endDate,
}: {
startDate: Date;
endDate: Date;
}): [Date, Date][] {
const result: [Date, Date][] = [];
let eventStart = startDate.getTime();
let eventEnd = new Date(eventStart).setHours(23, 59, 59, 999);
while (endDate.getTime() > eventEnd) {
result.push([new Date(eventStart), new Date(eventEnd)]);
eventStart = eventEnd + 1;
eventEnd = new Date(eventStart + 1).setHours(23, 59, 59, 999);
}
result.push([new Date(eventStart), endDate]);
return result;
}
onEventClick(onEventClickFn: (id: number, event: Event) => void) {
this.onEventClickFn = onEventClickFn;
}
clearEventsFromBoard() {
for (let i = 0; i < HOURS_IN_A_DAY; i++) {
for (let j = 0; j < DAYS_IN_A_WEEK; j++) {
this.cellArray[i][j]?.replaceChildren();
}
}
}
}