yearAndMonth.tsx 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /* eslint-disable max-len */
  2. import React from 'react';
  3. import PropTypes from 'prop-types';
  4. import YearAndMonthFoundation, { MonthScrollItem, YearAndMonthAdapter, YearAndMonthFoundationProps, YearAndMonthFoundationState, YearScrollItem } from '@douyinfe/semi-foundation/datePicker/yearAndMonthFoundation';
  5. import BaseComponent, { BaseProps } from '../_base/baseComponent';
  6. import ScrollList from '../scrollList/index';
  7. import ScrollItem from '../scrollList/scrollItem';
  8. import { getYears } from '@douyinfe/semi-foundation/datePicker/_utils/index';
  9. import isNullOrUndefined from '@douyinfe/semi-foundation/utils/isNullOrUndefined';
  10. import IconButton from '../iconButton';
  11. import { IconChevronLeft } from '@douyinfe/semi-icons';
  12. import { BASE_CLASS_PREFIX } from '@douyinfe/semi-foundation/base/constants';
  13. import { noop, stubFalse } from 'lodash';
  14. import { setYear, setMonth } from 'date-fns';
  15. import { Locale } from '../locale/interface';
  16. import { strings } from '@douyinfe/semi-foundation/datePicker/constants';
  17. const prefixCls = `${BASE_CLASS_PREFIX}-datepicker`;
  18. export interface YearAndMonthProps extends YearAndMonthFoundationProps, BaseProps {
  19. locale?: Locale['DatePicker'];
  20. }
  21. export type YearAndMonthState = YearAndMonthFoundationState;
  22. class YearAndMonth extends BaseComponent<YearAndMonthProps, YearAndMonthState> {
  23. static propTypes = {
  24. currentYear: PropTypes.number,
  25. currentMonth: PropTypes.number,
  26. onSelect: PropTypes.func,
  27. locale: PropTypes.object,
  28. localeCode: PropTypes.string,
  29. monthCycled: PropTypes.bool,
  30. yearCycled: PropTypes.bool,
  31. noBackBtn: PropTypes.bool,
  32. disabledDate: PropTypes.func,
  33. density: PropTypes.string,
  34. presetPosition: PropTypes.oneOf(strings.PRESET_POSITION_SET),
  35. renderQuickControls: PropTypes.node,
  36. renderDateInput: PropTypes.node
  37. };
  38. static defaultProps = {
  39. disabledDate: stubFalse,
  40. monthCycled: false,
  41. yearCycled: false,
  42. noBackBtn: false,
  43. onSelect: noop,
  44. };
  45. foundation: YearAndMonthFoundation;
  46. yearRef: React.RefObject<ScrollItem<YearScrollItem>>;
  47. monthRef: React.RefObject<ScrollItem<MonthScrollItem>>;
  48. constructor(props: YearAndMonthProps) {
  49. super(props);
  50. const now = new Date();
  51. let { currentYear, currentMonth } = props;
  52. currentYear = currentYear || now.getFullYear();
  53. currentMonth = currentMonth || now.getMonth() + 1;
  54. this.state = {
  55. years: getYears().map(year => ({
  56. value: year,
  57. year,
  58. })),
  59. months: Array(12)
  60. .fill(0)
  61. .map((v, idx) => ({
  62. value: idx + 1,
  63. month: idx + 1,
  64. })),
  65. currentYear,
  66. currentMonth,
  67. };
  68. this.yearRef = React.createRef();
  69. this.monthRef = React.createRef();
  70. this.foundation = new YearAndMonthFoundation(this.adapter);
  71. }
  72. get adapter(): YearAndMonthAdapter {
  73. return {
  74. ...super.adapter,
  75. // updateYears: years => this.setState({ years }),
  76. // updateMonths: months => this.setState({ months }),
  77. setCurrentYear: currentYear => this.setState({ currentYear }),
  78. setCurrentMonth: currentMonth => this.setState({ currentMonth }),
  79. notifySelectYear: year =>
  80. this.props.onSelect({
  81. currentMonth: this.state.currentMonth,
  82. currentYear: year,
  83. }),
  84. notifySelectMonth: month =>
  85. this.props.onSelect({
  86. currentYear: this.state.currentYear,
  87. currentMonth: month,
  88. }),
  89. notifyBackToMain: () => this.props.onBackToMain(),
  90. };
  91. }
  92. static getDerivedStateFromProps(props: YearAndMonthProps, state: YearAndMonthState) {
  93. const willUpdateStates: Partial<YearAndMonthState> = {};
  94. const now = new Date();
  95. if (!isNullOrUndefined(props.currentMonth) && props.currentMonth !== state.currentMonth && props.currentMonth !== 0) {
  96. willUpdateStates.currentMonth = props.currentMonth || now.getMonth() + 1;
  97. }
  98. if (isNullOrUndefined(props.currentYear) && props.currentYear !== state.currentYear && props.currentYear !== 0) {
  99. willUpdateStates.currentYear = props.currentYear || now.getFullYear();
  100. }
  101. return willUpdateStates;
  102. }
  103. renderColYear() {
  104. const { years, currentYear, currentMonth } = this.state;
  105. const { disabledDate, localeCode, yearCycled } = this.props;
  106. const currentDate = setMonth(Date.now(), currentMonth - 1);
  107. const list: any[] = years.map(({ value, year }) => ({
  108. year,
  109. value, // Actual rendered text
  110. disabled: disabledDate(setYear(currentDate, year)),
  111. }));
  112. let transform = (val: string) => val;
  113. if (localeCode === 'zh-CN' || localeCode === 'zh-TW') {
  114. // Only Chinese needs to add [year] after the selected year
  115. transform = val => `${val }年`;
  116. }
  117. return (
  118. <ScrollItem
  119. ref={this.yearRef}
  120. cycled={yearCycled}
  121. list={list}
  122. transform={transform}
  123. selectedIndex={years.findIndex(item => item.value === currentYear)}
  124. type="year"
  125. onSelect={this.selectYear}
  126. />
  127. );
  128. }
  129. selectYear = (item: YearScrollItem) => {
  130. this.foundation.selectYear(item);
  131. };
  132. selectMonth = (item: MonthScrollItem) => {
  133. this.foundation.selectMonth(item);
  134. };
  135. reselect = () => {
  136. const refKeys = ['yearRef', 'monthRef'];
  137. refKeys.forEach(key => {
  138. const ref = this[key];
  139. if (ref && ref.current && ref.current.scrollToIndex) {
  140. ref.current.scrollToIndex();
  141. }
  142. });
  143. };
  144. renderColMonth() {
  145. const { months, currentMonth, currentYear } = this.state;
  146. const { locale, localeCode, monthCycled, disabledDate } = this.props;
  147. let transform = (val: string) => val;
  148. const currentDate = setYear(Date.now(), currentYear);
  149. if (localeCode === 'zh-CN' || localeCode === 'zh-TW') {
  150. // Only Chinese needs to add [month] after the selected month
  151. transform = val => `${val }月`;
  152. }
  153. // i18n
  154. const list: MonthScrollItem[] = months.map(({ value, month }) => ({
  155. month,
  156. disabled: disabledDate(setMonth(currentDate, month - 1)),
  157. value: locale.fullMonths[value], // Actual rendered text
  158. }));
  159. const selectedIndex = list.findIndex(item => item.month === currentMonth);
  160. return (
  161. <ScrollItem
  162. ref={this.monthRef}
  163. cycled={monthCycled}
  164. list={list}
  165. transform={transform}
  166. selectedIndex={selectedIndex}
  167. type="month"
  168. onSelect={this.selectMonth}
  169. />
  170. );
  171. }
  172. backToMain: React.MouseEventHandler<HTMLButtonElement> = e => {
  173. e.nativeEvent.stopImmediatePropagation();
  174. this.foundation.backToMain();
  175. };
  176. render() {
  177. const { locale, noBackBtn, density, presetPosition, renderQuickControls, renderDateInput } = this.props;
  178. const prefix = `${prefixCls}-yearmonth-header`;
  179. // i18n
  180. const selectDateText = locale.selectDate;
  181. const iconSize = density === 'compact' ? 'default' : 'large';
  182. const buttonSize = density === 'compact' ? 'small' : 'default';
  183. return (
  184. <React.Fragment>
  185. {noBackBtn ? null : (
  186. <div className={prefix}>
  187. <IconButton
  188. noHorizontalPadding={false}
  189. icon={<IconChevronLeft aria-hidden size={iconSize} />}
  190. size={buttonSize}
  191. onClick={this.backToMain}
  192. >
  193. <span>{selectDateText}</span>
  194. </IconButton>
  195. </div>
  196. )}
  197. {
  198. presetPosition ? (
  199. <div style={{ display: 'flex' }}>
  200. {presetPosition === "left" && renderQuickControls}
  201. <div>
  202. {renderDateInput}
  203. <ScrollList>
  204. {this.renderColYear()}
  205. {this.renderColMonth()}
  206. </ScrollList>
  207. </div>
  208. {presetPosition === "right" && renderQuickControls}
  209. </div>
  210. ) :
  211. <>
  212. {renderDateInput}
  213. <ScrollList>
  214. {this.renderColYear()}
  215. {this.renderColMonth()}
  216. </ScrollList>
  217. </>
  218. }
  219. </React.Fragment>
  220. );
  221. }
  222. }
  223. export default YearAndMonth;