foundation.ts 14 KB

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