foundation.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. const invalid = this.validateDates(dates);
  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. const inputValue = this.formatValue(dates);
  185. this.setState({
  186. value: dates,
  187. invalid,
  188. inputValue,
  189. } as any);
  190. }
  191. }
  192. handleFocus(e: any) {
  193. if (!this.getState('open')) {
  194. this.handlePanelOpen();
  195. }
  196. this._adapter.notifyFocus(e);
  197. }
  198. setPanel(open: boolean) {
  199. this._adapter.togglePanel(open);
  200. }
  201. destroy() {
  202. this._adapter.unregisterClickOutSide();
  203. }
  204. handlePanelOpen() {
  205. if (!this._isControlledComponent('open')) {
  206. this._adapter.registerClickOutSide();
  207. this.setPanel(true);
  208. }
  209. this._adapter.notifyOpenChange(true);
  210. }
  211. handlePanelClose(clickedOutside: boolean, e: any) {
  212. if (!this._isControlledComponent('open')) {
  213. this._adapter.unregisterClickOutSide();
  214. this.setPanel(false);
  215. }
  216. this._adapter.notifyOpenChange(false);
  217. this._adapter.notifyBlur(e);
  218. }
  219. /* istanbul ignore next */
  220. handleVisibleChange(visible: boolean) {
  221. if (!this._isControlledComponent('open')) {
  222. this._adapter.togglePanel(visible);
  223. }
  224. this._adapter.notifyOpenChange(visible);
  225. }
  226. handleInputChange(input: string) {
  227. this._adapter.setInputValue(input);
  228. const rangeSeparator = this.getProp('rangeSeparator');
  229. const inputValues = split(input, rangeSeparator);
  230. const formatToken = this.getValidFormat();
  231. /**
  232. * 如果输入的字符串不是formatLike则不进行下一步操作,以免输入过程被打断
  233. * 特殊case
  234. * - 清空时,input 为 '',此时需要跳过isTimeFormatLike判断
  235. *
  236. * If the input string is not formatLike, do not proceed to the next operation to avoid interruption of the input process
  237. * special case
  238. * -when emptying, the input is "', at this time you need to skip isTimeFormatLike judgment
  239. */
  240. if (input !== '' && inputValues.some(time => !isTimeFormatLike(time, formatToken))) {
  241. return;
  242. }
  243. const dates = this.parseInput(input);
  244. const invalid = this.validateDates(dates);
  245. const states: { invalid: boolean; value?: Date[] } = { invalid };
  246. const oldValue = this.getState('value');
  247. let value = transformToArray(oldValue);
  248. if (!invalid) {
  249. states.value = dates;
  250. value = [...dates];
  251. }
  252. if (!this._isControlledComponent('value')) {
  253. this.setState(states as any);
  254. }
  255. if (this._hasChanged(value, oldValue)) {
  256. this._notifyChange(value, input);
  257. }
  258. }
  259. /* istanbul ignore next */
  260. doValidate(args: string | Array<Date>) {
  261. if (typeof args === 'string') {
  262. return this.validateStr(args);
  263. } else if (Array.isArray(args)) {
  264. return this.validateDates(args);
  265. }
  266. return undefined;
  267. }
  268. validateStr(inputValue = '') {
  269. const dates = this.parseInput(inputValue);
  270. return this.validateDates(dates);
  271. }
  272. validateDates(dates: Array<Date> = []) {
  273. let invalid = dates.some(d => isNaN(Number(d)));
  274. if (!invalid) {
  275. invalid = dates.some(d =>
  276. this.isDisabledHMS({ hours: d.getHours(), minutes: d.getMinutes(), seconds: d.getSeconds() })
  277. );
  278. }
  279. return invalid;
  280. }
  281. handleInputBlur(e: any) {
  282. const invalid = this.getState('invalid');
  283. const inputValue = this.getState('inputValue');
  284. const value = this.getState('value');
  285. if (inputValue) {
  286. if (invalid) {
  287. this.setState({
  288. inputValue: this.formatValue(value),
  289. invalid: false,
  290. } as any);
  291. } else {
  292. this.setState({
  293. inputValue: this.formatValue(value),
  294. } as any);
  295. }
  296. } else {
  297. this.setState({
  298. inputValue: '',
  299. value: [],
  300. invalid: false,
  301. } as any);
  302. }
  303. }
  304. formatValue(dates: Date[]): string {
  305. const validFormat = this.getValidFormat();
  306. const rangeSeparator = this.getProp('rangeSeparator');
  307. const dateFnsLocale = this.getProp('dateFnsLocale');
  308. let _dates = dates;
  309. if (_dates && !Array.isArray(_dates)) {
  310. _dates = _dates[_dates];
  311. }
  312. if (_dates && Array.isArray(_dates)) {
  313. const result = _dates.map(date => {
  314. let str;
  315. if (isUndefined(date)) {
  316. str = '';
  317. } else {
  318. str = formatToString(date, validFormat, dateFnsLocale);
  319. }
  320. return str;
  321. });
  322. return result.join(rangeSeparator);
  323. }
  324. return undefined;
  325. }
  326. parseInput(str: string) {
  327. const validFormat = this.getValidFormat();
  328. const rangeSeparator = this.getProp('rangeSeparator');
  329. const dateFnsLocale = this.getProp('dateFnsLocale');
  330. if (str && typeof str === 'string') {
  331. return split(str, rangeSeparator).map(v => parseToDate(v, validFormat, dateFnsLocale));
  332. }
  333. return [];
  334. }
  335. parseValue(value: string | Date | Array<string | Date> = []) {
  336. const formatToken = this.getValidFormat();
  337. const dateFnsLocale = this.getProp('dateFnsLocale');
  338. let _value = value;
  339. if (!Array.isArray(_value)) {
  340. _value = _value ? [_value] : [];
  341. }
  342. if (Array.isArray(_value)) {
  343. return _value.map(v => parseToDate(v, formatToken, dateFnsLocale));
  344. }
  345. return [];
  346. }
  347. _notifyChange(value: Date[], inputValue: string) {
  348. let str: string | string[] = inputValue;
  349. let _value: Date | Date[] = value;
  350. const timeZone = this.getProp('timeZone');
  351. if (this._adapter.isRangePicker()) {
  352. const rangeSeparator = this.getProp('rangeSeparator');
  353. str = split(inputValue, rangeSeparator);
  354. } else {
  355. _value = Array.isArray(_value) ? _value[0] : _value;
  356. }
  357. if (this.isValidTimeZone(timeZone) && _value) {
  358. const formatToken = this.getValidFormat();
  359. if (Array.isArray(_value)) {
  360. _value = _value.map(v => zonedTimeToUtc(v, timeZone));
  361. str = _value.map(v => format(v, formatToken));
  362. } else {
  363. _value = zonedTimeToUtc(_value, timeZone);
  364. str = format(_value, formatToken);
  365. }
  366. }
  367. const onChangeWithDateFirst = this.getProp('onChangeWithDateFirst');
  368. if (onChangeWithDateFirst) {
  369. this._adapter.notifyChange(_value, str);
  370. } else {
  371. this._adapter.notifyChange(str, _value);
  372. }
  373. }
  374. _hasChanged(dates: Date[] = [], oldDates: Date[] = []) {
  375. const formatToken = this.getValidFormat();
  376. const dateFnsLocale = this.getProp('dateFnsLocale');
  377. return (
  378. dates.length !== oldDates.length ||
  379. dates.some((date, index) => {
  380. const oldDate = oldDates[index];
  381. if (
  382. isValid(date) &&
  383. isValid(oldDate) &&
  384. formatToString(date, formatToken, dateFnsLocale) === formatToString(oldDate, formatToken, dateFnsLocale)
  385. ) {
  386. return false;
  387. }
  388. return true;
  389. })
  390. );
  391. }
  392. }
  393. export default TimePickerFoundation;