yearAndMonth.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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, yearAndMonthOpts } = 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. mode="normal"
  127. {...yearAndMonthOpts}
  128. />
  129. );
  130. }
  131. selectYear = (item: YearScrollItem) => {
  132. this.foundation.selectYear(item);
  133. };
  134. selectMonth = (item: MonthScrollItem) => {
  135. this.foundation.selectMonth(item);
  136. };
  137. reselect = () => {
  138. const refKeys = ['yearRef', 'monthRef'];
  139. refKeys.forEach(key => {
  140. const ref = this[key];
  141. if (ref && ref.current && ref.current.scrollToIndex) {
  142. ref.current.scrollToIndex();
  143. }
  144. });
  145. };
  146. renderColMonth() {
  147. const { months, currentMonth, currentYear } = this.state;
  148. const { locale, localeCode, monthCycled, disabledDate, yearAndMonthOpts } = this.props;
  149. console.log('yearAndMonthOpts', yearAndMonthOpts);
  150. let transform = (val: string) => val;
  151. const currentDate = setYear(Date.now(), currentYear);
  152. if (localeCode === 'zh-CN' || localeCode === 'zh-TW') {
  153. // Only Chinese needs to add [month] after the selected month
  154. transform = val => `${val}月`;
  155. }
  156. // i18n
  157. const list: MonthScrollItem[] = months.map(({ value, month }) => ({
  158. month,
  159. disabled: disabledDate(setMonth(currentDate, month - 1)),
  160. value: locale.fullMonths[value], // Actual rendered text
  161. }));
  162. const selectedIndex = list.findIndex(item => item.month === currentMonth);
  163. return (
  164. <ScrollItem
  165. ref={this.monthRef}
  166. cycled={monthCycled}
  167. list={list}
  168. transform={transform}
  169. selectedIndex={selectedIndex}
  170. type="month"
  171. onSelect={this.selectMonth}
  172. mode='normal'
  173. {...yearAndMonthOpts}
  174. />
  175. );
  176. }
  177. backToMain: React.MouseEventHandler<HTMLButtonElement> = e => {
  178. e.nativeEvent.stopImmediatePropagation();
  179. this.foundation.backToMain();
  180. };
  181. render() {
  182. const { locale, noBackBtn, density, presetPosition, renderQuickControls, renderDateInput } = this.props;
  183. const prefix = `${prefixCls}-yearmonth-header`;
  184. // i18n
  185. const selectDateText = locale.selectDate;
  186. const iconSize = density === 'compact' ? 'default' : 'large';
  187. const buttonSize = density === 'compact' ? 'small' : 'default';
  188. return (
  189. <React.Fragment>
  190. {noBackBtn ? null : (
  191. <div className={prefix}>
  192. <IconButton
  193. noHorizontalPadding={false}
  194. icon={<IconChevronLeft aria-hidden size={iconSize} />}
  195. size={buttonSize}
  196. onClick={this.backToMain}
  197. >
  198. <span>{selectDateText}</span>
  199. </IconButton>
  200. </div>
  201. )}
  202. {
  203. presetPosition ? (
  204. <div style={{ display: 'flex' }}>
  205. {presetPosition === "left" && renderQuickControls}
  206. <div>
  207. {renderDateInput}
  208. <ScrollList>
  209. {this.renderColYear()}
  210. {this.renderColMonth()}
  211. </ScrollList>
  212. </div>
  213. {presetPosition === "right" && renderQuickControls}
  214. </div>
  215. ) :
  216. <>
  217. {renderDateInput}
  218. <ScrollList>
  219. {this.renderColYear()}
  220. {this.renderColMonth()}
  221. </ScrollList>
  222. </>
  223. }
  224. </React.Fragment>
  225. );
  226. }
  227. }
  228. export default YearAndMonth;