Last active
May 3, 2023 17:46
-
-
Save ZachSaucier/ec6f58e49082c27eaae240786bc82997 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface YearDropdownPluginConfig { | |
text: string; | |
theme: string; | |
date: Date; | |
yearStart: number; | |
yearEnd: number; | |
} | |
const yearDropdownPlugin = function ({ | |
text = "", | |
theme = "light", | |
date = new Date(), | |
yearStart = 100, | |
yearEnd = 2, | |
} = {}) { | |
const config: YearDropdownPluginConfig = { | |
text, | |
theme, | |
date, | |
yearStart, | |
yearEnd, | |
}; | |
const getYear = function (value: Date) { | |
const d = value.toString().split("/"); | |
return parseInt(d[2], 10); | |
}; | |
const currYear = new Date().getFullYear(); | |
const selectedYear = getYear(config.date); | |
const yearDropdown = document.createElement("select"); | |
const createSelectElement = function (year: number) { | |
const start = new Date().getFullYear() - config.yearStart; | |
const end = currYear + config.yearEnd; | |
for (let i = end; i >= start; i--) { | |
const option = document.createElement("option"); | |
option.value = i.toString(); | |
option.text = i.toString(); | |
yearDropdown.appendChild(option); | |
} | |
yearDropdown.value = year.toString(); | |
}; | |
return function (fp: any) { | |
fp.yearSelectContainer = fp._createElement( | |
"div", | |
"flatpickr-year-select " + config.theme + "Theme", | |
config.text | |
); | |
fp.yearSelectContainer.tabIndex = -1; | |
createSelectElement(selectedYear); | |
yearDropdown.addEventListener("change", function (evt) { | |
const target = evt.target as HTMLSelectElement; | |
const year = target.options[target.selectedIndex].value; | |
fp.changeYear(year); | |
}); | |
fp.yearSelectContainer.append(yearDropdown); | |
return { | |
onReady: function onReady() { | |
const name = fp.monthNav.className; | |
const yearInputCollection = fp.calendarContainer.getElementsByClassName(name); | |
const el = yearInputCollection[0]; | |
el.parentNode.insertBefore(fp.yearSelectContainer, el.parentNode.firstChild); | |
}, | |
}; | |
}; | |
}; | |
export default yearDropdownPlugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment