foundation.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /* eslint-disable max-len */
  2. import { strings } from './constants';
  3. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  4. import {
  5. formatToString,
  6. parseToDate,
  7. hourIsDisabled,
  8. minuteIsDisabled,
  9. secondIsDisabled,
  10. transformToArray,
  11. isTimeFormatLike
  12. } from './utils';
  13. import { split } from 'lodash';
  14. import { isValid, format, getHours } from 'date-fns';
  15. import { utcToZonedTime, zonedTimeToUtc } from '../utils/date-fns-extra';
  16. import isNullOrUndefined from '../utils/isNullOrUndefined';
  17. export type Position =
  18. | 'top'
  19. | 'topLeft'
  20. | 'topRight'
  21. | 'left'
  22. | 'leftTop'
  23. | 'leftBottom'
  24. | 'right'
  25. | 'rightTop'
  26. | 'rightBottom'
  27. | 'bottom'
  28. | 'bottomLeft'
  29. | 'bottomRight'
  30. | 'leftTopOver'
  31. | 'rightTopOver';
  32. export interface TimePickerAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> {
  33. togglePanel: (show: boolean) => void;
  34. registerClickOutSide: () => void;
  35. setInputValue: (inputValue: string, cb?: () => void) => void;
  36. unregisterClickOutSide: () => void;
  37. notifyOpenChange: (open: boolean) => void;
  38. notifyChange(value: Date | Date[], input: string | string[]): void;
  39. notifyChange(input: string | string[], value: Date | Date[]): void;
  40. notifyFocus: (e: any) => void;
  41. notifyBlur: (e: any) => void;
  42. isRangePicker: () => boolean;
  43. }
  44. // TODO: split, timePicker different components cannot share a foundation
  45. class TimePickerFoundation<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<TimePickerAdapter<P, S>, P, S> {
  46. constructor(adapter: TimePickerAdapter<P, S>) {
  47. super({ ...adapter });
  48. }
  49. init() {
  50. this.initDataFromDefaultValue();
  51. const open = this._isControlledComponent('open') ? this.getProp('open') : this.getProp('defaultOpen');
  52. if (open && !this._isControlledComponent('open')) {
  53. this._adapter.registerClickOutSide();
  54. }
  55. }
  56. getPosition(): Position {
  57. const position = this.getProp('position');
  58. const type = this.getProp('type') || strings.DEFAULT_TYPE;
  59. // rtl change default position
  60. const direction = this.getContext('direction');
  61. const rtlDirection = direction === 'rtl' ? 'bottomRight' : '';
  62. return position || rtlDirection || strings.DEFAULT_POSITION[type];
  63. }
  64. isDisabledHMS({ hours, minutes, seconds }: { hours: number; minutes: number; seconds: number }) {
  65. const { disabledHours, disabledMinutes, disabledSeconds } = this.getProps();
  66. const hDis = !isNullOrUndefined(hours) && hourIsDisabled(disabledHours, hours);
  67. const mDis = !isNullOrUndefined(hours) && !isNullOrUndefined(minutes) && minuteIsDisabled(disabledMinutes, hours, minutes);
  68. const sDis =
  69. !isNullOrUndefined(hours) &&
  70. !isNullOrUndefined(minutes) &&
  71. !isNullOrUndefined(seconds) &&
  72. secondIsDisabled(disabledSeconds, hours, minutes, seconds);
  73. return hDis || mDis || sDis;
  74. }
  75. isValidTimeZone(timeZone?: string | number) {
  76. const _timeZone = timeZone === undefined ? this.getProp('timeZone') : timeZone;
  77. return ['string', 'number'].includes(typeof _timeZone) && _timeZone !== '';
  78. }
  79. getDefaultFormatIfNeed(): string {
  80. if (this._isInProps('format')) {
  81. return this.getProp('format');
  82. } else if (this.getProp('use12Hours')) {
  83. return strings.DEFAULT_FORMAT_A;
  84. } else {
  85. return strings.DEFAULT_FORMAT;
  86. }
  87. }
  88. /**
  89. * User input value => save timestamp
  90. */
  91. initDataFromDefaultValue() {
  92. const defaultValue = this.getProp('defaultValue');
  93. let value = this.getProp('value');
  94. const timeZone = this.getProp('timeZone');
  95. const formatToken = this.getValidFormat();
  96. const { rangeSeparator, dateFnsLocale } = this.getProps();
  97. value = value || defaultValue;
  98. if (!Array.isArray(value)) {
  99. value = value ? [value] : [];
  100. }
  101. const parsedValues: Date[] = [];
  102. let invalid = false;
  103. (value as any[]).forEach(v => {
  104. const pv = parseToDate(v, formatToken, dateFnsLocale);
  105. if (!isNaN(pv.getTime())) {
  106. parsedValues.push(this.isValidTimeZone() ? utcToZonedTime(pv, timeZone) : pv);
  107. }
  108. });
  109. const isAM = [true, false];
  110. parsedValues.map((item, idx)=>{
  111. isAM[idx]= getHours(item) < 12;
  112. });
  113. if (parsedValues.length === value.length) {
  114. value = parsedValues;
  115. } else {
  116. value = [];
  117. if (value.length) {
  118. invalid = true;
  119. }
  120. }
  121. let inputValue = '';
  122. if (!invalid) {
  123. inputValue = (value as any[]).map(v => formatToString(v, formatToken, dateFnsLocale)).join(rangeSeparator);
  124. }
  125. this.setState({
  126. isAM,
  127. value,
  128. inputValue,
  129. invalid,
  130. } as any);
  131. }
  132. getValidFormat(validFormat?: string) {
  133. let _format = validFormat;
  134. if (isNullOrUndefined(_format)) {
  135. _format = this.getDefaultFormatIfNeed();
  136. }
  137. if (typeof _format !== 'string') {
  138. _format = strings.DEFAULT_FORMAT;
  139. }
  140. return _format;
  141. }
  142. handlePanelChange(result: { isAM: boolean; value: string; timeStampValue: number }, index = 0) {
  143. // console.log(result, index);
  144. const formatToken = this.getValidFormat();
  145. const dateFnsLocale = this.getProp('dateFnsLocale');
  146. const oldValue: Date[] = this.getState('value');
  147. let isAM = this.getState('isAM');
  148. const value: Date[] = transformToArray(oldValue);
  149. isAM = transformToArray(isAM);
  150. if (result) {
  151. const panelIsAM = Boolean(result.isAM);
  152. const date = parseToDate(result.timeStampValue, formatToken, dateFnsLocale);
  153. value[index] = date;
  154. isAM[index] = panelIsAM;
  155. const inputValue = this.formatValue(value);
  156. if (this.getState('isAM')[index] !== result.isAM){
  157. this.setState({ isAM } as any);
  158. }
  159. if (!this._isControlledComponent('value')) {
  160. const invalid = this.validateDates(value);
  161. this.setState({
  162. isAM,
  163. value,
  164. inputValue,
  165. invalid,
  166. } as any);
  167. }
  168. if (this._hasChanged(value, oldValue)) {
  169. this._notifyChange(value, inputValue);
  170. }
  171. }
  172. }
  173. refreshProps(props: any = {}) {
  174. const { value, timeZone, __prevTimeZone } = props;
  175. let dates = this.parseValue(value);
  176. const invalid = this.validateDates(dates);
  177. if (!invalid) {
  178. if (this.isValidTimeZone(timeZone)) {
  179. dates = dates.map(date =>
  180. utcToZonedTime(
  181. this.isValidTimeZone(__prevTimeZone) ? zonedTimeToUtc(date, __prevTimeZone) : date,
  182. timeZone
  183. )
  184. );
  185. }
  186. const inputValue = this.formatValue(dates);
  187. this.setState({
  188. value: dates,
  189. invalid,
  190. inputValue,
  191. } as any);
  192. }
  193. }
  194. handleFocus(e: any) {
  195. if (!this.getState('open')) {
  196. this.handlePanelOpen();
  197. }
  198. this._adapter.notifyFocus(e);
  199. }
  200. setPanel(open: boolean) {
  201. this._adapter.togglePanel(open);
  202. }
  203. destroy() {
  204. this._adapter.unregisterClickOutSide();
  205. }
  206. handlePanelOpen() {
  207. if (!this._isControlledComponent('open')) {
  208. this._adapter.registerClickOutSide();
  209. this.setPanel(true);
  210. }
  211. this._adapter.notifyOpenChange(true);
  212. }
  213. handlePanelClose(clickedOutside: boolean, e: any) {
  214. if (!this._isControlledComponent('open')) {
  215. this._adapter.unregisterClickOutSide();
  216. this.setPanel(false);
  217. }
  218. this._adapter.notifyOpenChange(false);
  219. this._adapter.notifyBlur(e);
  220. }
  221. /* istanbul ignore next */
  222. handleVisibleChange(visible: boolean) {
  223. if (!this._isControlledComponent('open')) {
  224. this._adapter.togglePanel(visible);
  225. }
  226. this._adapter.notifyOpenChange(visible);
  227. }
  228. handleInputChange(input: string) {
  229. this._adapter.setInputValue(input);
  230. const rangeSeparator = this.getProp('rangeSeparator');
  231. const inputValues = split(input, rangeSeparator);
  232. const formatToken = this.getValidFormat();
  233. /**
  234. * 如果输入的字符串不是formatLike则不进行下一步操作,以免输入过程被打断
  235. * 特殊case
  236. * - 清空时,input 为 '',此时需要跳过isTimeFormatLike判断
  237. *
  238. * If the input string is not formatLike, do not proceed to the next operation to avoid interruption of the input process
  239. * special case
  240. * -when emptying, the input is "', at this time you need to skip isTimeFormatLike judgment
  241. */
  242. if (input !== '' && inputValues.some(time => !isTimeFormatLike(time, formatToken))) {
  243. return;
  244. }
  245. const dates = this.parseInput(input);
  246. const invalid = this.validateDates(dates);
  247. const states: { invalid: boolean; value?: Date[] } = { invalid };
  248. const oldValue = this.getState('value');
  249. let value = transformToArray(oldValue);
  250. if (!invalid) {
  251. states.value = dates;
  252. value = [...dates];
  253. }
  254. if (!this._isControlledComponent('value')) {
  255. this.setState(states as any);
  256. }
  257. if (this._hasChanged(value, oldValue)) {
  258. this._notifyChange(value, input);
  259. }
  260. }
  261. /* istanbul ignore next */
  262. doValidate(args: string | Array<Date>) {
  263. if (typeof args === 'string') {
  264. return this.validateStr(args);
  265. } else if (Array.isArray(args)) {
  266. return this.validateDates(args);
  267. }
  268. return undefined;
  269. }
  270. validateStr(inputValue = '') {
  271. const dates = this.parseInput(inputValue);
  272. return this.validateDates(dates);
  273. }
  274. validateDates(dates: Array<Date> = []) {
  275. let invalid = dates.some(d => isNaN(Number(d)));
  276. if (!invalid) {
  277. invalid = dates.some(d =>
  278. this.isDisabledHMS({ hours: d.getHours(), minutes: d.getMinutes(), seconds: d.getSeconds() })
  279. );
  280. }
  281. return invalid;
  282. }
  283. handleInputBlur(e: any) {
  284. const invalid = this.getState('invalid');
  285. const inputValue = this.getState('inputValue');
  286. const value = this.getState('value');
  287. if (inputValue) {
  288. if (invalid) {
  289. this.setState({
  290. inputValue: this.formatValue(value),
  291. invalid: false,
  292. } as any);
  293. } else {
  294. this.setState({
  295. inputValue: this.formatValue(value),
  296. } as any);
  297. }
  298. } else {
  299. this.setState({
  300. inputValue: '',
  301. value: [],
  302. invalid: false,
  303. } as any);
  304. }
  305. }
  306. formatValue(dates: Date[]): string {
  307. const validFormat = this.getValidFormat();
  308. const rangeSeparator = this.getProp('rangeSeparator');
  309. const dateFnsLocale = this.getProp('dateFnsLocale');
  310. let _dates = dates;
  311. if (_dates && !Array.isArray(_dates)) {
  312. _dates = _dates[_dates];
  313. }
  314. if (_dates && Array.isArray(_dates)) {
  315. return _dates.map(date => formatToString(date, validFormat, dateFnsLocale)).join(rangeSeparator);
  316. }
  317. return undefined;
  318. }
  319. parseInput(str: string) {
  320. const validFormat = this.getValidFormat();
  321. const rangeSeparator = this.getProp('rangeSeparator');
  322. const dateFnsLocale = this.getProp('dateFnsLocale');
  323. if (str && typeof str === 'string') {
  324. return split(str, rangeSeparator).map(v => parseToDate(v, validFormat, dateFnsLocale));
  325. }
  326. return [];
  327. }
  328. parseValue(value: string | Date | Array<string | Date> = []) {
  329. const formatToken = this.getValidFormat();
  330. const dateFnsLocale = this.getProp('dateFnsLocale');
  331. let _value = value;
  332. if (!Array.isArray(_value)) {
  333. _value = _value ? [_value] : [];
  334. }
  335. if (Array.isArray(_value)) {
  336. return _value.map(v => parseToDate(v, formatToken, dateFnsLocale));
  337. }
  338. return [];
  339. }
  340. _notifyChange(value: Date[], inputValue: string) {
  341. let str: string | string[] = inputValue;
  342. let _value: Date | Date[] = value;
  343. const timeZone = this.getProp('timeZone');
  344. if (this._adapter.isRangePicker()) {
  345. const rangeSeparator = this.getProp('rangeSeparator');
  346. str = split(inputValue, rangeSeparator);
  347. } else {
  348. _value = Array.isArray(_value) ? _value[0] : _value;
  349. }
  350. if (this.isValidTimeZone() && _value) {
  351. const formatToken = this.getValidFormat();
  352. if (Array.isArray(_value)) {
  353. _value = _value.map(v => zonedTimeToUtc(v, timeZone));
  354. str = _value.map(v => format(v, formatToken));
  355. } else {
  356. _value = zonedTimeToUtc(_value, timeZone);
  357. str = format(_value, formatToken);
  358. }
  359. }
  360. const onChangeWithDateFirst = this.getProp('onChangeWithDateFirst');
  361. if (onChangeWithDateFirst) {
  362. this._adapter.notifyChange(_value, str);
  363. } else {
  364. this._adapter.notifyChange(str, _value);
  365. }
  366. }
  367. _hasChanged(dates: Date[] = [], oldDates: Date[] = []) {
  368. const formatToken = this.getValidFormat();
  369. const dateFnsLocale = this.getProp('dateFnsLocale');
  370. return (
  371. dates.length !== oldDates.length ||
  372. dates.some((date, index) => {
  373. const oldDate = oldDates[index];
  374. if (
  375. isValid(date) &&
  376. isValid(oldDate) &&
  377. formatToString(date, formatToken, dateFnsLocale) === formatToString(oldDate, formatToken, dateFnsLocale)
  378. ) {
  379. return false;
  380. }
  381. return true;
  382. })
  383. );
  384. }
  385. }
  386. export default TimePickerFoundation;