foundation.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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, isUndefined } 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. return ['string', 'number'].includes(typeof timeZone) && timeZone !== '';
  77. }
  78. getDefaultFormatIfNeed(): string {
  79. if (this._isInProps('format')) {
  80. return this.getProp('format');
  81. } else if (this.getProp('use12Hours')) {
  82. return strings.DEFAULT_FORMAT_A;
  83. } else {
  84. return strings.DEFAULT_FORMAT;
  85. }
  86. }
  87. /**
  88. * User input value => save timestamp
  89. */
  90. initDataFromDefaultValue() {
  91. const defaultValue = this.getProp('defaultValue');
  92. let value = this.getProp('value');
  93. const timeZone = this.getProp('timeZone');
  94. const formatToken = this.getValidFormat();
  95. const { rangeSeparator, dateFnsLocale } = this.getProps();
  96. value = value || defaultValue;
  97. if (!Array.isArray(value)) {
  98. value = value ? [value] : [];
  99. }
  100. const parsedValues: Date[] = [];
  101. let invalid = false;
  102. (value as any[]).forEach(v => {
  103. const pv = parseToDate(v, formatToken, dateFnsLocale);
  104. if (!isNaN(pv.getTime())) {
  105. parsedValues.push(this.isValidTimeZone(timeZone) ? utcToZonedTime(pv, timeZone) : pv);
  106. }
  107. });
  108. const isAM = [true, false];
  109. parsedValues.map((item, idx)=>{
  110. isAM[idx]= getHours(item) < 12;
  111. });
  112. if (parsedValues.length === value.length) {
  113. value = parsedValues;
  114. } else {
  115. value = [];
  116. if (value.length) {
  117. invalid = true;
  118. }
  119. }
  120. let inputValue = '';
  121. if (!invalid) {
  122. inputValue = (value as any[]).map(v => formatToString(v, formatToken, dateFnsLocale)).join(rangeSeparator);
  123. }
  124. this.setState({
  125. isAM,
  126. value,
  127. inputValue,
  128. invalid,
  129. } as any);
  130. }
  131. getValidFormat(validFormat?: string) {
  132. let _format = validFormat;
  133. if (isNullOrUndefined(_format)) {
  134. _format = this.getDefaultFormatIfNeed();
  135. }
  136. if (typeof _format !== 'string') {
  137. _format = strings.DEFAULT_FORMAT;
  138. }
  139. return _format;
  140. }
  141. handlePanelChange(result: { isAM: boolean; value: string; timeStampValue: number }, index = 0) {
  142. // console.log(result, index);
  143. const formatToken = this.getValidFormat();
  144. const dateFnsLocale = this.getProp('dateFnsLocale');
  145. const oldValue: Date[] = this.getState('value');
  146. let isAM = this.getState('isAM');
  147. const value: Date[] = transformToArray(oldValue);
  148. isAM = transformToArray(isAM);
  149. if (result) {
  150. const panelIsAM = Boolean(result.isAM);
  151. const date = parseToDate(result.timeStampValue, formatToken, dateFnsLocale);
  152. value[index] = date;
  153. isAM[index] = panelIsAM;
  154. const inputValue = this.formatValue(value);
  155. if (this.getState('isAM')[index] !== result.isAM) {
  156. this.setState({ isAM } as any);
  157. }
  158. if (!this._isControlledComponent('value')) {
  159. const invalid = this.validateDates(value);
  160. this.setState({
  161. isAM,
  162. value,
  163. inputValue,
  164. invalid,
  165. } as any);
  166. }
  167. if (this._hasChanged(value, oldValue)) {
  168. this._notifyChange(value, inputValue);
  169. }
  170. }
  171. }
  172. refreshProps(props: any = {}) {
  173. const { value, timeZone, __prevTimeZone } = props;
  174. let dates = this.parseValue(value);
  175. const invalid = this.validateDates(dates);
  176. if (!invalid) {
  177. if (this.isValidTimeZone(timeZone)) {
  178. dates = dates.map(date =>
  179. utcToZonedTime(
  180. this.isValidTimeZone(__prevTimeZone) ? zonedTimeToUtc(date, __prevTimeZone) : date,
  181. timeZone
  182. )
  183. );
  184. }
  185. const inputValue = this.formatValue(dates);
  186. this.setState({
  187. value: dates,
  188. invalid,
  189. inputValue,
  190. } as any);
  191. }
  192. }
  193. handleFocus(e: any) {
  194. if (!this.getState('open')) {
  195. this.handlePanelOpen();
  196. }
  197. this._adapter.notifyFocus(e);
  198. }
  199. setPanel(open: boolean) {
  200. this._adapter.togglePanel(open);
  201. }
  202. destroy() {
  203. this._adapter.unregisterClickOutSide();
  204. }
  205. handlePanelOpen() {
  206. if (!this._isControlledComponent('open')) {
  207. this._adapter.registerClickOutSide();
  208. this.setPanel(true);
  209. }
  210. this._adapter.notifyOpenChange(true);
  211. }
  212. handlePanelClose(clickedOutside: boolean, e: any) {
  213. if (!this._isControlledComponent('open')) {
  214. this._adapter.unregisterClickOutSide();
  215. this.setPanel(false);
  216. }
  217. this._adapter.notifyOpenChange(false);
  218. this._adapter.notifyBlur(e);
  219. }
  220. /* istanbul ignore next */
  221. handleVisibleChange(visible: boolean) {
  222. if (!this._isControlledComponent('open')) {
  223. this._adapter.togglePanel(visible);
  224. }
  225. this._adapter.notifyOpenChange(visible);
  226. }
  227. handleInputChange(input: string) {
  228. this._adapter.setInputValue(input);
  229. const rangeSeparator = this.getProp('rangeSeparator');
  230. const inputValues = split(input, rangeSeparator);
  231. const formatToken = this.getValidFormat();
  232. /**
  233. * 如果输入的字符串不是formatLike则不进行下一步操作,以免输入过程被打断
  234. * 特殊case
  235. * - 清空时,input 为 '',此时需要跳过isTimeFormatLike判断
  236. *
  237. * If the input string is not formatLike, do not proceed to the next operation to avoid interruption of the input process
  238. * special case
  239. * -when emptying, the input is "', at this time you need to skip isTimeFormatLike judgment
  240. */
  241. if (input !== '' && inputValues.some(time => !isTimeFormatLike(time, formatToken))) {
  242. return;
  243. }
  244. const dates = this.parseInput(input);
  245. const invalid = this.validateDates(dates);
  246. const states: { invalid: boolean; value?: Date[] } = { invalid };
  247. const oldValue = this.getState('value');
  248. let value = transformToArray(oldValue);
  249. if (!invalid) {
  250. states.value = dates;
  251. value = [...dates];
  252. }
  253. if (!this._isControlledComponent('value')) {
  254. this.setState(states as any);
  255. }
  256. if (this._hasChanged(value, oldValue)) {
  257. this._notifyChange(value, input);
  258. }
  259. }
  260. /* istanbul ignore next */
  261. doValidate(args: string | Array<Date>) {
  262. if (typeof args === 'string') {
  263. return this.validateStr(args);
  264. } else if (Array.isArray(args)) {
  265. return this.validateDates(args);
  266. }
  267. return undefined;
  268. }
  269. validateStr(inputValue = '') {
  270. const dates = this.parseInput(inputValue);
  271. return this.validateDates(dates);
  272. }
  273. validateDates(dates: Array<Date> = []) {
  274. let invalid = dates.some(d => isNaN(Number(d)));
  275. if (!invalid) {
  276. invalid = dates.some(d =>
  277. this.isDisabledHMS({ hours: d.getHours(), minutes: d.getMinutes(), seconds: d.getSeconds() })
  278. );
  279. }
  280. return invalid;
  281. }
  282. handleInputBlur(e: any) {
  283. const invalid = this.getState('invalid');
  284. const inputValue = this.getState('inputValue');
  285. const value = this.getState('value');
  286. if (inputValue) {
  287. if (invalid) {
  288. this.setState({
  289. inputValue: this.formatValue(value),
  290. invalid: false,
  291. } as any);
  292. } else {
  293. this.setState({
  294. inputValue: this.formatValue(value),
  295. } as any);
  296. }
  297. } else {
  298. this.setState({
  299. inputValue: '',
  300. value: [],
  301. invalid: false,
  302. } as any);
  303. }
  304. }
  305. formatValue(dates: Date[]): string {
  306. const validFormat = this.getValidFormat();
  307. const rangeSeparator = this.getProp('rangeSeparator');
  308. const dateFnsLocale = this.getProp('dateFnsLocale');
  309. let _dates = dates;
  310. if (_dates && !Array.isArray(_dates)) {
  311. _dates = _dates[_dates];
  312. }
  313. if (_dates && Array.isArray(_dates)) {
  314. const result = _dates.map(date => {
  315. let str;
  316. if (isUndefined(date)) {
  317. str = '';
  318. } else {
  319. str = formatToString(date, validFormat, dateFnsLocale);
  320. }
  321. return str;
  322. });
  323. return result.join(rangeSeparator);
  324. }
  325. return undefined;
  326. }
  327. parseInput(str: string) {
  328. const validFormat = this.getValidFormat();
  329. const rangeSeparator = this.getProp('rangeSeparator');
  330. const dateFnsLocale = this.getProp('dateFnsLocale');
  331. if (str && typeof str === 'string') {
  332. return split(str, rangeSeparator).map(v => parseToDate(v, validFormat, dateFnsLocale));
  333. }
  334. return [];
  335. }
  336. parseValue(value: string | Date | Array<string | Date> = []) {
  337. const formatToken = this.getValidFormat();
  338. const dateFnsLocale = this.getProp('dateFnsLocale');
  339. let _value = value;
  340. if (!Array.isArray(_value)) {
  341. _value = _value ? [_value] : [];
  342. }
  343. if (Array.isArray(_value)) {
  344. return _value.map(v => parseToDate(v, formatToken, dateFnsLocale));
  345. }
  346. return [];
  347. }
  348. _notifyChange(value: Date[], inputValue: string) {
  349. let str: string | string[] = inputValue;
  350. let _value: Date | Date[] = value;
  351. const timeZone = this.getProp('timeZone');
  352. if (this._adapter.isRangePicker()) {
  353. const rangeSeparator = this.getProp('rangeSeparator');
  354. str = split(inputValue, rangeSeparator);
  355. } else {
  356. _value = Array.isArray(_value) ? _value[0] : _value;
  357. }
  358. if (this.isValidTimeZone(timeZone) && _value) {
  359. const formatToken = this.getValidFormat();
  360. if (Array.isArray(_value)) {
  361. _value = _value.map(v => zonedTimeToUtc(v, timeZone));
  362. str = _value.map(v => format(v, formatToken));
  363. } else {
  364. _value = zonedTimeToUtc(_value, timeZone);
  365. str = format(_value, formatToken);
  366. }
  367. }
  368. const onChangeWithDateFirst = this.getProp('onChangeWithDateFirst');
  369. if (onChangeWithDateFirst) {
  370. this._adapter.notifyChange(_value, str);
  371. } else {
  372. this._adapter.notifyChange(str, _value);
  373. }
  374. }
  375. _hasChanged(dates: Date[] = [], oldDates: Date[] = []) {
  376. const formatToken = this.getValidFormat();
  377. const dateFnsLocale = this.getProp('dateFnsLocale');
  378. return (
  379. dates.length !== oldDates.length ||
  380. dates.some((date, index) => {
  381. const oldDate = oldDates[index];
  382. if (
  383. isValid(date) &&
  384. isValid(oldDate) &&
  385. formatToString(date, formatToken, dateFnsLocale) === formatToString(oldDate, formatToken, dateFnsLocale)
  386. ) {
  387. return false;
  388. }
  389. return true;
  390. })
  391. );
  392. }
  393. }
  394. export default TimePickerFoundation;