@antmjs/vantui
Version:
一套适用于Taro3及React的vantui组件库
531 lines (529 loc) • 21.1 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
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", "longspan", "zIndex"];
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, useMemo } from 'react';
import { getCurrentPages, createIntersectionObserver, nextTick } from '@tarojs/taro';
import * as utils from '../wxs/utils';
import Toast from '../toast/index';
import { requestAnimationFrame } from '../common/utils';
import VanPopup from '../popup/index';
import VanButton from '../button/index';
import { get } from '../default-props';
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 { LongSpan } from './components/longSpan';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var d = get().Calendar || {};
var initialMinDate = getToday().getTime();
var init = 0;
var initialMaxDate = function () {
var now = getToday();
return new Date(now.getFullYear(), now.getMonth() + 6, now.getDate()).getTime();
}();
var fourMonth = 4 * 30 * 24 * 60 * 60 * 1000;
function Index(props, ref) {
var _d$props = _objectSpread(_objectSpread({}, d), props),
_d$props$title = _d$props.title,
title = _d$props$title === void 0 ? '日期选择' : _d$props$title,
color = _d$props.color,
show = _d$props.show,
formatter = _d$props.formatter,
_d$props$confirmText = _d$props.confirmText,
confirmText = _d$props$confirmText === void 0 ? '确定' : _d$props$confirmText,
rangePrompt = _d$props.rangePrompt,
defaultDate = _d$props.defaultDate,
allowSameDay = _d$props.allowSameDay,
_d$props$type = _d$props.type,
type = _d$props$type === void 0 ? 'single' : _d$props$type,
_d$props$confirmDisab = _d$props.confirmDisabledText,
confirmDisabledText = _d$props$confirmDisab === void 0 ? '确定' : _d$props$confirmDisab,
_d$props$minDate = _d$props.minDate,
minDate = _d$props$minDate === void 0 ? initialMinDate : _d$props$minDate,
_d$props$maxDate = _d$props.maxDate,
maxDate = _d$props$maxDate === void 0 ? initialMaxDate : _d$props$maxDate,
_d$props$position = _d$props.position,
position = _d$props$position === void 0 ? 'bottom' : _d$props$position,
_d$props$rowHeight = _d$props.rowHeight,
rowHeight = _d$props$rowHeight === void 0 ? ROW_HEIGHT : _d$props$rowHeight,
_d$props$round = _d$props.round,
round = _d$props$round === void 0 ? true : _d$props$round,
_d$props$poppable = _d$props.poppable,
poppable = _d$props$poppable === void 0 ? true : _d$props$poppable,
_d$props$showMark = _d$props.showMark,
showMark = _d$props$showMark === void 0 ? true : _d$props$showMark,
_d$props$showTitle = _d$props.showTitle,
showTitle = _d$props$showTitle === void 0 ? true : _d$props$showTitle,
_d$props$showConfirm = _d$props.showConfirm,
showConfirm = _d$props$showConfirm === void 0 ? true : _d$props$showConfirm,
_d$props$showSubtitle = _d$props.showSubtitle,
showSubtitle = _d$props$showSubtitle === void 0 ? true : _d$props$showSubtitle,
_d$props$safeAreaInse = _d$props.safeAreaInsetBottom,
safeAreaInsetBottom = _d$props$safeAreaInse === void 0 ? true : _d$props$safeAreaInse,
_d$props$closeOnClick = _d$props.closeOnClickOverlay,
closeOnClickOverlay = _d$props$closeOnClick === void 0 ? true : _d$props$closeOnClick,
_d$props$showRangePro = _d$props.showRangePrompt,
showRangePrompt = _d$props$showRangePro === void 0 ? true : _d$props$showRangePro,
maxRange = _d$props.maxRange,
_onClose = _d$props.onClose,
onOpen = _d$props.onOpen,
onClosed = _d$props.onClosed,
onOpened = _d$props.onOpened,
onConfirm = _d$props.onConfirm,
onSelect = _d$props.onSelect,
_d$props$firstDayOfWe = _d$props.firstDayOfWeek,
firstDayOfWeek = _d$props$firstDayOfWe === void 0 ? 0 : _d$props$firstDayOfWe,
overRange = _d$props.overRange,
onUnselect = _d$props.onUnselect,
_onClickSubtitle = _d$props.onClickSubtitle,
renderTitle = _d$props.renderTitle,
renderFooter = _d$props.renderFooter,
className = _d$props.className,
style = _d$props.style,
_d$props$longspan = _d$props.longspan,
longspan = _d$props$longspan === void 0 ? true : _d$props$longspan,
zIndex = _d$props.zIndex,
others = _objectWithoutProperties(_d$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(init++),
_useState8 = _slicedToArray(_useState7, 1),
compIndex = _useState8[0];
var _useState9 = useState(0),
_useState10 = _slicedToArray(_useState9, 2),
currentMonthDate = _useState10[0],
setCurrentMonthDate = _useState10[1];
var _useState11 = useState(false),
_useState12 = _slicedToArray(_useState11, 2),
longSpanShow = _useState12[0],
setLongSpanShow = _useState12[1];
var _useState13 = useState(true),
_useState14 = _slicedToArray(_useState13, 2),
isInitial = _useState14[0],
setIsInitial = _useState14[1];
var monthsData = useMemo(function () {
return computed.getMonths(minDate, maxDate);
}, [maxDate, minDate]);
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, allowSameDay ? maxDate : getPrevDay(maxDate).getTime());
var end = limitDateRange(endDay || now, allowSameDay ? minDate : getNextDay(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, allowSameDay, maxDate, minDate, type]);
var scrollIntoViewCompatible = useCallback(function (t) {
if (process.env.TARO_ENV === 'h5') {
var _document$querySelect;
(_document$querySelect = document.querySelector("#".concat(t))) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.scrollIntoView(false);
} else {
setScrollIntoView(t);
}
}, []);
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(month);
scrollIntoViewCompatible(id);
return true;
}
return false;
});
});
}, [currentDate, maxDate, minDate, poppable, scrollIntoViewCompatible, show, type]);
var reset = useCallback(function () {
setCurrentDate(getInitialDate(defaultDate));
setTimeout(function () {
scrollIntoViewFn();
}, 66);
}, [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_', '');
if (item && item !== subtitle) {
var monthDate = Number(item);
setSubtitle(formatMonthTitle(monthDate));
setCurrentMonthDate(monthDate);
}
}
}
}, {
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' || process.env.TARO_ENV === 'dd') {
_createIntersectionObserver = createIntersectionObserver;
}
var contentObserver_ = _createIntersectionObserver({
thresholds: [0.6, 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_', '');
if (item && item !== subtitle) {
var monthDate = Number(item);
setSubtitle(formatMonthTitle(monthDate));
setCurrentMonthDate(monthDate);
}
}
});
}, [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"),
selector: 'van-carlendar-toast'
});
}
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 && show) {
setCurrentDate(getInitialDate(defaultDate || new Date().getTime()));
setIsInitial(false);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[show]);
useEffect(function () {
if (show || !poppable) {
setTimeout(function () {
nextTick(function () {
initRect();
setTimeout(function () {
scrollIntoViewFn();
}, 66);
});
}, 66);
}
return function () {
if (!show) setScrollIntoView(''); // 需要重置滚动的目标id, 否则相同的前后两次id不会在此触发滚动
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[poppable, show, isInitial]);
useEffect(function () {
reset();
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[type]);
useImperativeHandle(ref, function () {
return {
reset: reset,
getSelectedDate: function getSelectedDate() {
return currentDate;
}
};
});
var quickSwitchMonth = useCallback(function (t, mIndex) {
if (process.env.TARO_ENV === 'h5') {
scrollIntoViewCompatible(t);
nextTick(function () {
setTimeout(function () {
setLongSpanShow(false);
var monthDate = monthsData[mIndex];
setSubtitle(formatMonthTitle(monthDate));
setCurrentMonthDate(monthDate);
}, 66.66);
});
} else {
setLongSpanShow(false);
nextTick(function () {
setTimeout(function () {
scrollIntoViewCompatible(t);
}, 16.66);
});
}
}, [monthsData, scrollIntoViewCompatible]);
var bodyRender = function bodyRender() {
return /*#__PURE__*/_jsxs(View, _objectSpread(_objectSpread({
className: "van-calendar ".concat(className || ''),
style: utils.style([style])
// @ts-ignore
,
catchMove: poppable
}, others), {}, {
children: [longspan && longSpanShow && poppable && /*#__PURE__*/_jsx(LongSpan, {
data: monthsData,
current: currentMonthDate,
setScrollIntoView: quickSwitchMonth
}), /*#__PURE__*/_jsx(Header, {
title: title,
showTitle: showTitle,
subtitle: subtitle,
showSubtitle: showSubtitle,
firstDayOfWeek: firstDayOfWeek,
onClickSubtitle: function onClickSubtitle() {
if (_onClickSubtitle) _onClickSubtitle();
setLongSpanShow(true);
},
renderTitle: renderTitle,
subtitleStyle: longspan ? {
textDecoration: 'underline'
} : {}
}), /*#__PURE__*/_jsx(ScrollView, {
className: "van-calendar__body van-calendar__body".concat(compIndex),
scrollY: true,
scrollIntoView: scrollIntoView,
scrollWithAnimation: false,
scrollAnimationDuration: "0ms",
onScroll: function onScroll(e) {
return e.stopPropagation();
},
children: monthsData.map(function (item, index) {
return /*#__PURE__*/_jsx(Month, {
ifRender: item >= currentMonthDate - fourMonth && item <= currentMonthDate + fourMonth,
id: "month_".concat(item),
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: "primary",
color: color,
className: "van-calendar__confirm",
disabled: computed.getButtonDisabled(type, currentDate)
// nativeType="text"
,
onClick: onConfirm_,
children: computed.getButtonDisabled(type, currentDate) ? confirmDisabledText : confirmText
})
})]
}));
};
return /*#__PURE__*/_jsx(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: function onClose() {
_onClose === null || _onClose === void 0 ? void 0 : _onClose();
setLongSpanShow(false);
},
onAfterEnter: onOpened,
onAfterLeave: onClosed,
zIndex: zIndex,
children: bodyRender()
}) : bodyRender()
});
}
var Calendar = /*#__PURE__*/forwardRef(Index);
export { Calendar };
export default Calendar;