yearAndMonth.tsx 12 KB

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