@zohodesk/hooks
Version:
Unified Component Library - Hooks
104 lines (96 loc) • 2.07 kB
JavaScript
import React from 'react';
import useCommonReducer from "../utils/useCommonReducer";
import calendarReducer from "./reducers/calendarReducer";
import * as constants from "./reducers/constants";
import getMonthDates from "./utils/getMonthData";
import getCurrentValue from "./utils/getCurrentValue";
import { dateDecode, dateEncode } from "./utils/dateConverter";
/**
* @param {Object} props={}
* @param {Function} customReducer
*/
export default function useCalendar() {
let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let customReducer = arguments.length > 1 ? arguments[1] : undefined;
const {
currentDate,
currentMonth,
currentYear
} = getCurrentValue();
let currentDateValue = dateEncode({
date: currentDate,
month: currentMonth + 1,
year: currentYear
});
const {
value: propsValue = currentDateValue
} = props;
const {
state,
dispatch
} = useCommonReducer(calendarReducer, customReducer, {
value: propsValue
});
let {
value
} = state;
const {
date,
month,
year
} = dateDecode(value);
const newDate = new Date(year, month - 1, date);
const day = newDate.getDay();
function getMonthData() {
return getMonthDates({
day,
date,
month,
year
});
}
function handlePrevMonth() {
dispatch({
type: constants.PREV_MONTH,
data: value
});
}
function handleNextMonth() {
dispatch({
type: constants.NEXT_MONTH,
data: value
});
}
function handlePrevYear() {
dispatch({
type: constants.PREV_YEAR,
data: value
});
}
function handleNextYear() {
dispatch({
type: constants.NEXT_YEAR,
data: value
});
}
function handleChange(data) {
dispatch({
type: constants.CHANGE,
data: {
date,
month,
year,
...data
}
});
}
return {
value,
getMonthData,
handleChange,
handlePrevMonth,
handleNextMonth,
handlePrevYear,
handleNextYear
};
}