foundation.ts 15 KB

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