foundation.ts 14 KB

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