index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
  2. import { RiCalendarLine, RiCloseCircleFill } from '@remixicon/react'
  3. import cn from '@/utils/classnames'
  4. import type { DatePickerProps, Period } from '../types'
  5. import { ViewType } from '../types'
  6. import type { Dayjs } from 'dayjs'
  7. import dayjs, {
  8. clearMonthMapCache,
  9. cloneTime,
  10. getDateWithTimezone,
  11. getDaysInMonth,
  12. getHourIn12Hour,
  13. } from '../utils/dayjs'
  14. import {
  15. PortalToFollowElem,
  16. PortalToFollowElemContent,
  17. PortalToFollowElemTrigger,
  18. } from '@/app/components/base/portal-to-follow-elem'
  19. import DatePickerHeader from './header'
  20. import Calendar from '../calendar'
  21. import DatePickerFooter from './footer'
  22. import YearAndMonthPickerHeader from '../year-and-month-picker/header'
  23. import YearAndMonthPickerOptions from '../year-and-month-picker/options'
  24. import YearAndMonthPickerFooter from '../year-and-month-picker/footer'
  25. import TimePickerHeader from '../time-picker/header'
  26. import TimePickerOptions from '../time-picker/options'
  27. import { useTranslation } from 'react-i18next'
  28. const DatePicker = ({
  29. value,
  30. timezone,
  31. onChange,
  32. onClear,
  33. placeholder,
  34. needTimePicker = true,
  35. renderTrigger,
  36. triggerWrapClassName,
  37. popupZIndexClassname = 'z-[11]',
  38. }: DatePickerProps) => {
  39. const { t } = useTranslation()
  40. const [isOpen, setIsOpen] = useState(false)
  41. const [view, setView] = useState(ViewType.date)
  42. const containerRef = useRef<HTMLDivElement>(null)
  43. const isInitial = useRef(true)
  44. const inputValue = useRef(value ? value.tz(timezone) : undefined).current
  45. const defaultValue = useRef(getDateWithTimezone({ timezone })).current
  46. const [currentDate, setCurrentDate] = useState(inputValue || defaultValue)
  47. const [selectedDate, setSelectedDate] = useState(inputValue)
  48. const [selectedMonth, setSelectedMonth] = useState((inputValue || defaultValue).month())
  49. const [selectedYear, setSelectedYear] = useState((inputValue || defaultValue).year())
  50. useEffect(() => {
  51. const handleClickOutside = (event: MouseEvent) => {
  52. if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
  53. setIsOpen(false)
  54. setView(ViewType.date)
  55. }
  56. }
  57. document.addEventListener('mousedown', handleClickOutside)
  58. return () => document.removeEventListener('mousedown', handleClickOutside)
  59. }, [])
  60. useEffect(() => {
  61. if (isInitial.current) {
  62. isInitial.current = false
  63. return
  64. }
  65. clearMonthMapCache()
  66. if (value) {
  67. const newValue = getDateWithTimezone({ date: value, timezone })
  68. setCurrentDate(newValue)
  69. setSelectedDate(newValue)
  70. onChange(newValue)
  71. }
  72. else {
  73. setCurrentDate(prev => getDateWithTimezone({ date: prev, timezone }))
  74. setSelectedDate(prev => prev ? getDateWithTimezone({ date: prev, timezone }) : undefined)
  75. }
  76. // eslint-disable-next-line react-hooks/exhaustive-deps
  77. }, [timezone])
  78. const handleClickTrigger = (e: React.MouseEvent) => {
  79. e.stopPropagation()
  80. if (isOpen) {
  81. setIsOpen(false)
  82. return
  83. }
  84. setView(ViewType.date)
  85. setIsOpen(true)
  86. if (value) {
  87. setCurrentDate(value)
  88. setSelectedDate(value)
  89. }
  90. }
  91. const handleClear = (e: React.MouseEvent) => {
  92. e.stopPropagation()
  93. setSelectedDate(undefined)
  94. if (!isOpen)
  95. onClear()
  96. }
  97. const days = useMemo(() => {
  98. return getDaysInMonth(currentDate)
  99. }, [currentDate])
  100. const handleClickNextMonth = useCallback(() => {
  101. setCurrentDate(currentDate.clone().add(1, 'month'))
  102. }, [currentDate])
  103. const handleClickPrevMonth = useCallback(() => {
  104. setCurrentDate(currentDate.clone().subtract(1, 'month'))
  105. }, [currentDate])
  106. const handleDateSelect = useCallback((day: Dayjs) => {
  107. const newDate = cloneTime(day, selectedDate || getDateWithTimezone({ timezone }))
  108. setCurrentDate(newDate)
  109. setSelectedDate(newDate)
  110. }, [selectedDate, timezone])
  111. const handleSelectCurrentDate = () => {
  112. const newDate = getDateWithTimezone({ timezone })
  113. setCurrentDate(newDate)
  114. setSelectedDate(newDate)
  115. onChange(newDate)
  116. setIsOpen(false)
  117. }
  118. const handleConfirmDate = () => {
  119. // debugger
  120. onChange(selectedDate ? selectedDate.tz(timezone) : undefined)
  121. setIsOpen(false)
  122. }
  123. const handleClickTimePicker = () => {
  124. if (view === ViewType.date) {
  125. setView(ViewType.time)
  126. return
  127. }
  128. if (view === ViewType.time)
  129. setView(ViewType.date)
  130. }
  131. const handleTimeSelect = (hour: string, minute: string, period: Period) => {
  132. const newTime = cloneTime(dayjs(), dayjs(`1/1/2000 ${hour}:${minute} ${period}`))
  133. setSelectedDate((prev) => {
  134. return prev ? cloneTime(prev, newTime) : newTime
  135. })
  136. }
  137. const handleSelectHour = useCallback((hour: string) => {
  138. const selectedTime = selectedDate || getDateWithTimezone({ timezone })
  139. handleTimeSelect(hour, selectedTime.minute().toString().padStart(2, '0'), selectedTime.format('A') as Period)
  140. }, [selectedDate, timezone])
  141. const handleSelectMinute = useCallback((minute: string) => {
  142. const selectedTime = selectedDate || getDateWithTimezone({ timezone })
  143. handleTimeSelect(getHourIn12Hour(selectedTime).toString().padStart(2, '0'), minute, selectedTime.format('A') as Period)
  144. }, [selectedDate, timezone])
  145. const handleSelectPeriod = useCallback((period: Period) => {
  146. const selectedTime = selectedDate || getDateWithTimezone({ timezone })
  147. handleTimeSelect(getHourIn12Hour(selectedTime).toString().padStart(2, '0'), selectedTime.minute().toString().padStart(2, '0'), period)
  148. }, [selectedDate, timezone])
  149. const handleOpenYearMonthPicker = () => {
  150. setSelectedMonth(currentDate.month())
  151. setSelectedYear(currentDate.year())
  152. setView(ViewType.yearMonth)
  153. }
  154. const handleCloseYearMonthPicker = useCallback(() => {
  155. setView(ViewType.date)
  156. }, [])
  157. const handleMonthSelect = useCallback((month: number) => {
  158. setSelectedMonth(month)
  159. }, [])
  160. const handleYearSelect = useCallback((year: number) => {
  161. setSelectedYear(year)
  162. }, [])
  163. const handleYearMonthCancel = useCallback(() => {
  164. setView(ViewType.date)
  165. }, [])
  166. const handleYearMonthConfirm = () => {
  167. setCurrentDate(prev => prev.clone().month(selectedMonth).year(selectedYear))
  168. setView(ViewType.date)
  169. }
  170. const timeFormat = needTimePicker ? 'MMMM D, YYYY hh:mm A' : 'MMMM D, YYYY'
  171. const displayValue = value?.format(timeFormat) || ''
  172. const displayTime = selectedDate?.format('hh:mm A') || '--:-- --'
  173. const placeholderDate = isOpen && selectedDate ? selectedDate.format(timeFormat) : (placeholder || t('time.defaultPlaceholder'))
  174. return (
  175. <PortalToFollowElem
  176. open={isOpen}
  177. onOpenChange={setIsOpen}
  178. placement='bottom-end'
  179. >
  180. <PortalToFollowElemTrigger className={triggerWrapClassName}>
  181. {renderTrigger ? (renderTrigger({
  182. value,
  183. selectedDate,
  184. isOpen,
  185. handleClear,
  186. handleClickTrigger,
  187. })) : (
  188. <div
  189. className='group flex w-[252px] cursor-pointer items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal px-2 py-1 hover:bg-state-base-hover-alt'
  190. onClick={handleClickTrigger}
  191. >
  192. <input
  193. className='system-xs-regular flex-1 cursor-pointer appearance-none truncate bg-transparent p-1
  194. text-components-input-text-filled outline-none placeholder:text-components-input-text-placeholder'
  195. readOnly
  196. value={isOpen ? '' : displayValue}
  197. placeholder={placeholderDate}
  198. />
  199. <RiCalendarLine className={cn(
  200. 'h-4 w-4 shrink-0 text-text-quaternary',
  201. isOpen ? 'text-text-secondary' : 'group-hover:text-text-secondary',
  202. (displayValue || (isOpen && selectedDate)) && 'group-hover:hidden',
  203. )} />
  204. <RiCloseCircleFill
  205. className={cn(
  206. 'hidden h-4 w-4 shrink-0 text-text-quaternary',
  207. (displayValue || (isOpen && selectedDate)) && 'hover:text-text-secondary group-hover:inline-block',
  208. )}
  209. onClick={handleClear}
  210. />
  211. </div>
  212. )}
  213. </PortalToFollowElemTrigger>
  214. <PortalToFollowElemContent className={popupZIndexClassname}>
  215. <div className='mt-1 w-[252px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg shadow-shadow-shadow-5'>
  216. {/* Header */}
  217. {view === ViewType.date ? (
  218. <DatePickerHeader
  219. handleOpenYearMonthPicker={handleOpenYearMonthPicker}
  220. currentDate={currentDate}
  221. onClickNextMonth={handleClickNextMonth}
  222. onClickPrevMonth={handleClickPrevMonth}
  223. />
  224. ) : view === ViewType.yearMonth ? (
  225. <YearAndMonthPickerHeader
  226. selectedYear={selectedYear}
  227. selectedMonth={selectedMonth}
  228. onClick={handleCloseYearMonthPicker}
  229. />
  230. ) : (
  231. <TimePickerHeader />
  232. )}
  233. {/* Content */}
  234. {
  235. view === ViewType.date ? (
  236. <Calendar
  237. days={days}
  238. selectedDate={selectedDate}
  239. onDateClick={handleDateSelect}
  240. />
  241. ) : view === ViewType.yearMonth ? (
  242. <YearAndMonthPickerOptions
  243. selectedMonth={selectedMonth}
  244. selectedYear={selectedYear}
  245. handleMonthSelect={handleMonthSelect}
  246. handleYearSelect={handleYearSelect}
  247. />
  248. ) : (
  249. <TimePickerOptions
  250. selectedTime={selectedDate}
  251. handleSelectHour={handleSelectHour}
  252. handleSelectMinute={handleSelectMinute}
  253. handleSelectPeriod={handleSelectPeriod}
  254. />
  255. )
  256. }
  257. {/* Footer */}
  258. {
  259. [ViewType.date, ViewType.time].includes(view) ? (
  260. <DatePickerFooter
  261. needTimePicker={needTimePicker}
  262. displayTime={displayTime}
  263. view={view}
  264. handleClickTimePicker={handleClickTimePicker}
  265. handleSelectCurrentDate={handleSelectCurrentDate}
  266. handleConfirmDate={handleConfirmDate}
  267. />
  268. ) : (
  269. <YearAndMonthPickerFooter
  270. handleYearMonthCancel={handleYearMonthCancel}
  271. handleYearMonthConfirm={handleYearMonthConfirm}
  272. />
  273. )
  274. }
  275. </div>
  276. </PortalToFollowElemContent>
  277. </PortalToFollowElem>
  278. )
  279. }
  280. export default DatePicker