Skip to content

Commit

Permalink
feat: add new methods
Browse files Browse the repository at this point in the history
  • Loading branch information
PawanKolhe committed Aug 24, 2020
1 parent 3ff2e6c commit e7424f3
Show file tree
Hide file tree
Showing 3 changed files with 138 additions and 47 deletions.
76 changes: 70 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
* [Usage](#usage)
* [Options](#options)
* [Events](#events)
* [Methods](#methods)
* [Types](#types)
* [Themes](#themes)
* [License](#license)

Expand Down Expand Up @@ -121,21 +123,23 @@ Default: `#color-calendar`
Selector referencing HTMLElement where the calendar instance will bind to.
### `eventsData`
Type: `Array[...Objects]`
Type: [`EventData`](#event-data)[]
Default: `null`
```javascript
[
{
start: '2020-08-17T06:00:00',
end: '2020-08-18T20:30:00',
start: '2020-08-17T06:00:00',
end: '2020-08-18T20:30:00',
name: 'Blockchain 101'
...
},
...
]
```
Array of objects containing events information. Properties `start` and `end` are *required* for each event in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time format.
Array of objects containing events information.
> Note: Properties `start` and `end` are *required* for each event in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time format. You can _optionally_ choose to add other properties.
### `theme`
Type: `String`
Expand Down Expand Up @@ -267,8 +271,68 @@ Props:
Emitted when the current month is changed.
<!-- ## 🔧 Methods
Coming soon... -->
<a id="methods"></a>
## 🔧 Methods
### `reset()`
Return:
- Type: `void`
Reset calendar to today's date.
```javascript
let myCal = new Calendar();
myCal.reset();
```
### `setDate()`
Props:
| Props | Type | Required | Description |
|-------|------|----------|--------------------|
| date | Date | required | New date to be set |
Return:
- Type: `void`
Set new selected date.
### `getSelectedDate()`
Return:
- Type: `Date`
- Description: `Currently selected date`
Get currently selected date.
### `setEventsData()`
Props:
| Props | Type | Required | Description |
|--------|------------|----------|------------------|
| events | [EventData](#eventdata)[] | required | Events to be set |
Return:
- Type: `Number`
- Description: `Number of events set`
Set a new events array.
### `addEventsData()`
Props:
| Props | Type | Required | Description |
|--------|------------|----------|--------------------|
| events | [EventData](#eventdata)[] | required | Events to be added |
Return:
- Type: `Number`
- Description: `Number of events added`
Add events of the events array.
<a id="types"></a>
## 💎 Types
<a id="event-data"></a>
### `EventData`
```javascript
interface EventData {
start: string,
end: string,
[key: string]: any,
}
```
<a id="themes"></a>
## 🎨 Themes
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
{
"name": "color-calendar",
"version": "1.0.0",
"version": "1.0.1",
"description": "A customizable events calendar widget library",
"main": "dist/bundle.cjs.js",
"module": "dist/bundle.esm.js",
"browser": "dist/bundle.js",
"typings": "dist/index.d.ts",
"types": "dist/index.d.ts",
"scripts": {
"start:js": "rollup -c -w",
"start:css": "gulp watch",
"prebuild": "rimraf dist",
"build": "rollup -c && gulp",
"build": "rollup -c && gulp && npm run build:types",
"build:types": "tsc --declaration src/index.ts --declarationDir dist --emitDeclarationOnly",
"clean": "rimraf dist",
"test": "echo \"Error: no test specified\" && exit 1"
Expand Down
103 changes: 65 additions & 38 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export default class Calendar {
yearDisplay: HTMLElement;

constructor(options: CalendarOptions = {}) {
// Options
// Initialize Options
this.id = options.id ?? "#calendar";
this.monthDisplayType = (options.monthDisplayType ?? "long") as MonthDisplayType;
this.eventsData = options.eventsData ?? [];
Expand All @@ -89,7 +89,7 @@ export default class Calendar {
this.monthChanged = options.monthChanged;
this.dateChanged = options.dateChanged;

// State
// Initialize State
this.weekdayType = (options.weekdayType ?? "long") as WeekdayType;
switch (this.weekdayType) {
case "short":
Expand Down Expand Up @@ -123,9 +123,13 @@ export default class Calendar {
this.yearPickerOffsetTemporary = 0;

this.calendar = document.querySelector(this.id) as HTMLElement;

// Check if HTML element with given selector exists in DOM
if(!this.calendar) {
throw new Error(`Element with selector '${this.id}' not found`);
throw new Error(`[COLOR-CALENDAR] Element with selector '${this.id}' not found`);
}

// Initialize initial HTML layout
this.calendar.innerHTML = `
<div class="${this.CAL_NAME} ${this.theme}">
<div class="calendar__header">
Expand Down Expand Up @@ -179,6 +183,7 @@ export default class Calendar {
</div>
`;

// Store HTML element references
this.calendarMonthYear = document.querySelector(`${this.id} .calendar__monthyear`) as HTMLElement;
this.calendarWeekdays = document.querySelector(`${this.id} .calendar__weekdays`) as HTMLElement;
this.calendarDays = document.querySelector(`${this.id} .calendar__days`) as HTMLElement;
Expand All @@ -193,18 +198,28 @@ export default class Calendar {
this.monthDisplay = document.querySelector(`${this.id} .calendar__month`) as HTMLElement;
this.yearDisplay = document.querySelector(`${this.id} .calendar__year`) as HTMLElement;

this.resetCalendar();
// Set initial picker styles
this.togglePicker(false);

// Set CSS Variables based on options given
this.configureStylePreferences();

// Apply click listeners to HTML elements
this.addEventListeners();

this.reset(new Date());
}

resetCalendar() {
this.initializeLayout();
reset(date: Date) {
this.currentDate = date ? date : new Date();
this.clearCalendarDays();
this.updateMonthYear();
this.updateMonthPickerSelection(this.currentDate.getMonth());
this.generatePickerYears();
this.updateYearPickerSelection(this.currentDate.getFullYear(), 4);
this.generateWeekdays();
this.generateDays();
this.selectDayInitial();
this.selectDayInitial(date ? true : false);
this.renderDays();
this.setOldSelectedNode();
if(this.dateChanged) {
Expand All @@ -215,10 +230,22 @@ export default class Calendar {
}
}

initializeLayout() {
// Set initial picker styles
this.togglePicker(false);
setDate(date: Date) {
if(!date) {
return;
}
if(date instanceof Date) {
this.reset(date);
} else {
this.reset(new Date(date));
}
}

getSelectedDate() {
return this.currentDate;
}

addEventListeners() {
// Event Listeners
this.prevButton.addEventListener("click",
this.handlePrevMonthButtonClick.bind(this)
Expand All @@ -244,8 +271,6 @@ export default class Calendar {
this.yearPickerChevronRight.addEventListener("click",
this.handleYearChevronRightClick.bind(this)
);

this.configureStylePreferences();
}

/** Configure calendar style preferences */
Expand Down Expand Up @@ -320,13 +345,17 @@ export default class Calendar {
}
}

selectDayInitial() {
let isTodayMonth = this.today.getMonth() === this.currentDate.getMonth();
let isTodayDay = this.today.getDate() === this.currentDate.getDate();
if(isTodayMonth && isTodayDay) {
this.daysIn_CurrentMonth[this.today.getDate() - 1].selected = true;
selectDayInitial(setDate?: boolean) {
if(setDate) {
this.daysIn_CurrentMonth[this.currentDate.getDate() - 1].selected = true;
} else {
this.daysIn_CurrentMonth[0].selected = true;
let isTodayMonth = this.today.getMonth() === this.currentDate.getMonth();
let isTodayDay = this.today.getDate() === this.currentDate.getDate();
if(isTodayMonth && isTodayDay) {
this.daysIn_CurrentMonth[this.today.getDate() - 1].selected = true;
} else {
this.daysIn_CurrentMonth[0].selected = true;
}
}
}

Expand All @@ -335,17 +364,17 @@ export default class Calendar {
}

/** Set new events data array */
setEventsData(data: EventData[]) {
this.eventsData = JSON.parse(JSON.stringify(data));
this.updateCalendar();
return this.eventsData;
setEventsData(events: EventData[]) {
this.eventsData = JSON.parse(JSON.stringify(events));
this.setDate(this.currentDate);
return this.eventsData.length;
}

/** Add events to existing events data array */
addEventsData(newEvents: EventData[] = []) {
const eventCount = this.eventsData.push(...newEvents);
this.updateCalendar();
return eventCount;
const eventAddedCount = this.eventsData.push(...newEvents);
this.setDate(this.currentDate);
return eventAddedCount;
}

/** Invoked on month or year click */
Expand Down Expand Up @@ -437,16 +466,25 @@ export default class Calendar {
}

updateMonthPickerSelection(newMonthValue: number) {
const oldMonthValue = this.currentDate.getMonth();
if(newMonthValue < 0) {
newMonthValue = 11;
} else {
newMonthValue = newMonthValue % 12;
}
this.pickerMonthContainer!.children[oldMonthValue].classList.remove('calendar__picker-month-selected');

this.removeMonthPickerSelection();
this.pickerMonthContainer!.children[newMonthValue].classList.add('calendar__picker-month-selected');
}

removeMonthPickerSelection() {
// Remove old year selection by scanning for the selected month
for(let i = 0; i < 12; i++) {
if(this.pickerMonthContainer!.children[i].classList.contains('calendar__picker-month-selected')) {
this.pickerMonthContainer!.children[i].classList.remove('calendar__picker-month-selected');
}
}
}

handleYearPickerClick(e: any) {
// Filter out unwanted click events
if (!(e.target.classList.contains("calendar__picker-year-option"))) {
Expand Down Expand Up @@ -644,17 +682,6 @@ export default class Calendar {
}
}

// /**
// * @param {Date} date - Date to use
// */
// DateUTCToISOLocal(date: Date) {
// console.log(date);
// const tzoffset = (date).getTimezoneOffset() * 60000;
// console.log(tzoffset);
// let localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
// return localISOTime;
// }

/** Update Month and Year HTML */
updateMonthYear() {
this.oldSelectedNode = null;
Expand Down

0 comments on commit e7424f3

Please sign in to comment.