UNPKG

@gizwits/vantui

Version:

机智云组件库

510 lines (508 loc) 20.4 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; var _excluded = ["title", "color", "show", "formatter", "confirmText", "rangePrompt", "defaultDate", "allowSameDay", "type", "confirmDisabledText", "minDate", "maxDate", "position", "rowHeight", "round", "poppable", "showMark", "showTitle", "showConfirm", "showSubtitle", "safeAreaInsetBottom", "closeOnClickOverlay", "showRangePrompt", "maxRange", "onClose", "onOpen", "onClosed", "onOpened", "onConfirm", "onSelect", "firstDayOfWeek", "overRange", "onUnselect", "onClickSubtitle", "renderTitle", "renderFooter", "className", "style"]; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } import { View, ScrollView } from '@tarojs/components'; import { useState, useEffect, useCallback, useRef, useLayoutEffect, forwardRef, useImperativeHandle } from 'react'; import { getCurrentPages, createIntersectionObserver } from '@tarojs/taro'; import * as utils from '../wxs/utils'; import Toast from '../toast/toast'; import { requestAnimationFrame } from '../common/utils'; import VanToast from '../toast/index'; import VanPopup from '../popup/index'; import VanButton from '../button/index'; import { ROW_HEIGHT, getPrevDay, getNextDay, getToday, compareDay, copyDates, calcDateNum, formatMonthTitle, compareMonth, getMonths, getDayByOffset } from './utils'; import * as computed from './wxs'; import Month from './components/month/index'; import Header from './components/header/index'; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; import { Fragment as _Fragment } from "react/jsx-runtime"; var initialMinDate = getToday().getTime(); var init = 0; var initialMaxDate = function () { var now = getToday(); return new Date(now.getFullYear(), now.getMonth() + 6, now.getDate()).getTime(); }(); function Index(props, ref) { var _props$title = props.title, title = _props$title === void 0 ? '日期选择' : _props$title, color = props.color, show = props.show, formatter = props.formatter, _props$confirmText = props.confirmText, confirmText = _props$confirmText === void 0 ? '确定' : _props$confirmText, rangePrompt = props.rangePrompt, defaultDate = props.defaultDate, allowSameDay = props.allowSameDay, _props$type = props.type, type = _props$type === void 0 ? 'single' : _props$type, _props$confirmDisable = props.confirmDisabledText, confirmDisabledText = _props$confirmDisable === void 0 ? '确定' : _props$confirmDisable, _props$minDate = props.minDate, minDate = _props$minDate === void 0 ? initialMinDate : _props$minDate, _props$maxDate = props.maxDate, maxDate = _props$maxDate === void 0 ? initialMaxDate : _props$maxDate, _props$position = props.position, position = _props$position === void 0 ? 'bottom' : _props$position, _props$rowHeight = props.rowHeight, rowHeight = _props$rowHeight === void 0 ? ROW_HEIGHT : _props$rowHeight, _props$round = props.round, round = _props$round === void 0 ? true : _props$round, _props$poppable = props.poppable, poppable = _props$poppable === void 0 ? true : _props$poppable, _props$showMark = props.showMark, showMark = _props$showMark === void 0 ? true : _props$showMark, _props$showTitle = props.showTitle, showTitle = _props$showTitle === void 0 ? true : _props$showTitle, _props$showConfirm = props.showConfirm, showConfirm = _props$showConfirm === void 0 ? true : _props$showConfirm, _props$showSubtitle = props.showSubtitle, showSubtitle = _props$showSubtitle === void 0 ? true : _props$showSubtitle, _props$safeAreaInsetB = props.safeAreaInsetBottom, safeAreaInsetBottom = _props$safeAreaInsetB === void 0 ? true : _props$safeAreaInsetB, _props$closeOnClickOv = props.closeOnClickOverlay, closeOnClickOverlay = _props$closeOnClickOv === void 0 ? true : _props$closeOnClickOv, _props$showRangePromp = props.showRangePrompt, showRangePrompt = _props$showRangePromp === void 0 ? true : _props$showRangePromp, maxRange = props.maxRange, onClose = props.onClose, onOpen = props.onOpen, onClosed = props.onClosed, onOpened = props.onOpened, onConfirm = props.onConfirm, onSelect = props.onSelect, _props$firstDayOfWeek = props.firstDayOfWeek, firstDayOfWeek = _props$firstDayOfWeek === void 0 ? 0 : _props$firstDayOfWeek, overRange = props.overRange, onUnselect = props.onUnselect, _onClickSubtitle = props.onClickSubtitle, renderTitle = props.renderTitle, renderFooter = props.renderFooter, className = props.className, style = props.style, others = _objectWithoutProperties(props, _excluded); var _useState = useState(''), _useState2 = _slicedToArray(_useState, 2), subtitle = _useState2[0], setSubtitle = _useState2[1]; var _useState3 = useState(), _useState4 = _slicedToArray(_useState3, 2), currentDate = _useState4[0], setCurrentDate = _useState4[1]; var _useState5 = useState(''), _useState6 = _slicedToArray(_useState5, 2), scrollIntoView = _useState6[0], setScrollIntoView = _useState6[1]; var contentObserver = useRef(); var _useState7 = useState(0), _useState8 = _slicedToArray(_useState7, 2), compIndex = _useState8[0], setComindex = _useState8[1]; useEffect(function () { setComindex(init++); }, []); var limitDateRange = useCallback(function (date) { var minDateD = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var maxDateD = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; minDateD = minDateD || minDate; maxDateD = maxDateD || maxDate; if (compareDay(date, minDateD) === -1) { return minDateD; } if (compareDay(date, maxDateD) === 1) { return maxDateD; } return date; }, [maxDate, minDate]); var getInitialDate = useCallback(function () { var defaultDate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var now = getToday().getTime(); if (type === 'range') { if (!Array.isArray(defaultDate)) { defaultDate = []; } var _ref = defaultDate || [], _ref2 = _slicedToArray(_ref, 2), startDay = _ref2[0], endDay = _ref2[1]; var start = limitDateRange(startDay || now, minDate, getPrevDay(new Date(maxDate)).getTime()); var end = limitDateRange(endDay || now, getNextDay(new Date(minDate)).getTime()); return [start, end]; } if (type === 'multiple') { if (Array.isArray(defaultDate)) { return defaultDate.map(function (date) { return limitDateRange(date); }); } return [limitDateRange(now)]; } if (!defaultDate || Array.isArray(defaultDate)) { defaultDate = now; } return limitDateRange(defaultDate); }, [limitDateRange, maxDate, minDate, type]); var scrollIntoViewFn = useCallback(function () { requestAnimationFrame(function () { if (!currentDate) return; var targetDate = type === 'single' ? currentDate : currentDate[0]; var displayed = show || !poppable; if (!targetDate || !displayed) { return; } var months = getMonths(minDate, maxDate); months.some(function (month) { if (compareMonth(month, targetDate) === 0) { var id = "month".concat(formatMonthTitle(month).replace('年', '_').replace('月', '-')); setScrollIntoView(id); if (process.env.TARO_ENV === 'h5') { var _document$getElementB; (_document$getElementB = document.getElementById(id)) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.scrollIntoView(); } return true; } return false; }); }); }, [currentDate, maxDate, minDate, poppable, show, type]); var reset = useCallback(function () { setCurrentDate(getInitialDate(defaultDate)); scrollIntoViewFn(); }, [getInitialDate, scrollIntoViewFn, defaultDate]); var initRectH5 = useCallback(function () { if (contentObserver.current != null) { contentObserver.current.disconnect(); } var contentObserver_ = new IntersectionObserver(function (res) { for (var i = 0; i < res.length; i++) { if (res[i].intersectionRatio > 0.6) { var item = res[i].target.id.replace('month', '').replace('_', '年').replace('-', '月'); if (item && item !== subtitle) setSubtitle(item); } } }, { threshold: [0.6] // root: document.getElementsByClassName('van-calendar__body')[0], }); contentObserver.current = contentObserver_; var targets = document.getElementsByClassName('month'); if (targets.length) { for (var i = 0; i < targets.length; i++) { contentObserver.current.observe(targets[i]); } } }, [subtitle]); var initRect = useCallback(function () { if (process.env.TARO_ENV === 'h5') { return initRectH5(); } if (contentObserver.current != null) { contentObserver.current.disconnect(); } var pages = getCurrentPages(); var curePage = pages[pages.length - 1]; var _createIntersectionObserver = curePage.createIntersectionObserver; if (process.env.TARO_ENV === 'alipay') { _createIntersectionObserver = createIntersectionObserver; } var contentObserver_ = _createIntersectionObserver({ thresholds: [0.5, 0.8, 1], observeAll: true, selectAll: true }); contentObserver.current = contentObserver_; contentObserver.current.relativeTo(".van-calendar__body".concat(compIndex)); contentObserver.current.observe('.month', function (res) { if (res.intersectionRatio) { var item = res.id.replace('month', '').replace('_', '年').replace('-', '月'); if (item && item !== subtitle) setSubtitle(item); } }); }, [compIndex, initRectH5, subtitle]); var emit = useCallback(function (date) { var getTime = function getTime(date) { return date instanceof Date ? date.getTime() : date; }; setCurrentDate(Array.isArray(date) ? date.map(getTime) : getTime(date)); var e = { detail: { value: copyDates(date) } }; if (onSelect) onSelect(e); }, [onSelect]); var checkRange = useCallback(function (date) { if (maxRange && calcDateNum(date) > maxRange) { if (showRangePrompt) { Toast({ // duration: 0, message: rangePrompt || "\u9009\u62E9\u5929\u6570\u4E0D\u80FD\u8D85\u8FC7 ".concat(maxRange, " \u5929") }); } if (overRange) overRange(); return false; } return true; }, [maxRange, overRange, rangePrompt, showRangePrompt]); // eslint-disable-next-line react-hooks/exhaustive-deps function select(date, complete) { if (Array.isArray(date)) { date = date.filter(function (d) { return !!d; }).map(function (item) { return typeof item === 'number' ? new Date(item) : item; }); } if (complete && type === 'range') { var valid = checkRange(date); if (!valid) { // auto selected to max range if showConfirm if (showConfirm) { emit([date[0], getDayByOffset(date[0], (maxRange || 0) - 1)]); } else { emit(date); } return; } } emit(date); if (complete && !showConfirm) { onConfirm_(null, date); } } var unselect = useCallback(function (dateArray) { var date = dateArray[0]; if (date) { var e = { detail: { value: copyDates(date) } }; if (onUnselect) onUnselect(e); } }, [onUnselect]); var onClickDay = useCallback(function (event) { var date = event.date; var currentDate_ = JSON.parse(JSON.stringify(currentDate)); if (type === 'range') { var _currentDate_ = _slicedToArray(currentDate_, 2), startDay = _currentDate_[0], endDay = _currentDate_[1]; if (startDay && !endDay) { var compareToStart = compareDay(date, startDay); if (compareToStart === 1) { select([startDay, date], true); } else if (compareToStart === -1) { select([date, null]); } else if (allowSameDay) { select([date, date]); } } else { select([date, null]); } } else if (type === 'multiple') { var selectedIndex; var selected = currentDate_.some(function (dateItem, index) { var equal = compareDay(dateItem, date) === 0; if (equal) { selectedIndex = index; } return equal; }); if (selected) { var cancelDate = currentDate_.splice(selectedIndex, 1); setCurrentDate(currentDate_); unselect(cancelDate); } else { select([].concat(_toConsumableArray(currentDate_), [date])); } } else { select(date, true); } }, [allowSameDay, currentDate, select, type, unselect]); var onConfirm_ = useCallback(function (_, date) { if (type === 'range' && !checkRange(currentDate)) { return; } var e = { detail: { value: date || copyDates(currentDate) } }; if (onConfirm) onConfirm(e); }, [checkRange, currentDate, onConfirm, type]); useLayoutEffect(function () { if (defaultDate) { setCurrentDate(getInitialDate(defaultDate || new Date().getTime())); } }, // eslint-disable-next-line react-hooks/exhaustive-deps []); useEffect(function () { if (show || !poppable) { requestAnimationFrame(function () { initRect(); setTimeout(function () { scrollIntoViewFn(); }, 66); }); } }, // eslint-disable-next-line react-hooks/exhaustive-deps [poppable, show]); useEffect(function () { reset(); }, // eslint-disable-next-line react-hooks/exhaustive-deps [type]); useImperativeHandle(ref, function () { return { reset: reset, getSelectedDate: function getSelectedDate() { return currentDate; } }; }); return /*#__PURE__*/_jsxs(View, { children: [poppable ? /*#__PURE__*/_jsx(VanPopup, { className: 'van-calendar__popup--' + position, show: show, round: round, position: position, closeable: showTitle || showSubtitle, closeOnClickOverlay: closeOnClickOverlay, onEnter: onOpen, onClose: onClose, onAfterEnter: onOpened, onAfterLeave: onClosed, children: /*#__PURE__*/_jsxs(View, _objectSpread(_objectSpread({ className: "van-calendar ".concat(className || ''), style: utils.style([style]) }, others), {}, { children: [/*#__PURE__*/_jsx(Header, { title: title, showTitle: showTitle, subtitle: subtitle, showSubtitle: showSubtitle, firstDayOfWeek: firstDayOfWeek, onClickSubtitle: function onClickSubtitle() { if (_onClickSubtitle) _onClickSubtitle; }, renderTitle: renderTitle }), /*#__PURE__*/_jsx(ScrollView, { className: "van-calendar__body van-calendar__body".concat(compIndex), scrollY: true, scrollIntoView: scrollIntoView, children: computed.getMonths(minDate, maxDate).map(function (item, index) { return /*#__PURE__*/_jsx(Month, { id: "month".concat(formatMonthTitle(item).replace('年', '_').replace('月', '-')), className: "month", date: item, type: type, color: color, minDate: minDate, maxDate: maxDate, showMark: showMark, formatter: formatter, rowHeight: rowHeight, currentDate: currentDate, showSubtitle: showSubtitle, allowSameDay: allowSameDay, showMonthTitle: index !== 0 || !showSubtitle, firstDayOfWeek: firstDayOfWeek, onClick: onClickDay }, "van-calendar-month___".concat(index)); }) }), /*#__PURE__*/_jsx(View, { className: utils.bem('calendar__footer', { safeAreaInsetBottom: safeAreaInsetBottom }), children: renderFooter }), /*#__PURE__*/_jsx(View, { className: utils.bem('calendar__footer', { safeAreaInsetBottom: safeAreaInsetBottom }), children: showConfirm && /*#__PURE__*/_jsx(VanButton, { block: true, type: "danger", color: color, className: "van-calendar__confirm", disabled: computed.getButtonDisabled(type, currentDate) // nativeType="text" , onClick: onConfirm_, children: computed.getButtonDisabled(type, currentDate) ? confirmDisabledText : confirmText }) })] })) }) : /*#__PURE__*/_jsxs(View, _objectSpread(_objectSpread({ className: "van-calendar ".concat(className || ''), style: utils.style([style]) }, others), {}, { children: [/*#__PURE__*/_jsx(Header, { title: title, showTitle: showTitle, subtitle: subtitle, showSubtitle: showSubtitle, firstDayOfWeek: firstDayOfWeek, onClickSubtitle: _onClickSubtitle, renderTitle: /*#__PURE__*/_jsx(_Fragment, { children: renderTitle }) }), /*#__PURE__*/_jsx(ScrollView, { className: "van-calendar__body van-calendar__body".concat(compIndex), scrollY: true, scrollIntoView: scrollIntoView, children: computed.getMonths(minDate, maxDate).map(function (item, index) { return /*#__PURE__*/_jsx(Month, { id: "month".concat(formatMonthTitle(item).replace('年', '_').replace('月', '-')), className: "month", date: item, type: type, color: color, minDate: minDate, maxDate: maxDate, showMark: showMark, formatter: formatter, rowHeight: rowHeight, currentDate: currentDate, showSubtitle: showSubtitle, allowSameDay: allowSameDay, showMonthTitle: index !== 0 || !showSubtitle, firstDayOfWeek: firstDayOfWeek, onClick: onClickDay }, "van-calendar-month___".concat(index)); }) }), /*#__PURE__*/_jsx(View, { className: utils.bem('calendar__footer', { safeAreaInsetBottom: safeAreaInsetBottom }), children: renderFooter }), /*#__PURE__*/_jsx(View, { className: utils.bem('calendar__footer', { safeAreaInsetBottom: safeAreaInsetBottom }), children: showConfirm && /*#__PURE__*/_jsx(VanButton, { block: true, type: "danger", color: color, className: "van-calendar__confirm", disabled: computed.getButtonDisabled(type, currentDate) // nativeType="text" , onClick: onConfirm_, children: computed.getButtonDisabled(type, currentDate) ? confirmDisabledText : confirmText }) })] })), /*#__PURE__*/_jsx(VanToast, { id: "van-toast" })] }); } var Calendar = /*#__PURE__*/forwardRef(Index); export { Calendar }; export default Calendar;