diff --git a/.gitignore b/.gitignore index 3d1ba2eac..94dda071e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ lib/ +dist/ # Logs logs diff --git a/dist/react-big-calendar.esm.js b/dist/react-big-calendar.esm.js deleted file mode 100644 index 524ab422d..000000000 --- a/dist/react-big-calendar.esm.js +++ /dev/null @@ -1,7689 +0,0 @@ -import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2' -import _objectWithoutProperties from '@babel/runtime/helpers/esm/objectWithoutProperties' -import _typeof from '@babel/runtime/helpers/esm/typeof' -import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck' -import _createClass from '@babel/runtime/helpers/esm/createClass' -import _inherits from '@babel/runtime/helpers/esm/inherits' -import _createSuper from '@babel/runtime/helpers/esm/createSuper' -import React, { - useEffect, - useLayoutEffect, - useRef, - createRef, - Component, - useMemo, - useState, - useCallback, -} from 'react' -import { uncontrollable } from 'uncontrollable' -import clsx from 'clsx' -import PropTypes from 'prop-types' -import invariant from 'invariant' -import * as dates from 'date-arithmetic' -import { - inRange as inRange$1, - lt, - lte, - gt, - gte, - eq, - neq, - startOf, - endOf, - add, - min, - max, - minutes, -} from 'date-arithmetic' -import _defineProperty from '@babel/runtime/helpers/esm/defineProperty' -import _toConsumableArray from '@babel/runtime/helpers/esm/toConsumableArray' -import chunk from 'lodash-es/chunk' -import getPosition$1 from 'dom-helpers/position' -import * as animationFrame from 'dom-helpers/animationFrame' -import { Overlay } from 'react-overlays' -import getOffset from 'dom-helpers/offset' -import isEqual$1 from 'lodash-es/isEqual' -import getHeight from 'dom-helpers/height' -import qsa from 'dom-helpers/querySelectorAll' -import contains from 'dom-helpers/contains' -import closest from 'dom-helpers/closest' -import listen from 'dom-helpers/listen' -import findIndex from 'lodash-es/findIndex' -import range$1 from 'lodash-es/range' -import memoize from 'memoize-one' -import _slicedToArray from '@babel/runtime/helpers/esm/slicedToArray' -import _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized' -import sortBy from 'lodash-es/sortBy' -import getWidth from 'dom-helpers/width' -import scrollbarSize from 'dom-helpers/scrollbarSize' -import _toArray from '@babel/runtime/helpers/esm/toArray' -import addClass from 'dom-helpers/addClass' -import removeClass from 'dom-helpers/removeClass' -import omit from 'lodash-es/omit' -import defaults from 'lodash-es/defaults' -import transform from 'lodash-es/transform' -import mapValues from 'lodash-es/mapValues' - -function NoopWrapper(props) { - return props.children -} - -var navigate = { - PREVIOUS: 'PREV', - NEXT: 'NEXT', - TODAY: 'TODAY', - DATE: 'DATE', -} -var views = { - MONTH: 'month', - WEEK: 'week', - WORK_WEEK: 'work_week', - DAY: 'day', - AGENDA: 'agenda', -} - -var viewNames$1 = Object.keys(views).map(function (k) { - return views[k] -}) -PropTypes.oneOfType([PropTypes.string, PropTypes.func]) -PropTypes.any -PropTypes.func -/** - * accepts either an array of builtin view names: - * - * ``` - * views={['month', 'day', 'agenda']} - * ``` - * - * or an object hash of the view name and the component (or boolean for builtin) - * - * ``` - * views={{ - * month: true, - * week: false, - * workweek: WorkWeekViewComponent, - * }} - * ``` - */ - -PropTypes.oneOfType([ - PropTypes.arrayOf(PropTypes.oneOf(viewNames$1)), - PropTypes.objectOf(function (prop, key) { - var isBuiltinView = - viewNames$1.indexOf(key) !== -1 && typeof prop[key] === 'boolean' - - if (isBuiltinView) { - return null - } else { - for ( - var _len = arguments.length, - args = new Array(_len > 2 ? _len - 2 : 0), - _key = 2; - _key < _len; - _key++ - ) { - args[_key - 2] = arguments[_key] - } - - return PropTypes.elementType.apply(PropTypes, [prop, key].concat(args)) - } - }), -]) -PropTypes.oneOfType([ - PropTypes.oneOf(['overlap', 'no-overlap']), - PropTypes.func, -]) - -function notify(handler, args) { - handler && handler.apply(null, [].concat(args)) -} - -/* eslint no-fallthrough: off */ -var MILLI = { - seconds: 1000, - minutes: 1000 * 60, - hours: 1000 * 60 * 60, - day: 1000 * 60 * 60 * 24, -} -function firstVisibleDay(date, localizer) { - var firstOfMonth = dates.startOf(date, 'month') - return dates.startOf(firstOfMonth, 'week', localizer.startOfWeek()) -} -function lastVisibleDay(date, localizer) { - var endOfMonth = dates.endOf(date, 'month') - return dates.endOf(endOfMonth, 'week', localizer.startOfWeek()) -} -function visibleDays(date, localizer) { - var current = firstVisibleDay(date, localizer), - last = lastVisibleDay(date, localizer), - days = [] - - while (dates.lte(current, last, 'day')) { - days.push(current) - current = dates.add(current, 1, 'day') - } - - return days -} -function ceil(date, unit) { - var floor = dates.startOf(date, unit) - return dates.eq(floor, date) ? floor : dates.add(floor, 1, unit) -} -function range(start, end) { - var unit = - arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'day' - var current = start, - days = [] - - while (dates.lte(current, end, unit)) { - days.push(current) - current = dates.add(current, 1, unit) - } - - return days -} -function merge(date, time) { - if (time == null && date == null) return null - if (time == null) time = new Date() - if (date == null) date = new Date() - date = dates.startOf(date, 'day') - date = dates.hours(date, dates.hours(time)) - date = dates.minutes(date, dates.minutes(time)) - date = dates.seconds(date, dates.seconds(time)) - return dates.milliseconds(date, dates.milliseconds(time)) -} -function isJustDate(date) { - return ( - dates.hours(date) === 0 && - dates.minutes(date) === 0 && - dates.seconds(date) === 0 && - dates.milliseconds(date) === 0 - ) -} -function diff(dateA, dateB, unit) { - if (!unit || unit === 'milliseconds') return Math.abs(+dateA - +dateB) // the .round() handles an edge case - // with DST where the total won't be exact - // since one day in the range may be shorter/longer by an hour - - return Math.round( - Math.abs( - +dates.startOf(dateA, unit) / MILLI[unit] - - +dates.startOf(dateB, unit) / MILLI[unit] - ) - ) -} - -var localePropType = PropTypes.oneOfType([PropTypes.string, PropTypes.func]) - -function _format(localizer, formatter, value, format, culture) { - var result = - typeof format === 'function' - ? format(value, culture, localizer) - : formatter.call(localizer, value, format, culture) - invariant( - result == null || typeof result === 'string', - '`localizer format(..)` must return a string, null, or undefined' - ) - return result -} -/** - * This date conversion was moved out of TimeSlots.js, to - * allow for localizer override - * @param {Date} dt - The date to start from - * @param {Number} minutesFromMidnight - * @param {Number} offset - * @returns {Date} - */ - -function getSlotDate(dt, minutesFromMidnight, offset) { - return new Date( - dt.getFullYear(), - dt.getMonth(), - dt.getDate(), - 0, - minutesFromMidnight + offset, - 0, - 0 - ) -} - -function getDstOffset(start, end) { - return start.getTimezoneOffset() - end.getTimezoneOffset() -} // if the start is on a DST-changing day but *after* the moment of DST -// transition we need to add those extra minutes to our minutesFromMidnight - -function getTotalMin(start, end) { - return diff(start, end, 'minutes') + getDstOffset(start, end) -} - -function getMinutesFromMidnight(start) { - var daystart = startOf(start, 'day') - return diff(daystart, start, 'minutes') + getDstOffset(daystart, start) -} // These two are used by DateSlotMetrics - -function continuesPrior(start, first) { - return lt(start, first, 'day') -} - -function continuesAfter(start, end, last) { - var singleDayDuration = eq(start, end, 'minutes') - return singleDayDuration - ? gte(end, last, 'minutes') - : gt(end, last, 'minutes') -} // These two are used by eventLevels - -function sortEvents$1(_ref) { - var _ref$evtA = _ref.evtA, - aStart = _ref$evtA.start, - aEnd = _ref$evtA.end, - aAllDay = _ref$evtA.allDay, - _ref$evtB = _ref.evtB, - bStart = _ref$evtB.start, - bEnd = _ref$evtB.end, - bAllDay = _ref$evtB.allDay - var startSort = +startOf(aStart, 'day') - +startOf(bStart, 'day') - var durA = diff(aStart, ceil(aEnd, 'day'), 'day') - var durB = diff(bStart, ceil(bEnd, 'day'), 'day') - return ( - startSort || // sort by start Day first - Math.max(durB, 1) - Math.max(durA, 1) || // events spanning multiple days go first - !!bAllDay - !!aAllDay || // then allDay single day events - +aStart - +bStart || // then sort by start time - +aEnd - +bEnd // then sort by end time - ) -} - -function inEventRange(_ref2) { - var _ref2$event = _ref2.event, - start = _ref2$event.start, - end = _ref2$event.end, - _ref2$range = _ref2.range, - rangeStart = _ref2$range.start, - rangeEnd = _ref2$range.end - var eStart = startOf(start, 'day') - var startsBeforeEnd = lte(eStart, rangeEnd, 'day') // when the event is zero duration we need to handle a bit differently - - var sameMin = neq(eStart, end, 'minutes') - var endsAfterStart = sameMin - ? gt(end, rangeStart, 'minutes') - : gte(end, rangeStart, 'minutes') - return startsBeforeEnd && endsAfterStart -} // other localizers treats 'day' and 'date' equality very differently, so we -// abstract the change the 'localizer.eq(date1, date2, 'day') into this -// new method, where they can be treated correctly by the localizer overrides - -function isSameDate(date1, date2) { - return eq(date1, date2, 'day') -} - -function startAndEndAreDateOnly(start, end) { - return isJustDate(start) && isJustDate(end) -} - -var DateLocalizer = /*#__PURE__*/ _createClass(function DateLocalizer(spec) { - var _this = this - - _classCallCheck(this, DateLocalizer) - - invariant( - typeof spec.format === 'function', - 'date localizer `format(..)` must be a function' - ) - invariant( - typeof spec.firstOfWeek === 'function', - 'date localizer `firstOfWeek(..)` must be a function' - ) - this.propType = spec.propType || localePropType - this.formats = spec.formats - - this.format = function () { - for ( - var _len = arguments.length, args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key] - } - - return _format.apply(void 0, [_this, spec.format].concat(args)) - } // These date arithmetic methods can be overriden by the localizer - - this.startOfWeek = spec.firstOfWeek - this.merge = spec.merge || merge - this.inRange = spec.inRange || inRange$1 - this.lt = spec.lt || lt - this.lte = spec.lte || lte - this.gt = spec.gt || gt - this.gte = spec.gte || gte - this.eq = spec.eq || eq - this.neq = spec.neq || neq - this.startOf = spec.startOf || startOf - this.endOf = spec.endOf || endOf - this.add = spec.add || add - this.range = spec.range || range - this.diff = spec.diff || diff - this.ceil = spec.ceil || ceil - this.min = spec.min || min - this.max = spec.max || max - this.minutes = spec.minutes || minutes - this.firstVisibleDay = spec.firstVisibleDay || firstVisibleDay - this.lastVisibleDay = spec.lastVisibleDay || lastVisibleDay - this.visibleDays = spec.visibleDays || visibleDays - this.getSlotDate = spec.getSlotDate || getSlotDate - - this.getTimezoneOffset = - spec.getTimezoneOffset || - function (value) { - return value.getTimezoneOffset() - } - - this.getDstOffset = spec.getDstOffset || getDstOffset - this.getTotalMin = spec.getTotalMin || getTotalMin - this.getMinutesFromMidnight = - spec.getMinutesFromMidnight || getMinutesFromMidnight - this.continuesPrior = spec.continuesPrior || continuesPrior - this.continuesAfter = spec.continuesAfter || continuesAfter - this.sortEvents = spec.sortEvents || sortEvents$1 - this.inEventRange = spec.inEventRange || inEventRange - this.isSameDate = spec.isSameDate || isSameDate - this.startAndEndAreDateOnly = - spec.startAndEndAreDateOnly || startAndEndAreDateOnly - this.segmentOffset = spec.browserTZOffset ? spec.browserTZOffset() : 0 -}) -function mergeWithDefaults(localizer, culture, formatOverrides, messages) { - var formats = _objectSpread( - _objectSpread({}, localizer.formats), - formatOverrides - ) - - return _objectSpread( - _objectSpread({}, localizer), - {}, - { - messages: messages, - startOfWeek: function startOfWeek() { - return localizer.startOfWeek(culture) - }, - format: function format(value, _format2) { - return localizer.format(value, formats[_format2] || _format2, culture) - }, - } - ) -} - -var defaultMessages = { - date: 'Date', - time: 'Time', - event: 'Event', - allDay: 'All Day', - week: 'Week', - work_week: 'Work Week', - day: 'Day', - month: 'Month', - previous: 'Back', - next: 'Next', - yesterday: 'Yesterday', - tomorrow: 'Tomorrow', - today: 'Today', - agenda: 'Agenda', - noEventsInRange: 'There are no events in this range.', - showMore: function showMore(total) { - return '+'.concat(total, ' more') - }, -} -function messages(msgs) { - return _objectSpread(_objectSpread({}, defaultMessages), msgs) -} - -function useClickOutside(_ref) { - var ref = _ref.ref, - callback = _ref.callback - useEffect( - function () { - var handleClickOutside = function handleClickOutside(e) { - if (ref.current && !ref.current.contains(e.target)) { - callback() - } - } - - document.addEventListener('mousedown', handleClickOutside) - return function () { - document.removeEventListener('mousedown', handleClickOutside) - } - }, - [ref, callback] - ) -} - -var _excluded$7 = [ - 'style', - 'className', - 'event', - 'selected', - 'isAllDay', - 'onSelect', - 'onDoubleClick', - 'onKeyPress', - 'localizer', - 'continuesPrior', - 'continuesAfter', - 'accessors', - 'getters', - 'children', - 'components', - 'slotStart', - 'slotEnd', -] - -var EventCell = /*#__PURE__*/ (function (_React$Component) { - _inherits(EventCell, _React$Component) - - var _super = _createSuper(EventCell) - - function EventCell() { - _classCallCheck(this, EventCell) - - return _super.apply(this, arguments) - } - - _createClass(EventCell, [ - { - key: 'render', - value: function render() { - var _this$props = this.props, - style = _this$props.style, - className = _this$props.className, - event = _this$props.event, - selected = _this$props.selected, - isAllDay = _this$props.isAllDay, - onSelect = _this$props.onSelect, - _onDoubleClick = _this$props.onDoubleClick, - _onKeyPress = _this$props.onKeyPress, - localizer = _this$props.localizer, - continuesPrior = _this$props.continuesPrior, - continuesAfter = _this$props.continuesAfter, - accessors = _this$props.accessors, - getters = _this$props.getters, - children = _this$props.children, - _this$props$component = _this$props.components, - Event = _this$props$component.event, - EventWrapper = _this$props$component.eventWrapper, - slotStart = _this$props.slotStart, - slotEnd = _this$props.slotEnd, - props = _objectWithoutProperties(_this$props, _excluded$7) - - delete props.resizable - var title = accessors.title(event) - var tooltip = accessors.tooltip(event) - var end = accessors.end(event) - var start = accessors.start(event) - var allDay = accessors.allDay(event) - var showAsAllDay = - isAllDay || - allDay || - localizer.diff(start, localizer.ceil(end, 'day'), 'day') > 1 - var userProps = getters.eventProp(event, start, end, selected) - var content = /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-event-content', - style: event.style || {}, - title: tooltip || undefined, - }, - Event - ? /*#__PURE__*/ React.createElement(Event, { - event: event, - continuesPrior: continuesPrior, - continuesAfter: continuesAfter, - title: title, - isAllDay: allDay, - localizer: localizer, - slotStart: slotStart, - slotEnd: slotEnd, - }) - : title - ) - return /*#__PURE__*/ React.createElement( - EventWrapper, - Object.assign({}, this.props, { - type: 'date', - }), - /*#__PURE__*/ React.createElement( - 'div', - Object.assign({}, props, { - tabIndex: 0, - style: _objectSpread( - _objectSpread(_objectSpread({}, userProps.style), style), - event.style || {} - ), - className: clsx('rbc-event', className, userProps.className, { - 'rbc-selected': selected, - 'rbc-event-allday': showAsAllDay, - 'rbc-event-continues-prior': continuesPrior, - 'rbc-event-continues-after': continuesAfter, - }), - onClick: function onClick(e) { - return onSelect && onSelect(event, e) - }, - onDoubleClick: function onDoubleClick(e) { - return _onDoubleClick && _onDoubleClick(event, e) - }, - onKeyPress: function onKeyPress(e) { - return _onKeyPress && _onKeyPress(event, e) - }, - }), - typeof children === 'function' ? children(content) : content - ) - ) - }, - }, - ]) - - return EventCell -})(React.Component) - -function isSelected(event, selected) { - if (!event || selected == null) return false - return isEqual$1(event, selected) -} -function slotWidth(rowBox, slots) { - var rowWidth = rowBox.right - rowBox.left - var cellWidth = rowWidth / slots - return cellWidth -} -function getSlotAtX(rowBox, x, rtl, slots) { - var cellWidth = slotWidth(rowBox, slots) - return rtl - ? slots - 1 - Math.floor((x - rowBox.left) / cellWidth) - : Math.floor((x - rowBox.left) / cellWidth) -} -function pointInBox(box, _ref) { - var x = _ref.x, - y = _ref.y - return y >= box.top && y <= box.bottom && x >= box.left && x <= box.right -} -function dateCellSelection(start, rowBox, box, slots, rtl) { - var startIdx = -1 - var endIdx = -1 - var lastSlotIdx = slots - 1 - var cellWidth = slotWidth(rowBox, slots) // cell under the mouse - - var currentSlot = getSlotAtX(rowBox, box.x, rtl, slots) // Identify row as either the initial row - // or the row under the current mouse point - - var isCurrentRow = rowBox.top < box.y && rowBox.bottom > box.y - var isStartRow = rowBox.top < start.y && rowBox.bottom > start.y // this row's position relative to the start point - - var isAboveStart = start.y > rowBox.bottom - var isBelowStart = rowBox.top > start.y - var isBetween = box.top < rowBox.top && box.bottom > rowBox.bottom // this row is between the current and start rows, so entirely selected - - if (isBetween) { - startIdx = 0 - endIdx = lastSlotIdx - } - - if (isCurrentRow) { - if (isBelowStart) { - startIdx = 0 - endIdx = currentSlot - } else if (isAboveStart) { - startIdx = currentSlot - endIdx = lastSlotIdx - } - } - - if (isStartRow) { - // select the cell under the initial point - startIdx = endIdx = rtl - ? lastSlotIdx - Math.floor((start.x - rowBox.left) / cellWidth) - : Math.floor((start.x - rowBox.left) / cellWidth) - - if (isCurrentRow) { - if (currentSlot < startIdx) startIdx = currentSlot - else endIdx = currentSlot //select current range - } else if (start.y < box.y) { - // the current row is below start row - // select cells to the right of the start cell - endIdx = lastSlotIdx - } else { - // select cells to the left of the start cell - startIdx = 0 - } - } - - return { - startIdx: startIdx, - endIdx: endIdx, - } -} - -/** - * Changes to react-overlays cause issue with auto positioning, - * so we need to manually calculate the position of the popper, - * and constrain it to the Month container. - */ - -function getPosition(_ref) { - var target = _ref.target, - offset = _ref.offset, - container = _ref.container, - box = _ref.box - - var _getOffset = getOffset(target), - top = _getOffset.top, - left = _getOffset.left, - width = _getOffset.width, - height = _getOffset.height - - var _getOffset2 = getOffset(container), - cTop = _getOffset2.top, - cLeft = _getOffset2.left, - cWidth = _getOffset2.width, - cHeight = _getOffset2.height - - var _getOffset3 = getOffset(box), - bWidth = _getOffset3.width, - bHeight = _getOffset3.height - - var viewBottom = cTop + cHeight - var viewRight = cLeft + cWidth - var bottom = top + bHeight - var right = left + bWidth - var x = offset.x, - y = offset.y - var topOffset = bottom > viewBottom ? top - bHeight - y : top + y + height - var leftOffset = right > viewRight ? left + x - bWidth + width : left + x - return { - topOffset: topOffset, - leftOffset: leftOffset, - } -} - -function Pop(_ref2) { - var containerRef = _ref2.containerRef, - accessors = _ref2.accessors, - getters = _ref2.getters, - selected = _ref2.selected, - components = _ref2.components, - localizer = _ref2.localizer, - position = _ref2.position, - show = _ref2.show, - events = _ref2.events, - slotStart = _ref2.slotStart, - slotEnd = _ref2.slotEnd, - onSelect = _ref2.onSelect, - onDoubleClick = _ref2.onDoubleClick, - onKeyPress = _ref2.onKeyPress, - handleDragStart = _ref2.handleDragStart, - popperRef = _ref2.popperRef, - target = _ref2.target, - offset = _ref2.offset - useClickOutside({ - ref: popperRef, - callback: show, - }) - useLayoutEffect( - function () { - var _getPosition = getPosition({ - target: target, - offset: offset, - container: containerRef.current, - box: popperRef.current, - }), - topOffset = _getPosition.topOffset, - leftOffset = _getPosition.leftOffset - - popperRef.current.style.top = ''.concat(topOffset, 'px') - popperRef.current.style.left = ''.concat(leftOffset, 'px') - }, - [offset.x, offset.y, target] - ) - var width = position.width - var style = { - minWidth: width + width / 2, - } - return /*#__PURE__*/ React.createElement( - 'div', - { - style: style, - className: 'rbc-overlay', - ref: popperRef, - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-overlay-header', - }, - localizer.format(slotStart, 'dayHeaderFormat') - ), - events.map(function (event, idx) { - return /*#__PURE__*/ React.createElement(EventCell, { - key: idx, - type: 'popup', - localizer: localizer, - event: event, - getters: getters, - onSelect: onSelect, - accessors: accessors, - components: components, - onDoubleClick: onDoubleClick, - onKeyPress: onKeyPress, - continuesPrior: localizer.lt(accessors.end(event), slotStart, 'day'), - continuesAfter: localizer.gte(accessors.start(event), slotEnd, 'day'), - slotStart: slotStart, - slotEnd: slotEnd, - selected: isSelected(event, selected), - draggable: true, - onDragStart: function onDragStart() { - return handleDragStart(event) - }, - onDragEnd: function onDragEnd() { - return show() - }, - }) - }) - ) -} - -var Popup = /*#__PURE__*/ React.forwardRef(function (props, ref) { - return /*#__PURE__*/ React.createElement( - Pop, - Object.assign({}, props, { - popperRef: ref, - }) - ) -}) -Popup.propTypes = { - accessors: PropTypes.object.isRequired, - getters: PropTypes.object.isRequired, - selected: PropTypes.object, - components: PropTypes.object.isRequired, - localizer: PropTypes.object.isRequired, - position: PropTypes.object.isRequired, - show: PropTypes.func.isRequired, - events: PropTypes.array.isRequired, - slotStart: PropTypes.instanceOf(Date).isRequired, - slotEnd: PropTypes.instanceOf(Date), - onSelect: PropTypes.func, - onDoubleClick: PropTypes.func, - onKeyPress: PropTypes.func, - handleDragStart: PropTypes.func, - style: PropTypes.object, - offset: PropTypes.shape({ - x: PropTypes.number, - y: PropTypes.number, - }), -} - -function CalOverlay(_ref) { - var containerRef = _ref.containerRef, - _ref$popupOffset = _ref.popupOffset, - popupOffset = _ref$popupOffset === void 0 ? 5 : _ref$popupOffset, - overlay = _ref.overlay, - accessors = _ref.accessors, - localizer = _ref.localizer, - components = _ref.components, - getters = _ref.getters, - selected = _ref.selected, - handleSelectEvent = _ref.handleSelectEvent, - handleDoubleClickEvent = _ref.handleDoubleClickEvent, - handleKeyPressEvent = _ref.handleKeyPressEvent, - handleDragStart = _ref.handleDragStart, - onHide = _ref.onHide, - overlayDisplay = _ref.overlayDisplay - var popperRef = useRef(null) - if (!overlay.position) return null - var offset = popupOffset - - if (!isNaN(popupOffset)) { - offset = { - x: popupOffset, - y: popupOffset, - } - } - - var position = overlay.position, - events = overlay.events, - date = overlay.date, - end = overlay.end - return /*#__PURE__*/ React.createElement( - Overlay, - { - rootClose: true, - flip: true, - show: true, - placement: 'bottom', - onHide: onHide, - target: overlay.target, - }, - function (_ref2) { - var props = _ref2.props - return /*#__PURE__*/ React.createElement( - Popup, - Object.assign({}, props, { - containerRef: containerRef, - ref: popperRef, - target: overlay.target, - offset: offset, - accessors: accessors, - getters: getters, - selected: selected, - components: components, - localizer: localizer, - position: position, - show: overlayDisplay, - events: events, - slotStart: date, - slotEnd: end, - onSelect: handleSelectEvent, - onDoubleClick: handleDoubleClickEvent, - onKeyPress: handleKeyPressEvent, - handleDragStart: handleDragStart, - }) - ) - } - ) -} - -var PopOverlay = /*#__PURE__*/ React.forwardRef(function (props, ref) { - return /*#__PURE__*/ React.createElement( - CalOverlay, - Object.assign({}, props, { - containerRef: ref, - }) - ) -}) -PopOverlay.propTypes = { - popupOffset: PropTypes.oneOfType([ - PropTypes.number, - PropTypes.shape({ - x: PropTypes.number, - y: PropTypes.number, - }), - ]), - overlay: PropTypes.shape({ - position: PropTypes.object, - events: PropTypes.array, - date: PropTypes.instanceOf(Date), - end: PropTypes.instanceOf(Date), - }), - accessors: PropTypes.object.isRequired, - localizer: PropTypes.object.isRequired, - components: PropTypes.object.isRequired, - getters: PropTypes.object.isRequired, - selected: PropTypes.object, - handleSelectEvent: PropTypes.func, - handleDoubleClickEvent: PropTypes.func, - handleKeyPressEvent: PropTypes.func, - handleDragStart: PropTypes.func, - onHide: PropTypes.func, - overlayDisplay: PropTypes.func, -} - -function addEventListener(type, handler) { - var target = - arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document - return listen(target, type, handler, { - passive: false, - }) -} - -function isOverContainer(container, x, y) { - return !container || contains(container, document.elementFromPoint(x, y)) -} - -function getEventNodeFromPoint(node, _ref) { - var clientX = _ref.clientX, - clientY = _ref.clientY - var target = document.elementFromPoint(clientX, clientY) - return closest(target, '.rbc-event', node) -} -function isEvent(node, bounds) { - return !!getEventNodeFromPoint(node, bounds) -} - -function getEventCoordinates(e) { - var target = e - - if (e.touches && e.touches.length) { - target = e.touches[0] - } - - return { - clientX: target.clientX, - clientY: target.clientY, - pageX: target.pageX, - pageY: target.pageY, - } -} - -var clickTolerance = 5 -var clickInterval = 250 - -var Selection = /*#__PURE__*/ (function () { - function Selection(node) { - var _ref2 = - arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref2$global = _ref2.global, - global = _ref2$global === void 0 ? false : _ref2$global, - _ref2$longPressThresh = _ref2.longPressThreshold, - longPressThreshold = - _ref2$longPressThresh === void 0 ? 250 : _ref2$longPressThresh, - _ref2$validContainers = _ref2.validContainers, - validContainers = - _ref2$validContainers === void 0 ? [] : _ref2$validContainers - - _classCallCheck(this, Selection) - - this.isDetached = false - this.container = node - this.globalMouse = !node || global - this.longPressThreshold = longPressThreshold - this.validContainers = validContainers - this._listeners = Object.create(null) - this._handleInitialEvent = this._handleInitialEvent.bind(this) - this._handleMoveEvent = this._handleMoveEvent.bind(this) - this._handleTerminatingEvent = this._handleTerminatingEvent.bind(this) - this._keyListener = this._keyListener.bind(this) - this._dropFromOutsideListener = this._dropFromOutsideListener.bind(this) - this._dragOverFromOutsideListener = - this._dragOverFromOutsideListener.bind(this) // Fixes an iOS 10 bug where scrolling could not be prevented on the window. - // https://github.com/metafizzy/flickity/issues/457#issuecomment-254501356 - - this._removeTouchMoveWindowListener = addEventListener( - 'touchmove', - function () {}, - window - ) - this._removeKeyDownListener = addEventListener('keydown', this._keyListener) - this._removeKeyUpListener = addEventListener('keyup', this._keyListener) - this._removeDropFromOutsideListener = addEventListener( - 'drop', - this._dropFromOutsideListener - ) - this._removeDragOverFromOutsideListener = addEventListener( - 'dragover', - this._dragOverFromOutsideListener - ) - - this._addInitialEventListener() - } - - _createClass(Selection, [ - { - key: 'on', - value: function on(type, handler) { - var handlers = this._listeners[type] || (this._listeners[type] = []) - handlers.push(handler) - return { - remove: function remove() { - var idx = handlers.indexOf(handler) - if (idx !== -1) handlers.splice(idx, 1) - }, - } - }, - }, - { - key: 'emit', - value: function emit(type) { - for ( - var _len = arguments.length, - args = new Array(_len > 1 ? _len - 1 : 0), - _key = 1; - _key < _len; - _key++ - ) { - args[_key - 1] = arguments[_key] - } - - var result - var handlers = this._listeners[type] || [] - handlers.forEach(function (fn) { - if (result === undefined) result = fn.apply(void 0, args) - }) - return result - }, - }, - { - key: 'teardown', - value: function teardown() { - this.isDetached = true - this._listeners = Object.create(null) - this._removeTouchMoveWindowListener && - this._removeTouchMoveWindowListener() - this._removeInitialEventListener && this._removeInitialEventListener() - this._removeEndListener && this._removeEndListener() - this._onEscListener && this._onEscListener() - this._removeMoveListener && this._removeMoveListener() - this._removeKeyUpListener && this._removeKeyUpListener() - this._removeKeyDownListener && this._removeKeyDownListener() - this._removeDropFromOutsideListener && - this._removeDropFromOutsideListener() - this._removeDragOverFromOutsideListener && - this._removeDragOverFromOutsideListener() - }, - }, - { - key: 'isSelected', - value: function isSelected(node) { - var box = this._selectRect - if (!box || !this.selecting) return false - return objectsCollide(box, getBoundsForNode(node)) - }, - }, - { - key: 'filter', - value: function filter(items) { - var box = this._selectRect //not selecting - - if (!box || !this.selecting) return [] - return items.filter(this.isSelected, this) - }, // Adds a listener that will call the handler only after the user has pressed on the screen - // without moving their finger for 250ms. - }, - { - key: '_addLongPressListener', - value: function _addLongPressListener(handler, initialEvent) { - var _this = this - - var timer = null - var removeTouchMoveListener = null - var removeTouchEndListener = null - - var handleTouchStart = function handleTouchStart(initialEvent) { - timer = setTimeout(function () { - cleanup() - handler(initialEvent) - }, _this.longPressThreshold) - removeTouchMoveListener = addEventListener('touchmove', function () { - return cleanup() - }) - removeTouchEndListener = addEventListener('touchend', function () { - return cleanup() - }) - } - - var removeTouchStartListener = addEventListener( - 'touchstart', - handleTouchStart - ) - - var cleanup = function cleanup() { - if (timer) { - clearTimeout(timer) - } - - if (removeTouchMoveListener) { - removeTouchMoveListener() - } - - if (removeTouchEndListener) { - removeTouchEndListener() - } - - timer = null - removeTouchMoveListener = null - removeTouchEndListener = null - } - - if (initialEvent) { - handleTouchStart(initialEvent) - } - - return function () { - cleanup() - removeTouchStartListener() - } - }, // Listen for mousedown and touchstart events. When one is received, disable the other and setup - // future event handling based on the type of event. - }, - { - key: '_addInitialEventListener', - value: function _addInitialEventListener() { - var _this2 = this - - var removeMouseDownListener = addEventListener( - 'mousedown', - function (e) { - _this2._removeInitialEventListener() - - _this2._handleInitialEvent(e) - - _this2._removeInitialEventListener = addEventListener( - 'mousedown', - _this2._handleInitialEvent - ) - } - ) - var removeTouchStartListener = addEventListener( - 'touchstart', - function (e) { - _this2._removeInitialEventListener() - - _this2._removeInitialEventListener = _this2._addLongPressListener( - _this2._handleInitialEvent, - e - ) - } - ) - - this._removeInitialEventListener = function () { - removeMouseDownListener() - removeTouchStartListener() - } - }, - }, - { - key: '_dropFromOutsideListener', - value: function _dropFromOutsideListener(e) { - var _getEventCoordinates = getEventCoordinates(e), - pageX = _getEventCoordinates.pageX, - pageY = _getEventCoordinates.pageY, - clientX = _getEventCoordinates.clientX, - clientY = _getEventCoordinates.clientY - - this.emit('dropFromOutside', { - x: pageX, - y: pageY, - clientX: clientX, - clientY: clientY, - }) - e.preventDefault() - }, - }, - { - key: '_dragOverFromOutsideListener', - value: function _dragOverFromOutsideListener(e) { - var _getEventCoordinates2 = getEventCoordinates(e), - pageX = _getEventCoordinates2.pageX, - pageY = _getEventCoordinates2.pageY, - clientX = _getEventCoordinates2.clientX, - clientY = _getEventCoordinates2.clientY - - this.emit('dragOverFromOutside', { - x: pageX, - y: pageY, - clientX: clientX, - clientY: clientY, - }) - e.preventDefault() - }, - }, - { - key: '_handleInitialEvent', - value: function _handleInitialEvent(e) { - if (this.isDetached) { - return - } - - var _getEventCoordinates3 = getEventCoordinates(e), - clientX = _getEventCoordinates3.clientX, - clientY = _getEventCoordinates3.clientY, - pageX = _getEventCoordinates3.pageX, - pageY = _getEventCoordinates3.pageY - - var node = this.container(), - collides, - offsetData // Right clicks - - if ( - e.which === 3 || - e.button === 2 || - !isOverContainer(node, clientX, clientY) - ) - return - - if (!this.globalMouse && node && !contains(node, e.target)) { - var _normalizeDistance = normalizeDistance(0), - top = _normalizeDistance.top, - left = _normalizeDistance.left, - bottom = _normalizeDistance.bottom, - right = _normalizeDistance.right - - offsetData = getBoundsForNode(node) - collides = objectsCollide( - { - top: offsetData.top - top, - left: offsetData.left - left, - bottom: offsetData.bottom + bottom, - right: offsetData.right + right, - }, - { - top: pageY, - left: pageX, - } - ) - if (!collides) return - } - - var result = this.emit( - 'beforeSelect', - (this._initialEventData = { - isTouch: /^touch/.test(e.type), - x: pageX, - y: pageY, - clientX: clientX, - clientY: clientY, - }) - ) - if (result === false) return - - switch (e.type) { - case 'mousedown': - this._removeEndListener = addEventListener( - 'mouseup', - this._handleTerminatingEvent - ) - this._onEscListener = addEventListener( - 'keydown', - this._handleTerminatingEvent - ) - this._removeMoveListener = addEventListener( - 'mousemove', - this._handleMoveEvent - ) - break - - case 'touchstart': - this._handleMoveEvent(e) - - this._removeEndListener = addEventListener( - 'touchend', - this._handleTerminatingEvent - ) - this._removeMoveListener = addEventListener( - 'touchmove', - this._handleMoveEvent - ) - break - } - }, // Check whether provided event target element - // - is contained within a valid container - }, - { - key: '_isWithinValidContainer', - value: function _isWithinValidContainer(e) { - var eventTarget = e.target - var containers = this.validContainers - - if (!containers || !containers.length || !eventTarget) { - return true - } - - return containers.some(function (target) { - return !!eventTarget.closest(target) - }) - }, - }, - { - key: '_handleTerminatingEvent', - value: function _handleTerminatingEvent(e) { - var _getEventCoordinates4 = getEventCoordinates(e), - pageX = _getEventCoordinates4.pageX, - pageY = _getEventCoordinates4.pageY - - this.selecting = false - this._removeEndListener && this._removeEndListener() - this._removeMoveListener && this._removeMoveListener() - if (!this._initialEventData) return - var inRoot = !this.container || contains(this.container(), e.target) - - var isWithinValidContainer = this._isWithinValidContainer(e) - - var bounds = this._selectRect - var click = this.isClick(pageX, pageY) - this._initialEventData = null - - if (e.key === 'Escape' || !isWithinValidContainer) { - return this.emit('reset') - } - - if (click && inRoot) { - return this._handleClickEvent(e) - } // User drag-clicked in the Selectable area - - if (!click) return this.emit('select', bounds) - return this.emit('reset') - }, - }, - { - key: '_handleClickEvent', - value: function _handleClickEvent(e) { - var _getEventCoordinates5 = getEventCoordinates(e), - pageX = _getEventCoordinates5.pageX, - pageY = _getEventCoordinates5.pageY, - clientX = _getEventCoordinates5.clientX, - clientY = _getEventCoordinates5.clientY - - var now = new Date().getTime() - - if ( - this._lastClickData && - now - this._lastClickData.timestamp < clickInterval - ) { - // Double click event - this._lastClickData = null - return this.emit('doubleClick', { - x: pageX, - y: pageY, - clientX: clientX, - clientY: clientY, - }) - } // Click event - - this._lastClickData = { - timestamp: now, - } - return this.emit('click', { - x: pageX, - y: pageY, - clientX: clientX, - clientY: clientY, - }) - }, - }, - { - key: '_handleMoveEvent', - value: function _handleMoveEvent(e) { - if (this._initialEventData === null || this.isDetached) { - return - } - - var _this$_initialEventDa = this._initialEventData, - x = _this$_initialEventDa.x, - y = _this$_initialEventDa.y - - var _getEventCoordinates6 = getEventCoordinates(e), - pageX = _getEventCoordinates6.pageX, - pageY = _getEventCoordinates6.pageY - - var w = Math.abs(x - pageX) - var h = Math.abs(y - pageY) - var left = Math.min(pageX, x), - top = Math.min(pageY, y), - old = this.selecting // Prevent emitting selectStart event until mouse is moved. - // in Chrome on Windows, mouseMove event may be fired just after mouseDown event. - - if (this.isClick(pageX, pageY) && !old && !(w || h)) { - return - } - - this.selecting = true - this._selectRect = { - top: top, - left: left, - x: pageX, - y: pageY, - right: left + w, - bottom: top + h, - } - - if (!old) { - this.emit('selectStart', this._initialEventData) - } - - if (!this.isClick(pageX, pageY)) - this.emit('selecting', this._selectRect) - e.preventDefault() - }, - }, - { - key: '_keyListener', - value: function _keyListener(e) { - this.ctrl = e.metaKey || e.ctrlKey - }, - }, - { - key: 'isClick', - value: function isClick(pageX, pageY) { - var _this$_initialEventDa2 = this._initialEventData, - x = _this$_initialEventDa2.x, - y = _this$_initialEventDa2.y, - isTouch = _this$_initialEventDa2.isTouch - return ( - !isTouch && - Math.abs(pageX - x) <= clickTolerance && - Math.abs(pageY - y) <= clickTolerance - ) - }, - }, - ]) - - return Selection -})() -/** - * Resolve the disance prop from either an Int or an Object - * @return {Object} - */ - -function normalizeDistance() { - var distance = - arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0 - if (_typeof(distance) !== 'object') - distance = { - top: distance, - left: distance, - right: distance, - bottom: distance, - } - return distance -} -/** - * Given two objects containing "top", "left", "offsetWidth" and "offsetHeight" - * properties, determine if they collide. - * @param {Object|HTMLElement} a - * @param {Object|HTMLElement} b - * @return {bool} - */ - -function objectsCollide(nodeA, nodeB) { - var tolerance = - arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0 - - var _getBoundsForNode = getBoundsForNode(nodeA), - aTop = _getBoundsForNode.top, - aLeft = _getBoundsForNode.left, - _getBoundsForNode$rig = _getBoundsForNode.right, - aRight = _getBoundsForNode$rig === void 0 ? aLeft : _getBoundsForNode$rig, - _getBoundsForNode$bot = _getBoundsForNode.bottom, - aBottom = _getBoundsForNode$bot === void 0 ? aTop : _getBoundsForNode$bot - - var _getBoundsForNode2 = getBoundsForNode(nodeB), - bTop = _getBoundsForNode2.top, - bLeft = _getBoundsForNode2.left, - _getBoundsForNode2$ri = _getBoundsForNode2.right, - bRight = _getBoundsForNode2$ri === void 0 ? bLeft : _getBoundsForNode2$ri, - _getBoundsForNode2$bo = _getBoundsForNode2.bottom, - bBottom = _getBoundsForNode2$bo === void 0 ? bTop : _getBoundsForNode2$bo - - return !( - // 'a' bottom doesn't touch 'b' top - ( - aBottom - tolerance < bTop || // 'a' top doesn't touch 'b' bottom - aTop + tolerance > bBottom || // 'a' right doesn't touch 'b' left - aRight - tolerance < bLeft || // 'a' left doesn't touch 'b' right - aLeft + tolerance > bRight - ) - ) -} -/** - * Given a node, get everything needed to calculate its boundaries - * @param {HTMLElement} node - * @return {Object} - */ - -function getBoundsForNode(node) { - if (!node.getBoundingClientRect) return node - var rect = node.getBoundingClientRect(), - left = rect.left + pageOffset('left'), - top = rect.top + pageOffset('top') - return { - top: top, - left: left, - right: (node.offsetWidth || 0) + left, - bottom: (node.offsetHeight || 0) + top, - } -} - -function pageOffset(dir) { - if (dir === 'left') return window.pageXOffset || document.body.scrollLeft || 0 - if (dir === 'top') return window.pageYOffset || document.body.scrollTop || 0 -} - -var BackgroundCells = /*#__PURE__*/ (function (_React$Component) { - _inherits(BackgroundCells, _React$Component) - - var _super = _createSuper(BackgroundCells) - - function BackgroundCells(props, context) { - var _this - - _classCallCheck(this, BackgroundCells) - - _this = _super.call(this, props, context) - _this.state = { - selecting: false, - } - _this.containerRef = /*#__PURE__*/ createRef() - return _this - } - - _createClass(BackgroundCells, [ - { - key: 'componentDidMount', - value: function componentDidMount() { - this.props.selectable && this._selectable() - }, - }, - { - key: 'componentWillUnmount', - value: function componentWillUnmount() { - this._teardownSelectable() - }, - }, - { - key: 'componentDidUpdate', - value: function componentDidUpdate(prevProps) { - if (!prevProps.selectable && this.props.selectable) this._selectable() - if (prevProps.selectable && !this.props.selectable) - this._teardownSelectable() - }, - }, - { - key: 'render', - value: function render() { - var _this$props = this.props, - range = _this$props.range, - getNow = _this$props.getNow, - getters = _this$props.getters, - currentDate = _this$props.date, - Wrapper = _this$props.components.dateCellWrapper, - localizer = _this$props.localizer - var _this$state = this.state, - selecting = _this$state.selecting, - startIdx = _this$state.startIdx, - endIdx = _this$state.endIdx - var current = getNow() - return /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row-bg', - ref: this.containerRef, - }, - range.map(function (date, index) { - var selected = selecting && index >= startIdx && index <= endIdx - - var _getters$dayProp = getters.dayProp(date), - className = _getters$dayProp.className, - style = _getters$dayProp.style - - return /*#__PURE__*/ React.createElement( - Wrapper, - { - key: index, - value: date, - range: range, - }, - /*#__PURE__*/ React.createElement('div', { - style: style, - className: clsx( - 'rbc-day-bg', - className, - selected && 'rbc-selected-cell', - localizer.isSameDate(date, current) && 'rbc-today', - currentDate && - localizer.neq(currentDate, date, 'month') && - 'rbc-off-range-bg' - ), - }) - ) - }) - ) - }, - }, - { - key: '_selectable', - value: function _selectable() { - var _this2 = this - - var node = this.containerRef.current - var selector = (this._selector = new Selection(this.props.container, { - longPressThreshold: this.props.longPressThreshold, - })) - - var selectorClicksHandler = function selectorClicksHandler( - point, - actionType - ) { - if (!isEvent(node, point)) { - var rowBox = getBoundsForNode(node) - var _this2$props = _this2.props, - range = _this2$props.range, - rtl = _this2$props.rtl - - if (pointInBox(rowBox, point)) { - var currentCell = getSlotAtX(rowBox, point.x, rtl, range.length) - - _this2._selectSlot({ - startIdx: currentCell, - endIdx: currentCell, - action: actionType, - box: point, - }) - } - } - - _this2._initial = {} - - _this2.setState({ - selecting: false, - }) - } - - selector.on('selecting', function (box) { - var _this2$props2 = _this2.props, - range = _this2$props2.range, - rtl = _this2$props2.rtl - var startIdx = -1 - var endIdx = -1 - - if (!_this2.state.selecting) { - notify(_this2.props.onSelectStart, [box]) - _this2._initial = { - x: box.x, - y: box.y, - } - } - - if (selector.isSelected(node)) { - var nodeBox = getBoundsForNode(node) - - var _dateCellSelection = dateCellSelection( - _this2._initial, - nodeBox, - box, - range.length, - rtl - ) - - startIdx = _dateCellSelection.startIdx - endIdx = _dateCellSelection.endIdx - } - - _this2.setState({ - selecting: true, - startIdx: startIdx, - endIdx: endIdx, - }) - }) - selector.on('beforeSelect', function (box) { - if (_this2.props.selectable !== 'ignoreEvents') return - return !isEvent(_this2.containerRef.current, box) - }) - selector.on('click', function (point) { - return selectorClicksHandler(point, 'click') - }) - selector.on('doubleClick', function (point) { - return selectorClicksHandler(point, 'doubleClick') - }) - selector.on('select', function (bounds) { - _this2._selectSlot( - _objectSpread( - _objectSpread({}, _this2.state), - {}, - { - action: 'select', - bounds: bounds, - } - ) - ) - - _this2._initial = {} - - _this2.setState({ - selecting: false, - }) - - notify(_this2.props.onSelectEnd, [_this2.state]) - }) - }, - }, - { - key: '_teardownSelectable', - value: function _teardownSelectable() { - if (!this._selector) return - - this._selector.teardown() - - this._selector = null - }, - }, - { - key: '_selectSlot', - value: function _selectSlot(_ref) { - var endIdx = _ref.endIdx, - startIdx = _ref.startIdx, - action = _ref.action, - bounds = _ref.bounds, - box = _ref.box - if (endIdx !== -1 && startIdx !== -1) - this.props.onSelectSlot && - this.props.onSelectSlot({ - start: startIdx, - end: endIdx, - action: action, - bounds: bounds, - box: box, - resourceId: this.props.resourceId, - }) - }, - }, - ]) - - return BackgroundCells -})(React.Component) - -/* eslint-disable react/prop-types */ - -var EventRowMixin = { - propTypes: { - slotMetrics: PropTypes.object.isRequired, - selected: PropTypes.object, - isAllDay: PropTypes.bool, - accessors: PropTypes.object.isRequired, - localizer: PropTypes.object.isRequired, - components: PropTypes.object.isRequired, - getters: PropTypes.object.isRequired, - onSelect: PropTypes.func, - onDoubleClick: PropTypes.func, - onKeyPress: PropTypes.func, - }, - defaultProps: { - segments: [], - selected: {}, - }, - renderEvent: function renderEvent(props, event) { - var selected = props.selected - props.isAllDay - var accessors = props.accessors, - getters = props.getters, - onSelect = props.onSelect, - onDoubleClick = props.onDoubleClick, - onKeyPress = props.onKeyPress, - localizer = props.localizer, - slotMetrics = props.slotMetrics, - components = props.components, - resizable = props.resizable - var continuesPrior = slotMetrics.continuesPrior(event) - var continuesAfter = slotMetrics.continuesAfter(event) - return /*#__PURE__*/ React.createElement(EventCell, { - event: event, - getters: getters, - localizer: localizer, - accessors: accessors, - components: components, - onSelect: onSelect, - onDoubleClick: onDoubleClick, - onKeyPress: onKeyPress, - continuesPrior: continuesPrior, - continuesAfter: continuesAfter, - slotStart: slotMetrics.first, - slotEnd: slotMetrics.last, - selected: isSelected(event, selected), - resizable: resizable, - }) - }, - renderSpan: function renderSpan(slots, len, key) { - var content = - arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ' ' - var per = (Math.abs(len) / slots) * 100 + '%' - return /*#__PURE__*/ React.createElement( - 'div', - { - key: key, - className: 'rbc-row-segment', // IE10/11 need max-width. flex-basis doesn't respect box-sizing - style: { - WebkitFlexBasis: per, - flexBasis: per, - maxWidth: per, - }, - }, - content - ) - }, -} - -var EventRow = /*#__PURE__*/ (function (_React$Component) { - _inherits(EventRow, _React$Component) - - var _super = _createSuper(EventRow) - - function EventRow() { - _classCallCheck(this, EventRow) - - return _super.apply(this, arguments) - } - - _createClass(EventRow, [ - { - key: 'render', - value: function render() { - var _this = this - - var _this$props = this.props, - segments = _this$props.segments, - slots = _this$props.slotMetrics.slots, - className = _this$props.className - var lastEnd = 1 - return /*#__PURE__*/ React.createElement( - 'div', - { - className: clsx(className, 'rbc-row'), - }, - segments.reduce(function (row, _ref, li) { - var event = _ref.event, - left = _ref.left, - right = _ref.right, - span = _ref.span - var key = '_lvl_' + li - var gap = left - lastEnd - var content = EventRowMixin.renderEvent(_this.props, event) - if (gap) - row.push( - EventRowMixin.renderSpan(slots, gap, ''.concat(key, '_gap')) - ) - row.push(EventRowMixin.renderSpan(slots, span, key, content)) - lastEnd = right + 1 - return row - }, []) - ) - }, - }, - ]) - - return EventRow -})(React.Component) - -EventRow.defaultProps = _objectSpread({}, EventRowMixin.defaultProps) - -function endOfRange(_ref) { - var dateRange = _ref.dateRange, - _ref$unit = _ref.unit, - unit = _ref$unit === void 0 ? 'day' : _ref$unit, - localizer = _ref.localizer - return { - first: dateRange[0], - last: localizer.add(dateRange[dateRange.length - 1], 1, unit), - } -} // properly calculating segments requires working with dates in -// the timezone we're working with, so we use the localizer - -function eventSegments(event, range, accessors, localizer) { - var _endOfRange = endOfRange({ - dateRange: range, - localizer: localizer, - }), - first = _endOfRange.first, - last = _endOfRange.last - - var slots = localizer.diff(first, last, 'day') - var start = localizer.max( - localizer.startOf(accessors.start(event), 'day'), - first - ) - var end = localizer.min(localizer.ceil(accessors.end(event), 'day'), last) - var padding = findIndex(range, function (x) { - return localizer.isSameDate(x, start) - }) - var span = localizer.diff(start, end, 'day') - span = Math.min(span, slots) // The segmentOffset is necessary when adjusting for timezones - // ahead of the browser timezone - - span = Math.max(span - localizer.segmentOffset, 1) - return { - event: event, - span: span, - left: padding + 1, - right: Math.max(padding + span, 1), - } -} -function eventLevels(rowSegments) { - var limit = - arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity - var i, - j, - seg, - levels = [], - extra = [] - - for (i = 0; i < rowSegments.length; i++) { - seg = rowSegments[i] - - for (j = 0; j < levels.length; j++) { - if (!segsOverlap(seg, levels[j])) break - } - - if (j >= limit) { - extra.push(seg) - } else { - ;(levels[j] || (levels[j] = [])).push(seg) - } - } - - for (i = 0; i < levels.length; i++) { - levels[i].sort(function (a, b) { - return a.left - b.left - }) //eslint-disable-line - } - - return { - levels: levels, - extra: extra, - } -} -function inRange(e, start, end, accessors, localizer) { - var event = { - start: accessors.start(e), - end: accessors.end(e), - } - var range = { - start: start, - end: end, - } - return localizer.inEventRange({ - event: event, - range: range, - }) -} -function segsOverlap(seg, otherSegs) { - return otherSegs.some(function (otherSeg) { - return otherSeg.left <= seg.right && otherSeg.right >= seg.left - }) -} -function sortEvents(eventA, eventB, accessors, localizer) { - var evtA = { - start: accessors.start(eventA), - end: accessors.end(eventA), - allDay: accessors.allDay(eventA), - } - var evtB = { - start: accessors.start(eventB), - end: accessors.end(eventB), - allDay: accessors.allDay(eventB), - } - return localizer.sortEvents({ - evtA: evtA, - evtB: evtB, - }) -} - -var isSegmentInSlot$1 = function isSegmentInSlot(seg, slot) { - return seg.left <= slot && seg.right >= slot -} - -var eventsInSlot = function eventsInSlot(segments, slot) { - return segments.filter(function (seg) { - return isSegmentInSlot$1(seg, slot) - }).length -} - -var EventEndingRow = /*#__PURE__*/ (function (_React$Component) { - _inherits(EventEndingRow, _React$Component) - - var _super = _createSuper(EventEndingRow) - - function EventEndingRow() { - _classCallCheck(this, EventEndingRow) - - return _super.apply(this, arguments) - } - - _createClass(EventEndingRow, [ - { - key: 'render', - value: function render() { - var _this$props = this.props, - segments = _this$props.segments, - slots = _this$props.slotMetrics.slots - var rowSegments = eventLevels(segments).levels[0] - var current = 1, - lastEnd = 1, - row = [] - - while (current <= slots) { - var key = '_lvl_' + current - - var _ref = - rowSegments.filter(function (seg) { - return isSegmentInSlot$1(seg, current) - })[0] || {}, - event = _ref.event, - left = _ref.left, - right = _ref.right, - span = _ref.span //eslint-disable-line - - if (!event) { - current++ - continue - } - - var gap = Math.max(0, left - lastEnd) - - if (this.canRenderSlotEvent(left, span)) { - var content = EventRowMixin.renderEvent(this.props, event) - - if (gap) { - row.push(EventRowMixin.renderSpan(slots, gap, key + '_gap')) - } - - row.push(EventRowMixin.renderSpan(slots, span, key, content)) - lastEnd = current = right + 1 - } else { - if (gap) { - row.push(EventRowMixin.renderSpan(slots, gap, key + '_gap')) - } - - row.push( - EventRowMixin.renderSpan( - slots, - 1, - key, - this.renderShowMore(segments, current) - ) - ) - lastEnd = current = current + 1 - } - } - - return /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row', - }, - row - ) - }, - }, - { - key: 'canRenderSlotEvent', - value: function canRenderSlotEvent(slot, span) { - var segments = this.props.segments - return range$1(slot, slot + span).every(function (s) { - var count = eventsInSlot(segments, s) - return count === 1 - }) - }, - }, - { - key: 'renderShowMore', - value: function renderShowMore(segments, slot) { - var _this = this - - var localizer = this.props.localizer - var count = eventsInSlot(segments, slot) - return count - ? /*#__PURE__*/ React.createElement( - 'button', - { - type: 'button', - key: 'sm_' + slot, - className: clsx('rbc-button-link', 'rbc-show-more'), - onClick: function onClick(e) { - return _this.showMore(slot, e) - }, - }, - localizer.messages.showMore(count) - ) - : false - }, - }, - { - key: 'showMore', - value: function showMore(slot, e) { - e.preventDefault() - e.stopPropagation() - this.props.onShowMore(slot, e.target) - }, - }, - ]) - - return EventEndingRow -})(React.Component) - -EventEndingRow.defaultProps = _objectSpread({}, EventRowMixin.defaultProps) - -var ScrollableWeekWrapper = function ScrollableWeekWrapper(_ref) { - var children = _ref.children - return /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row-content-scroll-container', - }, - children - ) -} - -var isSegmentInSlot = function isSegmentInSlot(seg, slot) { - return seg.left <= slot && seg.right >= slot -} - -var isEqual = function isEqual(a, b) { - return a[0].range === b[0].range && a[0].events === b[0].events -} - -function getSlotMetrics$1() { - return memoize(function (options) { - var range = options.range, - events = options.events, - maxRows = options.maxRows, - minRows = options.minRows, - accessors = options.accessors, - localizer = options.localizer - - var _endOfRange = endOfRange({ - dateRange: range, - localizer: localizer, - }), - first = _endOfRange.first, - last = _endOfRange.last - - var segments = events.map(function (evt) { - return eventSegments(evt, range, accessors, localizer) - }) - - var _eventLevels = eventLevels(segments, Math.max(maxRows - 1, 1)), - levels = _eventLevels.levels, - extra = _eventLevels.extra - - while (levels.length < minRows) { - levels.push([]) - } - - return { - first: first, - last: last, - levels: levels, - extra: extra, - range: range, - slots: range.length, - clone: function clone(args) { - var metrics = getSlotMetrics$1() - return metrics(_objectSpread(_objectSpread({}, options), args)) - }, - getDateForSlot: function getDateForSlot(slotNumber) { - return range[slotNumber] - }, - getSlotForDate: function getSlotForDate(date) { - return range.find(function (r) { - return localizer.isSameDate(r, date) - }) - }, - getEventsForSlot: function getEventsForSlot(slot) { - return segments - .filter(function (seg) { - return isSegmentInSlot(seg, slot) - }) - .map(function (seg) { - return seg.event - }) - }, - continuesPrior: function continuesPrior(event) { - return localizer.continuesPrior(accessors.start(event), first) - }, - continuesAfter: function continuesAfter(event) { - var start = accessors.start(event) - var end = accessors.end(event) - return localizer.continuesAfter(start, end, last) - }, - } - }, isEqual) -} - -var DateContentRow = /*#__PURE__*/ (function (_React$Component) { - _inherits(DateContentRow, _React$Component) - - var _super = _createSuper(DateContentRow) - - function DateContentRow() { - var _this - - _classCallCheck(this, DateContentRow) - - for ( - var _len = arguments.length, args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key] - } - - _this = _super.call.apply(_super, [this].concat(args)) - - _this.handleSelectSlot = function (slot) { - var _this$props = _this.props, - range = _this$props.range, - onSelectSlot = _this$props.onSelectSlot - onSelectSlot(range.slice(slot.start, slot.end + 1), slot) - } - - _this.handleShowMore = function (slot, target) { - var _this$props2 = _this.props, - range = _this$props2.range, - onShowMore = _this$props2.onShowMore - - var metrics = _this.slotMetrics(_this.props) - - var row = qsa(_this.containerRef.current, '.rbc-row-bg')[0] - var cell - if (row) cell = row.children[slot - 1] - var events = metrics.getEventsForSlot(slot) - onShowMore(events, range[slot - 1], cell, slot, target) - } - - _this.getContainer = function () { - var container = _this.props.container - return container ? container() : _this.containerRef.current - } - - _this.renderHeadingCell = function (date, index) { - var _this$props3 = _this.props, - renderHeader = _this$props3.renderHeader, - getNow = _this$props3.getNow, - localizer = _this$props3.localizer - return renderHeader({ - date: date, - key: 'header_'.concat(index), - className: clsx( - 'rbc-date-cell', - localizer.isSameDate(date, getNow()) && 'rbc-now' - ), - }) - } - - _this.renderDummy = function () { - var _this$props4 = _this.props, - className = _this$props4.className, - range = _this$props4.range, - renderHeader = _this$props4.renderHeader, - showAllEvents = _this$props4.showAllEvents - return /*#__PURE__*/ React.createElement( - 'div', - { - className: className, - ref: _this.containerRef, - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: clsx( - 'rbc-row-content', - showAllEvents && 'rbc-row-content-scrollable' - ), - }, - renderHeader && - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row', - ref: _this.headingRowRef, - }, - range.map(_this.renderHeadingCell) - ), - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row', - ref: _this.eventRowRef, - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row-segment', - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-event', - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-event-content', - }, - '\xA0' - ) - ) - ) - ) - ) - ) - } - - _this.containerRef = /*#__PURE__*/ createRef() - _this.headingRowRef = /*#__PURE__*/ createRef() - _this.eventRowRef = /*#__PURE__*/ createRef() - _this.slotMetrics = getSlotMetrics$1() - return _this - } - - _createClass(DateContentRow, [ - { - key: 'getRowLimit', - value: function getRowLimit() { - var _this$headingRowRef - - /* Guessing this only gets called on the dummyRow */ - var eventHeight = getHeight(this.eventRowRef.current) - var headingHeight = - (_this$headingRowRef = this.headingRowRef) !== null && - _this$headingRowRef !== void 0 && - _this$headingRowRef.current - ? getHeight(this.headingRowRef.current) - : 0 - var eventSpace = getHeight(this.containerRef.current) - headingHeight - return Math.max(Math.floor(eventSpace / eventHeight), 1) - }, - }, - { - key: 'render', - value: function render() { - var _this$props5 = this.props, - date = _this$props5.date, - rtl = _this$props5.rtl, - range = _this$props5.range, - className = _this$props5.className, - selected = _this$props5.selected, - selectable = _this$props5.selectable, - renderForMeasure = _this$props5.renderForMeasure, - accessors = _this$props5.accessors, - getters = _this$props5.getters, - components = _this$props5.components, - getNow = _this$props5.getNow, - renderHeader = _this$props5.renderHeader, - onSelect = _this$props5.onSelect, - localizer = _this$props5.localizer, - onSelectStart = _this$props5.onSelectStart, - onSelectEnd = _this$props5.onSelectEnd, - onDoubleClick = _this$props5.onDoubleClick, - onKeyPress = _this$props5.onKeyPress, - resourceId = _this$props5.resourceId, - longPressThreshold = _this$props5.longPressThreshold, - isAllDay = _this$props5.isAllDay, - resizable = _this$props5.resizable, - showAllEvents = _this$props5.showAllEvents - if (renderForMeasure) return this.renderDummy() - var metrics = this.slotMetrics(this.props) - var levels = metrics.levels, - extra = metrics.extra - var ScrollableWeekComponent = showAllEvents - ? ScrollableWeekWrapper - : NoopWrapper - var WeekWrapper = components.weekWrapper - var eventRowProps = { - selected: selected, - accessors: accessors, - getters: getters, - localizer: localizer, - components: components, - onSelect: onSelect, - onDoubleClick: onDoubleClick, - onKeyPress: onKeyPress, - resourceId: resourceId, - slotMetrics: metrics, - resizable: resizable, - } - return /*#__PURE__*/ React.createElement( - 'div', - { - className: className, - role: 'rowgroup', - ref: this.containerRef, - }, - /*#__PURE__*/ React.createElement(BackgroundCells, { - localizer: localizer, - date: date, - getNow: getNow, - rtl: rtl, - range: range, - selectable: selectable, - container: this.getContainer, - getters: getters, - onSelectStart: onSelectStart, - onSelectEnd: onSelectEnd, - onSelectSlot: this.handleSelectSlot, - components: components, - longPressThreshold: longPressThreshold, - resourceId: resourceId, - }), - /*#__PURE__*/ React.createElement( - 'div', - { - className: clsx( - 'rbc-row-content', - showAllEvents && 'rbc-row-content-scrollable' - ), - role: 'row', - }, - renderHeader && - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row ', - ref: this.headingRowRef, - }, - range.map(this.renderHeadingCell) - ), - /*#__PURE__*/ React.createElement( - ScrollableWeekComponent, - null, - /*#__PURE__*/ React.createElement( - WeekWrapper, - Object.assign( - { - isAllDay: isAllDay, - }, - eventRowProps - ), - levels.map(function (segs, idx) { - return /*#__PURE__*/ React.createElement( - EventRow, - Object.assign( - { - key: idx, - segments: segs, - }, - eventRowProps - ) - ) - }), - !!extra.length && - /*#__PURE__*/ React.createElement( - EventEndingRow, - Object.assign( - { - segments: extra, - onShowMore: this.handleShowMore, - }, - eventRowProps - ) - ) - ) - ) - ) - ) - }, - }, - ]) - - return DateContentRow -})(React.Component) - -DateContentRow.defaultProps = { - minRows: 0, - maxRows: Infinity, -} - -var Header = function Header(_ref) { - var label = _ref.label - return /*#__PURE__*/ React.createElement( - 'span', - { - role: 'columnheader', - 'aria-sort': 'none', - }, - label - ) -} - -var DateHeader = function DateHeader(_ref) { - var label = _ref.label, - drilldownView = _ref.drilldownView, - onDrillDown = _ref.onDrillDown - - if (!drilldownView) { - return /*#__PURE__*/ React.createElement('span', null, label) - } - - return /*#__PURE__*/ React.createElement( - 'button', - { - type: 'button', - className: 'rbc-button-link', - onClick: onDrillDown, - role: 'cell', - }, - label - ) -} - -var _excluded$6 = ['date', 'className'] - -var eventsForWeek = function eventsForWeek( - evts, - start, - end, - accessors, - localizer -) { - return evts.filter(function (e) { - return inRange(e, start, end, accessors, localizer) - }) -} - -var MonthView = /*#__PURE__*/ (function (_React$Component) { - _inherits(MonthView, _React$Component) - - var _super = _createSuper(MonthView) - - function MonthView() { - var _this - - _classCallCheck(this, MonthView) - - for ( - var _len = arguments.length, _args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - _args[_key] = arguments[_key] - } - - _this = _super.call.apply(_super, [this].concat(_args)) - - _this.getContainer = function () { - return _this.containerRef.current - } - - _this.renderWeek = function (week, weekIdx) { - var _this$props = _this.props, - events = _this$props.events, - components = _this$props.components, - selectable = _this$props.selectable, - getNow = _this$props.getNow, - selected = _this$props.selected, - date = _this$props.date, - localizer = _this$props.localizer, - longPressThreshold = _this$props.longPressThreshold, - accessors = _this$props.accessors, - getters = _this$props.getters, - showAllEvents = _this$props.showAllEvents - var _this$state = _this.state, - needLimitMeasure = _this$state.needLimitMeasure, - rowLimit = _this$state.rowLimit // let's not mutate props - - var weeksEvents = eventsForWeek( - _toConsumableArray(events), - week[0], - week[week.length - 1], - accessors, - localizer - ) - weeksEvents.sort(function (a, b) { - return sortEvents(a, b, accessors, localizer) - }) - return /*#__PURE__*/ React.createElement(DateContentRow, { - key: weekIdx, - ref: weekIdx === 0 ? _this.slotRowRef : undefined, - container: _this.getContainer, - className: 'rbc-month-row', - getNow: getNow, - date: date, - range: week, - events: weeksEvents, - maxRows: showAllEvents ? Infinity : rowLimit, - selected: selected, - selectable: selectable, - components: components, - accessors: accessors, - getters: getters, - localizer: localizer, - renderHeader: _this.readerDateHeading, - renderForMeasure: needLimitMeasure, - onShowMore: _this.handleShowMore, - onSelect: _this.handleSelectEvent, - onDoubleClick: _this.handleDoubleClickEvent, - onKeyPress: _this.handleKeyPressEvent, - onSelectSlot: _this.handleSelectSlot, - longPressThreshold: longPressThreshold, - rtl: _this.props.rtl, - resizable: _this.props.resizable, - showAllEvents: showAllEvents, - }) - } - - _this.readerDateHeading = function (_ref) { - var date = _ref.date, - className = _ref.className, - props = _objectWithoutProperties(_ref, _excluded$6) - - var _this$props2 = _this.props, - currentDate = _this$props2.date, - getDrilldownView = _this$props2.getDrilldownView, - localizer = _this$props2.localizer - var isOffRange = localizer.neq(date, currentDate, 'month') - var isCurrent = localizer.isSameDate(date, currentDate) - var drilldownView = getDrilldownView(date) - var label = localizer.format(date, 'dateFormat') - var DateHeaderComponent = _this.props.components.dateHeader || DateHeader - return /*#__PURE__*/ React.createElement( - 'div', - Object.assign({}, props, { - className: clsx( - className, - isOffRange && 'rbc-off-range', - isCurrent && 'rbc-current' - ), - role: 'cell', - }), - /*#__PURE__*/ React.createElement(DateHeaderComponent, { - label: label, - date: date, - drilldownView: drilldownView, - isOffRange: isOffRange, - onDrillDown: function onDrillDown(e) { - return _this.handleHeadingClick(date, drilldownView, e) - }, - }) - ) - } - - _this.handleSelectSlot = function (range, slotInfo) { - _this._pendingSelection = _this._pendingSelection.concat(range) - clearTimeout(_this._selectTimer) - _this._selectTimer = setTimeout(function () { - return _this.selectDates(slotInfo) - }) - } - - _this.handleHeadingClick = function (date, view, e) { - e.preventDefault() - - _this.clearSelection() - - notify(_this.props.onDrillDown, [date, view]) - } - - _this.handleSelectEvent = function () { - _this.clearSelection() - - for ( - var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; - _key2 < _len2; - _key2++ - ) { - args[_key2] = arguments[_key2] - } - - notify(_this.props.onSelectEvent, args) - } - - _this.handleDoubleClickEvent = function () { - _this.clearSelection() - - for ( - var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; - _key3 < _len3; - _key3++ - ) { - args[_key3] = arguments[_key3] - } - - notify(_this.props.onDoubleClickEvent, args) - } - - _this.handleKeyPressEvent = function () { - _this.clearSelection() - - for ( - var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; - _key4 < _len4; - _key4++ - ) { - args[_key4] = arguments[_key4] - } - - notify(_this.props.onKeyPressEvent, args) - } - - _this.handleShowMore = function (events, date, cell, slot, target) { - var _this$props3 = _this.props, - popup = _this$props3.popup, - onDrillDown = _this$props3.onDrillDown, - onShowMore = _this$props3.onShowMore, - getDrilldownView = _this$props3.getDrilldownView, - doShowMoreDrillDown = _this$props3.doShowMoreDrillDown //cancel any pending selections so only the event click goes through. - - _this.clearSelection() - - if (popup) { - var position = getPosition$1(cell, _this.containerRef.current) - - _this.setState({ - overlay: { - date: date, - events: events, - position: position, - target: target, - }, - }) - } else if (doShowMoreDrillDown) { - notify(onDrillDown, [date, getDrilldownView(date) || views.DAY]) - } - - notify(onShowMore, [events, date, slot]) - } - - _this.overlayDisplay = function () { - _this.setState({ - overlay: null, - }) - } - - _this.state = { - rowLimit: 5, - needLimitMeasure: true, - date: null, - } - _this.containerRef = /*#__PURE__*/ createRef() - _this.slotRowRef = /*#__PURE__*/ createRef() - _this._bgRows = [] - _this._pendingSelection = [] - return _this - } - - _createClass( - MonthView, - [ - { - key: 'componentDidMount', - value: function componentDidMount() { - var _this2 = this - - var running - if (this.state.needLimitMeasure) this.measureRowLimit(this.props) - window.addEventListener( - 'resize', - (this._resizeListener = function () { - if (!running) { - animationFrame.request(function () { - running = false - - _this2.setState({ - needLimitMeasure: true, - }) //eslint-disable-line - }) - } - }), - false - ) - }, - }, - { - key: 'componentDidUpdate', - value: function componentDidUpdate() { - if (this.state.needLimitMeasure) this.measureRowLimit(this.props) - }, - }, - { - key: 'componentWillUnmount', - value: function componentWillUnmount() { - window.removeEventListener('resize', this._resizeListener, false) - }, - }, - { - key: 'render', - value: function render() { - var _this$props4 = this.props, - date = _this$props4.date, - localizer = _this$props4.localizer, - className = _this$props4.className, - month = localizer.visibleDays(date, localizer), - weeks = chunk(month, 7) - this._weekCount = weeks.length - return /*#__PURE__*/ React.createElement( - 'div', - { - className: clsx('rbc-month-view', className), - role: 'table', - 'aria-label': 'Month View', - ref: this.containerRef, - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row rbc-month-header', - role: 'row', - }, - this.renderHeaders(weeks[0]) - ), - weeks.map(this.renderWeek), - this.props.popup && this.renderOverlay() - ) - }, - }, - { - key: 'renderHeaders', - value: function renderHeaders(row) { - var _this$props5 = this.props, - localizer = _this$props5.localizer, - components = _this$props5.components - var first = row[0] - var last = row[row.length - 1] - var HeaderComponent = components.header || Header - return localizer.range(first, last, 'day').map(function (day, idx) { - return /*#__PURE__*/ React.createElement( - 'div', - { - key: 'header_' + idx, - className: 'rbc-header', - }, - /*#__PURE__*/ React.createElement(HeaderComponent, { - date: day, - localizer: localizer, - label: localizer.format(day, 'weekdayFormat'), - }) - ) - }) - }, - }, - { - key: 'renderOverlay', - value: function renderOverlay() { - var _this$state$overlay, - _this$state2, - _this3 = this - - var overlay = - (_this$state$overlay = - (_this$state2 = this.state) === null || _this$state2 === void 0 - ? void 0 - : _this$state2.overlay) !== null && - _this$state$overlay !== void 0 - ? _this$state$overlay - : {} - var _this$props6 = this.props, - accessors = _this$props6.accessors, - localizer = _this$props6.localizer, - components = _this$props6.components, - getters = _this$props6.getters, - selected = _this$props6.selected, - popupOffset = _this$props6.popupOffset, - handleDragStart = _this$props6.handleDragStart - - var onHide = function onHide() { - return _this3.setState({ - overlay: null, - }) - } - - return /*#__PURE__*/ React.createElement(PopOverlay, { - overlay: overlay, - accessors: accessors, - localizer: localizer, - components: components, - getters: getters, - selected: selected, - popupOffset: popupOffset, - ref: this.containerRef, - handleKeyPressEvent: this.handleKeyPressEvent, - handleSelectEvent: this.handleSelectEvent, - handleDoubleClickEvent: this.handleDoubleClickEvent, - handleDragStart: handleDragStart, - show: !!overlay.position, - overlayDisplay: this.overlayDisplay, - onHide: onHide, - }) - /* return ( - this.setState({ overlay: null })} - target={() => overlay.target} - > - {({ props }) => ( - - )} - - ) */ - }, - }, - { - key: 'measureRowLimit', - value: function measureRowLimit() { - this.setState({ - needLimitMeasure: false, - rowLimit: this.slotRowRef.current.getRowLimit(), - }) - }, - }, - { - key: 'selectDates', - value: function selectDates(slotInfo) { - var slots = this._pendingSelection.slice() - - this._pendingSelection = [] - slots.sort(function (a, b) { - return +a - +b - }) - var start = new Date(slots[0]) - var end = new Date(slots[slots.length - 1]) - end.setDate(slots[slots.length - 1].getDate() + 1) - notify(this.props.onSelectSlot, { - slots: slots, - start: start, - end: end, - action: slotInfo.action, - bounds: slotInfo.bounds, - box: slotInfo.box, - }) - }, - }, - { - key: 'clearSelection', - value: function clearSelection() { - clearTimeout(this._selectTimer) - this._pendingSelection = [] - }, - }, - ], - [ - { - key: 'getDerivedStateFromProps', - value: function getDerivedStateFromProps(_ref2, state) { - var date = _ref2.date, - localizer = _ref2.localizer - return { - date: date, - needLimitMeasure: localizer.neq(date, state.date, 'month'), - } - }, - }, - ] - ) - - return MonthView -})(React.Component) - -MonthView.range = function (date, _ref3) { - var localizer = _ref3.localizer - var start = localizer.firstVisibleDay(date, localizer) - var end = localizer.lastVisibleDay(date, localizer) - return { - start: start, - end: end, - } -} - -MonthView.navigate = function (date, action, _ref4) { - var localizer = _ref4.localizer - - switch (action) { - case navigate.PREVIOUS: - return localizer.add(date, -1, 'month') - - case navigate.NEXT: - return localizer.add(date, 1, 'month') - - default: - return date - } -} - -MonthView.title = function (date, _ref5) { - var localizer = _ref5.localizer - return localizer.format(date, 'monthHeaderFormat') -} - -var getKey = function getKey(_ref) { - var min = _ref.min, - max = _ref.max, - step = _ref.step, - slots = _ref.slots, - localizer = _ref.localizer - return ( - ''.concat(+localizer.startOf(min, 'minutes')) + - ''.concat(+localizer.startOf(max, 'minutes')) + - ''.concat(step, '-').concat(slots) - ) -} - -function getSlotMetrics(_ref2) { - var start = _ref2.min, - end = _ref2.max, - step = _ref2.step, - timeslots = _ref2.timeslots, - localizer = _ref2.localizer - var key = getKey({ - start: start, - end: end, - step: step, - timeslots: timeslots, - localizer: localizer, - }) // DST differences are handled inside the localizer - - var totalMin = 1 + localizer.getTotalMin(start, end) - var minutesFromMidnight = localizer.getMinutesFromMidnight(start) - var numGroups = Math.ceil((totalMin - 1) / (step * timeslots)) - var numSlots = numGroups * timeslots - var groups = new Array(numGroups) - var slots = new Array(numSlots) // Each slot date is created from "zero", instead of adding `step` to - // the previous one, in order to avoid DST oddities - - for (var grp = 0; grp < numGroups; grp++) { - groups[grp] = new Array(timeslots) - - for (var slot = 0; slot < timeslots; slot++) { - var slotIdx = grp * timeslots + slot - var minFromStart = slotIdx * step // A date with total minutes calculated from the start of the day - - slots[slotIdx] = groups[grp][slot] = localizer.getSlotDate( - start, - minutesFromMidnight, - minFromStart - ) - } - } // Necessary to be able to select up until the last timeslot in a day - - var lastSlotMinFromStart = slots.length * step - slots.push( - localizer.getSlotDate(start, minutesFromMidnight, lastSlotMinFromStart) - ) - - function positionFromDate(date) { - var diff = - localizer.diff(start, date, 'minutes') + - localizer.getDstOffset(start, date) - return Math.min(diff, totalMin) - } - - return { - groups: groups, - update: function update(args) { - if (getKey(args) !== key) return getSlotMetrics(args) - return this - }, - dateIsInGroup: function dateIsInGroup(date, groupIndex) { - var nextGroup = groups[groupIndex + 1] - return localizer.inRange( - date, - groups[groupIndex][0], - nextGroup ? nextGroup[0] : end, - 'minutes' - ) - }, - nextSlot: function nextSlot(slot) { - var next = slots[Math.min(slots.indexOf(slot) + 1, slots.length - 1)] // in the case of the last slot we won't a long enough range so manually get it - - if (next === slot) next = localizer.add(slot, step, 'minutes') - return next - }, - closestSlotToPosition: function closestSlotToPosition(percent) { - var slot = Math.min( - slots.length - 1, - Math.max(0, Math.floor(percent * numSlots)) - ) - return slots[slot] - }, - closestSlotFromPoint: function closestSlotFromPoint(point, boundaryRect) { - var range = Math.abs(boundaryRect.top - boundaryRect.bottom) - return this.closestSlotToPosition((point.y - boundaryRect.top) / range) - }, - closestSlotFromDate: function closestSlotFromDate(date) { - var offset = - arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0 - if (localizer.lt(date, start, 'minutes')) return slots[0] - if (localizer.gt(date, end, 'minutes')) return slots[slots.length - 1] - var diffMins = localizer.diff(start, date, 'minutes') - return slots[(diffMins - (diffMins % step)) / step + offset] - }, - startsBeforeDay: function startsBeforeDay(date) { - return localizer.lt(date, start, 'day') - }, - startsAfterDay: function startsAfterDay(date) { - return localizer.gt(date, end, 'day') - }, - startsBefore: function startsBefore(date) { - return localizer.lt(localizer.merge(start, date), start, 'minutes') - }, - startsAfter: function startsAfter(date) { - return localizer.gt(localizer.merge(end, date), end, 'minutes') - }, - getRange: function getRange(rangeStart, rangeEnd, ignoreMin, ignoreMax) { - if (!ignoreMin) - rangeStart = localizer.min(end, localizer.max(start, rangeStart)) - if (!ignoreMax) - rangeEnd = localizer.min(end, localizer.max(start, rangeEnd)) - var rangeStartMin = positionFromDate(rangeStart) - var rangeEndMin = positionFromDate(rangeEnd) - var top = - rangeEndMin > step * numSlots && !localizer.eq(end, rangeEnd) - ? ((rangeStartMin - step) / (step * numSlots)) * 100 - : (rangeStartMin / (step * numSlots)) * 100 - return { - top: top, - height: (rangeEndMin / (step * numSlots)) * 100 - top, - start: positionFromDate(rangeStart), - startDate: rangeStart, - end: positionFromDate(rangeEnd), - endDate: rangeEnd, - } - }, - getCurrentTimePosition: function getCurrentTimePosition(rangeStart) { - var rangeStartMin = positionFromDate(rangeStart) - var top = (rangeStartMin / (step * numSlots)) * 100 - return top - }, - } -} - -var Event = /*#__PURE__*/ (function () { - function Event(data, _ref) { - var accessors = _ref.accessors, - slotMetrics = _ref.slotMetrics - - _classCallCheck(this, Event) - - var _slotMetrics$getRange = slotMetrics.getRange( - accessors.start(data), - accessors.end(data) - ), - start = _slotMetrics$getRange.start, - startDate = _slotMetrics$getRange.startDate, - end = _slotMetrics$getRange.end, - endDate = _slotMetrics$getRange.endDate, - top = _slotMetrics$getRange.top, - height = _slotMetrics$getRange.height - - this.start = start - this.end = end - this.startMs = +startDate - this.endMs = +endDate - this.top = top - this.height = height - this.data = data - } - /** - * The event's width without any overlap. - */ - - _createClass(Event, [ - { - key: '_width', - get: function get() { - // The container event's width is determined by the maximum number of - // events in any of its rows. - if (this.rows) { - var columns = - this.rows.reduce( - function (max, row) { - return Math.max(max, row.leaves.length + 1) - }, // add itself - 0 - ) + 1 // add the container - - return 100 / columns - } - - var availableWidth = 100 - this.container._width // The row event's width is the space left by the container, divided - // among itself and its leaves. - - if (this.leaves) { - return availableWidth / (this.leaves.length + 1) - } // The leaf event's width is determined by its row's width - - return this.row._width - }, - /** - * The event's calculated width, possibly with extra width added for - * overlapping effect. - */ - }, - { - key: 'width', - get: function get() { - var noOverlap = this._width - var overlap = Math.min(100, this._width * 1.7) // Containers can always grow. - - if (this.rows) { - return overlap - } // Rows can grow if they have leaves. - - if (this.leaves) { - return this.leaves.length > 0 ? overlap : noOverlap - } // Leaves can grow unless they're the last item in a row. - - var leaves = this.row.leaves - var index = leaves.indexOf(this) - return index === leaves.length - 1 ? noOverlap : overlap - }, - }, - { - key: 'xOffset', - get: function get() { - // Containers have no offset. - if (this.rows) return 0 // Rows always start where their container ends. - - if (this.leaves) return this.container._width // Leaves are spread out evenly on the space left by its row. - - var _this$row = this.row, - leaves = _this$row.leaves, - xOffset = _this$row.xOffset, - _width = _this$row._width - var index = leaves.indexOf(this) + 1 - return xOffset + index * _width - }, - }, - ]) - - return Event -})() -/** - * Return true if event a and b is considered to be on the same row. - */ - -function onSameRow(a, b, minimumStartDifference) { - return ( - // Occupies the same start slot. - Math.abs(b.start - a.start) < minimumStartDifference || // A's start slot overlaps with b's end slot. - (b.start > a.start && b.start < a.end) - ) -} - -function sortByRender(events) { - var sortedByTime = sortBy(events, [ - 'startMs', - function (e) { - return -e.endMs - }, - ]) - var sorted = [] - - while (sortedByTime.length > 0) { - var event = sortedByTime.shift() - sorted.push(event) - - for (var i = 0; i < sortedByTime.length; i++) { - var test = sortedByTime[i] // Still inside this event, look for next. - - if (event.endMs > test.startMs) continue // We've found the first event of the next event group. - // If that event is not right next to our current event, we have to - // move it here. - - if (i > 0) { - var _event = sortedByTime.splice(i, 1)[0] - sorted.push(_event) - } // We've already found the next event group, so stop looking. - - break - } - } - - return sorted -} - -function getStyledEvents$1(_ref2) { - var events = _ref2.events, - minimumStartDifference = _ref2.minimumStartDifference, - slotMetrics = _ref2.slotMetrics, - accessors = _ref2.accessors - // Create proxy events and order them so that we don't have - // to fiddle with z-indexes. - var proxies = events.map(function (event) { - return new Event(event, { - slotMetrics: slotMetrics, - accessors: accessors, - }) - }) - var eventsInRenderOrder = sortByRender(proxies) // Group overlapping events, while keeping order. - // Every event is always one of: container, row or leaf. - // Containers can contain rows, and rows can contain leaves. - - var containerEvents = [] - - var _loop = function _loop(i) { - var event = eventsInRenderOrder[i] // Check if this event can go into a container event. - - var container = containerEvents.find(function (c) { - return ( - c.end > event.start || - Math.abs(event.start - c.start) < minimumStartDifference - ) - }) // Couldn't find a container — that means this event is a container. - - if (!container) { - event.rows = [] - containerEvents.push(event) - return 'continue' - } // Found a container for the event. - - event.container = container // Check if the event can be placed in an existing row. - // Start looking from behind. - - var row = null - - for (var j = container.rows.length - 1; !row && j >= 0; j--) { - if (onSameRow(container.rows[j], event, minimumStartDifference)) { - row = container.rows[j] - } - } - - if (row) { - // Found a row, so add it. - row.leaves.push(event) - event.row = row - } else { - // Couldn't find a row – that means this event is a row. - event.leaves = [] - container.rows.push(event) - } - } - - for (var i = 0; i < eventsInRenderOrder.length; i++) { - var _ret = _loop(i) - - if (_ret === 'continue') continue - } // Return the original events, along with their styles. - - return eventsInRenderOrder.map(function (event) { - return { - event: event.data, - style: { - top: event.top, - height: event.height, - width: event.width, - xOffset: Math.max(0, event.xOffset), - }, - } - }) -} - -function getMaxIdxDFS(node, maxIdx, visited) { - for (var i = 0; i < node.friends.length; ++i) { - if (visited.indexOf(node.friends[i]) > -1) continue - maxIdx = maxIdx > node.friends[i].idx ? maxIdx : node.friends[i].idx // TODO : trace it by not object but kinda index or something for performance - - visited.push(node.friends[i]) - var newIdx = getMaxIdxDFS(node.friends[i], maxIdx, visited) - maxIdx = maxIdx > newIdx ? maxIdx : newIdx - } - - return maxIdx -} - -function noOverlap(_ref) { - var events = _ref.events, - minimumStartDifference = _ref.minimumStartDifference, - slotMetrics = _ref.slotMetrics, - accessors = _ref.accessors - var styledEvents = getStyledEvents$1({ - events: events, - minimumStartDifference: minimumStartDifference, - slotMetrics: slotMetrics, - accessors: accessors, - }) - styledEvents.sort(function (a, b) { - a = a.style - b = b.style - if (a.top !== b.top) return a.top > b.top ? 1 : -1 - else return a.top + a.height < b.top + b.height ? 1 : -1 - }) - - for (var i = 0; i < styledEvents.length; ++i) { - styledEvents[i].friends = [] - delete styledEvents[i].style.left - delete styledEvents[i].style.left - delete styledEvents[i].idx - delete styledEvents[i].size - } - - for (var _i = 0; _i < styledEvents.length - 1; ++_i) { - var se1 = styledEvents[_i] - var y1 = se1.style.top - var y2 = se1.style.top + se1.style.height - - for (var j = _i + 1; j < styledEvents.length; ++j) { - var se2 = styledEvents[j] - var y3 = se2.style.top - var y4 = se2.style.top + se2.style.height // be friends when overlapped - - if ((y3 <= y1 && y1 <= y4) || (y1 <= y3 && y3 <= y2)) { - // TODO : hashmap would be effective for performance - se1.friends.push(se2) - se2.friends.push(se1) - } - } - } - - for (var _i2 = 0; _i2 < styledEvents.length; ++_i2) { - var se = styledEvents[_i2] - var bitmap = [] - - for (var _j = 0; _j < 100; ++_j) { - bitmap.push(1) - } // 1 means available - - for (var _j2 = 0; _j2 < se.friends.length; ++_j2) { - if (se.friends[_j2].idx !== undefined) bitmap[se.friends[_j2].idx] = 0 - } // 0 means reserved - - se.idx = bitmap.indexOf(1) - } - - for (var _i3 = 0; _i3 < styledEvents.length; ++_i3) { - var size = 0 - if (styledEvents[_i3].size) continue - var allFriends = [] - var maxIdx = getMaxIdxDFS(styledEvents[_i3], 0, allFriends) - size = 100 / (maxIdx + 1) - styledEvents[_i3].size = size - - for (var _j3 = 0; _j3 < allFriends.length; ++_j3) { - allFriends[_j3].size = size - } - } - - for (var _i4 = 0; _i4 < styledEvents.length; ++_i4) { - var e = styledEvents[_i4] - e.style.left = e.idx * e.size // stretch to maximum - - var _maxIdx = 0 - - for (var _j4 = 0; _j4 < e.friends.length; ++_j4) { - var idx = e.friends[_j4].idx - _maxIdx = _maxIdx > idx ? _maxIdx : idx - } - - if (_maxIdx <= e.idx) e.size = 100 - e.idx * e.size // padding between events - // for this feature, `width` is not percentage based unit anymore - // it will be used with calc() - - var padding = e.idx === 0 ? 0 : 3 - e.style.width = 'calc('.concat(e.size, '% - ').concat(padding, 'px)') - e.style.height = 'calc('.concat(e.style.height, '% - 2px)') - e.style.xOffset = 'calc(' - .concat(e.style.left, '% + ') - .concat(padding, 'px)') - } - - return styledEvents -} - -/*eslint no-unused-vars: "off"*/ -var DefaultAlgorithms = { - overlap: getStyledEvents$1, - 'no-overlap': noOverlap, -} - -function isFunction(a) { - return !!(a && a.constructor && a.call && a.apply) -} // - -function getStyledEvents(_ref) { - _ref.events - _ref.minimumStartDifference - _ref.slotMetrics - _ref.accessors - var dayLayoutAlgorithm = _ref.dayLayoutAlgorithm - var algorithm = dayLayoutAlgorithm - if (dayLayoutAlgorithm in DefaultAlgorithms) - algorithm = DefaultAlgorithms[dayLayoutAlgorithm] - - if (!isFunction(algorithm)) { - // invalid algorithm - return [] - } - - return algorithm.apply(this, arguments) -} - -var TimeSlotGroup = /*#__PURE__*/ (function (_Component) { - _inherits(TimeSlotGroup, _Component) - - var _super = _createSuper(TimeSlotGroup) - - function TimeSlotGroup() { - _classCallCheck(this, TimeSlotGroup) - - return _super.apply(this, arguments) - } - - _createClass(TimeSlotGroup, [ - { - key: 'render', - value: function render() { - var _this$props = this.props, - renderSlot = _this$props.renderSlot, - resource = _this$props.resource, - group = _this$props.group, - getters = _this$props.getters, - _this$props$component = _this$props.components - _this$props$component = - _this$props$component === void 0 ? {} : _this$props$component - var _this$props$component2 = _this$props$component.timeSlotWrapper, - Wrapper = - _this$props$component2 === void 0 - ? NoopWrapper - : _this$props$component2 - var groupProps = getters ? getters.slotGroupProp() : {} - return /*#__PURE__*/ React.createElement( - 'div', - Object.assign( - { - className: 'rbc-timeslot-group', - }, - groupProps - ), - group.map(function (value, idx) { - var slotProps = getters ? getters.slotProp(value, resource) : {} - return /*#__PURE__*/ React.createElement( - Wrapper, - { - key: idx, - value: value, - resource: resource, - }, - /*#__PURE__*/ React.createElement( - 'div', - Object.assign({}, slotProps, { - className: clsx('rbc-time-slot', slotProps.className), - }), - renderSlot && renderSlot(value, idx) - ) - ) - }) - ) - }, - }, - ]) - - return TimeSlotGroup -})(Component) -TimeSlotGroup.propTypes = - process.env.NODE_ENV !== 'production' - ? { - renderSlot: PropTypes.func, - group: PropTypes.array.isRequired, - resource: PropTypes.any, - components: PropTypes.object, - getters: PropTypes.object, - } - : {} - -function stringifyPercent(v) { - return typeof v === 'string' ? v : v + '%' -} -/* eslint-disable react/prop-types */ - -function TimeGridEvent(props) { - var style = props.style, - className = props.className, - event = props.event, - accessors = props.accessors, - rtl = props.rtl, - selected = props.selected, - label = props.label, - continuesPrior = props.continuesPrior, - continuesAfter = props.continuesAfter, - getters = props.getters, - onClick = props.onClick, - onDoubleClick = props.onDoubleClick, - isBackgroundEvent = props.isBackgroundEvent, - onKeyPress = props.onKeyPress, - _props$components = props.components, - Event = _props$components.event, - EventWrapper = _props$components.eventWrapper - var title = accessors.title(event) - var tooltip = accessors.tooltip(event) - var end = accessors.end(event) - var start = accessors.start(event) - var userProps = getters.eventProp(event, start, end, selected) - var height = style.height, - top = style.top, - width = style.width, - xOffset = style.xOffset - var inner = [ - /*#__PURE__*/ React.createElement( - 'div', - { - key: '1', - className: 'rbc-event-label', - }, - label - ), - /*#__PURE__*/ React.createElement( - 'div', - { - key: '2', - className: 'rbc-event-content', - }, - Event - ? /*#__PURE__*/ React.createElement(Event, { - event: event, - title: title, - }) - : title - ), - ] - var eventStyle = isBackgroundEvent - ? _objectSpread( - _objectSpread({}, userProps.style), - {}, - _defineProperty( - { - top: stringifyPercent(top), - height: stringifyPercent(height), - // Adding 10px to take events container right margin into account - width: 'calc('.concat(width, ' + 10px)'), - }, - rtl ? 'right' : 'left', - stringifyPercent(Math.max(0, xOffset)) - ) - ) - : _objectSpread( - _objectSpread({}, userProps.style), - {}, - _defineProperty( - { - top: stringifyPercent(top), - width: stringifyPercent(width), - height: stringifyPercent(height), - }, - rtl ? 'right' : 'left', - stringifyPercent(xOffset) - ) - ) - return /*#__PURE__*/ React.createElement( - EventWrapper, - Object.assign( - { - type: 'time', - }, - props - ), - /*#__PURE__*/ React.createElement( - 'div', - { - onClick: onClick, - onDoubleClick: onDoubleClick, - style: eventStyle, - onKeyPress: onKeyPress, - title: tooltip - ? (typeof label === 'string' ? label + ': ' : '') + tooltip - : undefined, - className: clsx( - isBackgroundEvent ? 'rbc-background-event' : 'rbc-event', - className, - userProps.className, - { - 'rbc-selected': selected, - 'rbc-event-continues-earlier': continuesPrior, - 'rbc-event-continues-later': continuesAfter, - } - ), - }, - inner - ) - ) -} - -var DayColumnWrapper = function DayColumnWrapper(_ref) { - var children = _ref.children, - className = _ref.className, - style = _ref.style, - innerRef = _ref.innerRef - return /*#__PURE__*/ React.createElement( - 'div', - { - className: className, - style: style, - ref: innerRef, - }, - children - ) -} - -var DayColumnWrapper$1 = /*#__PURE__*/ React.forwardRef(function (props, ref) { - return /*#__PURE__*/ React.createElement( - DayColumnWrapper, - Object.assign({}, props, { - innerRef: ref, - }) - ) -}) - -var _excluded$5 = ['dayProp'], - _excluded2$1 = ['eventContainerWrapper'] - -var DayColumn = /*#__PURE__*/ (function (_React$Component) { - _inherits(DayColumn, _React$Component) - - var _super = _createSuper(DayColumn) - - function DayColumn() { - var _this - - _classCallCheck(this, DayColumn) - - for ( - var _len = arguments.length, _args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - _args[_key] = arguments[_key] - } - - _this = _super.call.apply(_super, [this].concat(_args)) - _this.state = { - selecting: false, - timeIndicatorPosition: null, - } - _this.intervalTriggered = false - - _this.renderEvents = function (_ref) { - var events = _ref.events, - isBackgroundEvent = _ref.isBackgroundEvent - var _this$props = _this.props, - rtl = _this$props.rtl, - selected = _this$props.selected, - accessors = _this$props.accessors, - localizer = _this$props.localizer, - getters = _this$props.getters, - components = _this$props.components, - step = _this$props.step, - timeslots = _this$props.timeslots, - dayLayoutAlgorithm = _this$props.dayLayoutAlgorithm, - resizable = _this$props.resizable - - var _assertThisInitialize = _assertThisInitialized(_this), - slotMetrics = _assertThisInitialize.slotMetrics - - var messages = localizer.messages - var styledEvents = getStyledEvents({ - events: events, - accessors: accessors, - slotMetrics: slotMetrics, - minimumStartDifference: Math.ceil((step * timeslots) / 2), - dayLayoutAlgorithm: dayLayoutAlgorithm, - }) - return styledEvents.map(function (_ref2, idx) { - var event = _ref2.event, - style = _ref2.style - var end = accessors.end(event) - var start = accessors.start(event) - var format = 'eventTimeRangeFormat' - var label - var startsBeforeDay = slotMetrics.startsBeforeDay(start) - var startsAfterDay = slotMetrics.startsAfterDay(end) - if (startsBeforeDay) format = 'eventTimeRangeEndFormat' - else if (startsAfterDay) format = 'eventTimeRangeStartFormat' - if (startsBeforeDay && startsAfterDay) label = messages.allDay - else - label = localizer.format( - { - start: start, - end: end, - }, - format - ) - var continuesPrior = startsBeforeDay || slotMetrics.startsBefore(start) - var continuesAfter = startsAfterDay || slotMetrics.startsAfter(end) - return /*#__PURE__*/ React.createElement(TimeGridEvent, { - style: style, - event: event, - label: label, - key: 'evt_' + idx, - getters: getters, - rtl: rtl, - components: components, - continuesPrior: continuesPrior, - continuesAfter: continuesAfter, - accessors: accessors, - selected: isSelected(event, selected), - onClick: function onClick(e) { - return _this._select(event, e) - }, - onDoubleClick: function onDoubleClick(e) { - return _this._doubleClick(event, e) - }, - isBackgroundEvent: isBackgroundEvent, - onKeyPress: function onKeyPress(e) { - return _this._keyPress(event, e) - }, - resizable: resizable, - }) - }) - } - - _this._selectable = function () { - var node = _this.containerRef.current - var _this$props2 = _this.props, - longPressThreshold = _this$props2.longPressThreshold, - localizer = _this$props2.localizer - var selector = (_this._selector = new Selection( - function () { - return node - }, - { - longPressThreshold: longPressThreshold, - } - )) - - var maybeSelect = function maybeSelect(box) { - var onSelecting = _this.props.onSelecting - var current = _this.state || {} - var state = selectionState(box) - var start = state.startDate, - end = state.endDate - - if (onSelecting) { - if ( - (localizer.eq(current.startDate, start, 'minutes') && - localizer.eq(current.endDate, end, 'minutes')) || - onSelecting({ - start: start, - end: end, - resourceId: _this.props.resource, - }) === false - ) - return - } - - if ( - _this.state.start !== state.start || - _this.state.end !== state.end || - _this.state.selecting !== state.selecting - ) { - _this.setState(state) - } - } - - var selectionState = function selectionState(point) { - var currentSlot = _this.slotMetrics.closestSlotFromPoint( - point, - getBoundsForNode(node) - ) - - if (!_this.state.selecting) { - _this._initialSlot = currentSlot - } - - var initialSlot = _this._initialSlot - - if (localizer.lte(initialSlot, currentSlot)) { - currentSlot = _this.slotMetrics.nextSlot(currentSlot) - } else if (localizer.gt(initialSlot, currentSlot)) { - initialSlot = _this.slotMetrics.nextSlot(initialSlot) - } - - var selectRange = _this.slotMetrics.getRange( - localizer.min(initialSlot, currentSlot), - localizer.max(initialSlot, currentSlot) - ) - - return _objectSpread( - _objectSpread({}, selectRange), - {}, - { - selecting: true, - top: ''.concat(selectRange.top, '%'), - height: ''.concat(selectRange.height, '%'), - } - ) - } - - var selectorClicksHandler = function selectorClicksHandler( - box, - actionType - ) { - if (!isEvent(_this.containerRef.current, box)) { - var _selectionState = selectionState(box), - startDate = _selectionState.startDate, - endDate = _selectionState.endDate - - _this._selectSlot({ - startDate: startDate, - endDate: endDate, - action: actionType, - box: box, - }) - } - - _this.setState({ - selecting: false, - }) - } - - selector.on('selecting', maybeSelect) - selector.on('selectStart', maybeSelect) - selector.on('beforeSelect', function (box) { - if (_this.props.selectable !== 'ignoreEvents') return - return !isEvent(_this.containerRef.current, box) - }) - selector.on('click', function (box) { - return selectorClicksHandler(box, 'click') - }) - selector.on('doubleClick', function (box) { - return selectorClicksHandler(box, 'doubleClick') - }) - selector.on('select', function (bounds) { - if (_this.state.selecting) { - _this._selectSlot( - _objectSpread( - _objectSpread({}, _this.state), - {}, - { - action: 'select', - bounds: bounds, - } - ) - ) - - _this.setState({ - selecting: false, - }) - } - }) - selector.on('reset', function () { - if (_this.state.selecting) { - _this.setState({ - selecting: false, - }) - } - }) - } - - _this._teardownSelectable = function () { - if (!_this._selector) return - - _this._selector.teardown() - - _this._selector = null - } - - _this._selectSlot = function (_ref3) { - var startDate = _ref3.startDate, - endDate = _ref3.endDate, - action = _ref3.action, - bounds = _ref3.bounds, - box = _ref3.box - var current = startDate, - slots = [] - - while (_this.props.localizer.lte(current, endDate)) { - slots.push(current) - current = new Date(+current + _this.props.step * 60 * 1000) // using Date ensures not to create an endless loop the day DST begins - } - - notify(_this.props.onSelectSlot, { - slots: slots, - start: startDate, - end: endDate, - resourceId: _this.props.resource, - action: action, - bounds: bounds, - box: box, - }) - } - - _this._select = function () { - for ( - var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; - _key2 < _len2; - _key2++ - ) { - args[_key2] = arguments[_key2] - } - - notify(_this.props.onSelectEvent, args) - } - - _this._doubleClick = function () { - for ( - var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; - _key3 < _len3; - _key3++ - ) { - args[_key3] = arguments[_key3] - } - - notify(_this.props.onDoubleClickEvent, args) - } - - _this._keyPress = function () { - for ( - var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; - _key4 < _len4; - _key4++ - ) { - args[_key4] = arguments[_key4] - } - - notify(_this.props.onKeyPressEvent, args) - } - - _this.slotMetrics = getSlotMetrics(_this.props) - _this.containerRef = /*#__PURE__*/ createRef() - return _this - } - - _createClass(DayColumn, [ - { - key: 'componentDidMount', - value: function componentDidMount() { - this.props.selectable && this._selectable() - - if (this.props.isNow) { - this.setTimeIndicatorPositionUpdateInterval() - } - }, - }, - { - key: 'componentWillUnmount', - value: function componentWillUnmount() { - this._teardownSelectable() - - this.clearTimeIndicatorInterval() - }, - }, - { - key: 'UNSAFE_componentWillReceiveProps', - value: function UNSAFE_componentWillReceiveProps(nextProps) { - if (nextProps.selectable && !this.props.selectable) this._selectable() - if (!nextProps.selectable && this.props.selectable) - this._teardownSelectable() - this.slotMetrics = this.slotMetrics.update(nextProps) - }, - }, - { - key: 'componentDidUpdate', - value: function componentDidUpdate(prevProps, prevState) { - var _this$props3 = this.props, - getNow = _this$props3.getNow, - isNow = _this$props3.isNow, - localizer = _this$props3.localizer, - date = _this$props3.date, - min = _this$props3.min, - max = _this$props3.max - var getNowChanged = localizer.neq( - prevProps.getNow(), - getNow(), - 'minutes' - ) - - if (prevProps.isNow !== isNow || getNowChanged) { - this.clearTimeIndicatorInterval() - - if (isNow) { - var tail = - !getNowChanged && - localizer.eq(prevProps.date, date, 'minutes') && - prevState.timeIndicatorPosition === - this.state.timeIndicatorPosition - this.setTimeIndicatorPositionUpdateInterval(tail) - } - } else if ( - isNow && - (localizer.neq(prevProps.min, min, 'minutes') || - localizer.neq(prevProps.max, max, 'minutes')) - ) { - this.positionTimeIndicator() - } - }, - /** - * @param tail {Boolean} - whether `positionTimeIndicator` call should be - * deferred or called upon setting interval (`true` - if deferred); - */ - }, - { - key: 'setTimeIndicatorPositionUpdateInterval', - value: function setTimeIndicatorPositionUpdateInterval() { - var _this2 = this - - var tail = - arguments.length > 0 && arguments[0] !== undefined - ? arguments[0] - : false - - if (!this.intervalTriggered && !tail) { - this.positionTimeIndicator() - } - - this._timeIndicatorTimeout = window.setTimeout(function () { - _this2.intervalTriggered = true - - _this2.positionTimeIndicator() - - _this2.setTimeIndicatorPositionUpdateInterval() - }, 60000) - }, - }, - { - key: 'clearTimeIndicatorInterval', - value: function clearTimeIndicatorInterval() { - this.intervalTriggered = false - window.clearTimeout(this._timeIndicatorTimeout) - }, - }, - { - key: 'positionTimeIndicator', - value: function positionTimeIndicator() { - var _this$props4 = this.props, - min = _this$props4.min, - max = _this$props4.max, - getNow = _this$props4.getNow - var current = getNow() - - if (current >= min && current <= max) { - var top = this.slotMetrics.getCurrentTimePosition(current) - this.intervalTriggered = true - this.setState({ - timeIndicatorPosition: top, - }) - } else { - this.clearTimeIndicatorInterval() - } - }, - }, - { - key: 'render', - value: function render() { - var _this$props5 = this.props, - date = _this$props5.date, - max = _this$props5.max, - rtl = _this$props5.rtl, - isNow = _this$props5.isNow, - resource = _this$props5.resource, - accessors = _this$props5.accessors, - localizer = _this$props5.localizer, - _this$props5$getters = _this$props5.getters, - dayProp = _this$props5$getters.dayProp, - getters = _objectWithoutProperties(_this$props5$getters, _excluded$5), - _this$props5$componen = _this$props5.components, - EventContainer = _this$props5$componen.eventContainerWrapper, - components = _objectWithoutProperties( - _this$props5$componen, - _excluded2$1 - ) - - var slotMetrics = this.slotMetrics - var _this$state = this.state, - selecting = _this$state.selecting, - top = _this$state.top, - height = _this$state.height, - startDate = _this$state.startDate, - endDate = _this$state.endDate - var selectDates = { - start: startDate, - end: endDate, - } - - var _dayProp = dayProp(max), - className = _dayProp.className, - style = _dayProp.style - - var DayColumnWrapperComponent = - components.dayColumnWrapper || DayColumnWrapper$1 - return /*#__PURE__*/ React.createElement( - DayColumnWrapperComponent, - { - ref: this.containerRef, - date: date, - style: style, - className: clsx( - className, - 'rbc-day-slot', - 'rbc-time-column', - isNow && 'rbc-now', - isNow && 'rbc-today', // WHY - selecting && 'rbc-slot-selecting' - ), - slotMetrics: slotMetrics, - }, - slotMetrics.groups.map(function (grp, idx) { - return /*#__PURE__*/ React.createElement(TimeSlotGroup, { - key: idx, - group: grp, - resource: resource, - getters: getters, - components: components, - }) - }), - /*#__PURE__*/ React.createElement( - EventContainer, - { - localizer: localizer, - resource: resource, - accessors: accessors, - getters: getters, - components: components, - slotMetrics: slotMetrics, - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: clsx('rbc-events-container', rtl && 'rtl'), - }, - this.renderEvents({ - events: this.props.backgroundEvents, - isBackgroundEvent: true, - }), - this.renderEvents({ - events: this.props.events, - }) - ) - ), - selecting && - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-slot-selection', - style: { - top: top, - height: height, - }, - }, - /*#__PURE__*/ React.createElement( - 'span', - null, - localizer.format(selectDates, 'selectRangeFormat') - ) - ), - isNow && - this.intervalTriggered && - /*#__PURE__*/ React.createElement('div', { - className: 'rbc-current-time-indicator', - style: { - top: ''.concat(this.state.timeIndicatorPosition, '%'), - }, - }) - ) - }, - }, - ]) - - return DayColumn -})(React.Component) - -DayColumn.defaultProps = { - dragThroughEvents: true, - timeslots: 2, -} - -/** - * Since the TimeGutter only displays the 'times' of slots in a day, and is separate - * from the Day Columns themselves, we check to see if the range contains an offset difference - * and, if so, change the beginning and end 'date' by a day to properly display the slots times - * used. - */ - -function adjustForDST(_ref) { - var min = _ref.min, - max = _ref.max, - localizer = _ref.localizer - - if (localizer.getTimezoneOffset(min) !== localizer.getTimezoneOffset(max)) { - return { - start: localizer.add(min, -1, 'day'), - end: localizer.add(max, -1, 'day'), - } - } - - return { - start: min, - end: max, - } -} - -var TimeGutter = function TimeGutter(_ref2) { - var min = _ref2.min, - max = _ref2.max, - timeslots = _ref2.timeslots, - step = _ref2.step, - localizer = _ref2.localizer, - getNow = _ref2.getNow, - resource = _ref2.resource, - components = _ref2.components, - getters = _ref2.getters, - gutterRef = _ref2.gutterRef - var TimeGutterWrapper = components.timeGutterWrapper - - var _useMemo = useMemo( - function () { - return adjustForDST({ - min: min, - max: max, - localizer: localizer, - }) - }, // eslint-disable-next-line react-hooks/exhaustive-deps - [ - min === null || min === void 0 ? void 0 : min.toISOString(), - max === null || max === void 0 ? void 0 : max.toISOString(), - localizer, - ] - ), - start = _useMemo.start, - end = _useMemo.end - - var _useState = useState( - getSlotMetrics({ - min: start, - max: end, - timeslots: timeslots, - step: step, - localizer: localizer, - }) - ), - _useState2 = _slicedToArray(_useState, 2), - slotMetrics = _useState2[0], - setSlotMetrics = _useState2[1] - - useEffect( - function () { - if (slotMetrics) { - setSlotMetrics( - slotMetrics.update({ - min: start, - max: end, - timeslots: timeslots, - step: step, - localizer: localizer, - }) - ) - } - /** - * We don't want this to fire when slotMetrics is updated as it would recursively bomb - */ - // eslint-disable-next-line react-hooks/exhaustive-deps - }, - [ - start === null || start === void 0 ? void 0 : start.toISOString(), - end === null || end === void 0 ? void 0 : end.toISOString(), - timeslots, - step, - ] - ) - var renderSlot = useCallback( - function (value, idx) { - if (idx) return null // don't return the first (0) idx - - var isNow = slotMetrics.dateIsInGroup(getNow(), idx) - return /*#__PURE__*/ React.createElement( - 'span', - { - className: clsx('rbc-label', isNow && 'rbc-now'), - }, - localizer.format(value, 'timeGutterFormat') - ) - }, - [slotMetrics, localizer, getNow] - ) - return /*#__PURE__*/ React.createElement( - TimeGutterWrapper, - { - slotMetrics: slotMetrics, - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-time-gutter rbc-time-column', - ref: gutterRef, - }, - slotMetrics.groups.map(function (grp, idx) { - return /*#__PURE__*/ React.createElement(TimeSlotGroup, { - key: idx, - group: grp, - resource: resource, - components: components, - renderSlot: renderSlot, - getters: getters, - }) - }) - ) - ) -} - -var TimeGutter$1 = /*#__PURE__*/ React.forwardRef(function (props, ref) { - return /*#__PURE__*/ React.createElement( - TimeGutter, - Object.assign( - { - gutterRef: ref, - }, - props - ) - ) -}) - -var ResourceHeader = function ResourceHeader(_ref) { - var label = _ref.label - return /*#__PURE__*/ React.createElement(React.Fragment, null, label) -} - -var TimeGridHeader = /*#__PURE__*/ (function (_React$Component) { - _inherits(TimeGridHeader, _React$Component) - - var _super = _createSuper(TimeGridHeader) - - function TimeGridHeader() { - var _this - - _classCallCheck(this, TimeGridHeader) - - for ( - var _len = arguments.length, args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key] - } - - _this = _super.call.apply(_super, [this].concat(args)) - - _this.handleHeaderClick = function (date, view, e) { - e.preventDefault() - notify(_this.props.onDrillDown, [date, view]) - } - - _this.renderRow = function (resource) { - var _this$props = _this.props, - events = _this$props.events, - rtl = _this$props.rtl, - selectable = _this$props.selectable, - getNow = _this$props.getNow, - range = _this$props.range, - getters = _this$props.getters, - localizer = _this$props.localizer, - accessors = _this$props.accessors, - components = _this$props.components, - resizable = _this$props.resizable - var resourceId = accessors.resourceId(resource) - var eventsToDisplay = resource - ? events.filter(function (event) { - return accessors.resource(event) === resourceId - }) - : events - return /*#__PURE__*/ React.createElement(DateContentRow, { - isAllDay: true, - rtl: rtl, - getNow: getNow, - minRows: 2, - range: range, - events: eventsToDisplay, - resourceId: resourceId, - className: 'rbc-allday-cell', - selectable: selectable, - selected: _this.props.selected, - components: components, - accessors: accessors, - getters: getters, - localizer: localizer, - onSelect: _this.props.onSelectEvent, - onDoubleClick: _this.props.onDoubleClickEvent, - onKeyPress: _this.props.onKeyPressEvent, - onSelectSlot: _this.props.onSelectSlot, - longPressThreshold: _this.props.longPressThreshold, - resizable: resizable, - }) - } - - return _this - } - - _createClass(TimeGridHeader, [ - { - key: 'renderHeaderCells', - value: function renderHeaderCells(range) { - var _this2 = this - - var _this$props2 = this.props, - localizer = _this$props2.localizer, - getDrilldownView = _this$props2.getDrilldownView, - getNow = _this$props2.getNow, - dayProp = _this$props2.getters.dayProp, - _this$props2$componen = _this$props2.components.header, - HeaderComponent = - _this$props2$componen === void 0 ? Header : _this$props2$componen - var today = getNow() - return range.map(function (date, i) { - var drilldownView = getDrilldownView(date) - var label = localizer.format(date, 'dayFormat') - - var _dayProp = dayProp(date), - className = _dayProp.className, - style = _dayProp.style - - var header = /*#__PURE__*/ React.createElement(HeaderComponent, { - date: date, - label: label, - localizer: localizer, - }) - return /*#__PURE__*/ React.createElement( - 'div', - { - key: i, - style: style, - className: clsx( - 'rbc-header', - className, - localizer.isSameDate(date, today) && 'rbc-today' - ), - }, - drilldownView - ? /*#__PURE__*/ React.createElement( - 'button', - { - type: 'button', - className: 'rbc-button-link', - onClick: function onClick(e) { - return _this2.handleHeaderClick(date, drilldownView, e) - }, - }, - header - ) - : /*#__PURE__*/ React.createElement('span', null, header) - ) - }) - }, - }, - { - key: 'render', - value: function render() { - var _this3 = this - - var _this$props3 = this.props, - width = _this$props3.width, - rtl = _this$props3.rtl, - resources = _this$props3.resources, - range = _this$props3.range, - events = _this$props3.events, - getNow = _this$props3.getNow, - accessors = _this$props3.accessors, - selectable = _this$props3.selectable, - components = _this$props3.components, - getters = _this$props3.getters, - scrollRef = _this$props3.scrollRef, - localizer = _this$props3.localizer, - isOverflowing = _this$props3.isOverflowing, - _this$props3$componen = _this$props3.components, - TimeGutterHeader = _this$props3$componen.timeGutterHeader, - _this$props3$componen2 = _this$props3$componen.resourceHeader, - ResourceHeaderComponent = - _this$props3$componen2 === void 0 - ? ResourceHeader - : _this$props3$componen2, - resizable = _this$props3.resizable - var style = {} - - if (isOverflowing) { - style[rtl ? 'marginLeft' : 'marginRight'] = ''.concat( - scrollbarSize(), - 'px' - ) - } - - var groupedEvents = resources.groupEvents(events) - return /*#__PURE__*/ React.createElement( - 'div', - { - style: style, - ref: scrollRef, - className: clsx( - 'rbc-time-header', - isOverflowing && 'rbc-overflowing' - ), - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-label rbc-time-header-gutter', - style: { - width: width, - minWidth: width, - maxWidth: width, - }, - }, - TimeGutterHeader && - /*#__PURE__*/ React.createElement(TimeGutterHeader, null) - ), - resources.map(function (_ref, idx) { - var _ref2 = _slicedToArray(_ref, 2), - id = _ref2[0], - resource = _ref2[1] - - return /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-time-header-content', - key: id || idx, - }, - resource && - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row rbc-row-resource', - key: 'resource_'.concat(idx), - }, - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-header', - }, - /*#__PURE__*/ React.createElement(ResourceHeaderComponent, { - index: idx, - label: accessors.resourceTitle(resource), - resource: resource, - }) - ) - ), - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-row rbc-time-header-cell'.concat( - range.length <= 1 ? ' rbc-time-header-cell-single-day' : '' - ), - }, - _this3.renderHeaderCells(range) - ), - /*#__PURE__*/ React.createElement(DateContentRow, { - isAllDay: true, - rtl: rtl, - getNow: getNow, - minRows: 2, - range: range, - events: groupedEvents.get(id) || [], - resourceId: resource && id, - className: 'rbc-allday-cell', - selectable: selectable, - selected: _this3.props.selected, - components: components, - accessors: accessors, - getters: getters, - localizer: localizer, - onSelect: _this3.props.onSelectEvent, - onDoubleClick: _this3.props.onDoubleClickEvent, - onKeyPress: _this3.props.onKeyPressEvent, - onSelectSlot: _this3.props.onSelectSlot, - longPressThreshold: _this3.props.longPressThreshold, - resizable: resizable, - }) - ) - }) - ) - }, - }, - ]) - - return TimeGridHeader -})(React.Component) - -var NONE = {} -function Resources(resources, accessors) { - return { - map: function map(fn) { - if (!resources) return [fn([NONE, null], 0)] - return resources.map(function (resource, idx) { - return fn([accessors.resourceId(resource), resource], idx) - }) - }, - groupEvents: function groupEvents(events) { - var eventsByResource = new Map() - - if (!resources) { - // Return all events if resources are not provided - eventsByResource.set(NONE, events) - return eventsByResource - } - - events.forEach(function (event) { - var id = accessors.resource(event) || NONE - var resourceEvents = eventsByResource.get(id) || [] - resourceEvents.push(event) - eventsByResource.set(id, resourceEvents) - }) - return eventsByResource - }, - } -} - -var TimeGrid = /*#__PURE__*/ (function (_Component) { - _inherits(TimeGrid, _Component) - - var _super = _createSuper(TimeGrid) - - function TimeGrid(props) { - var _this - - _classCallCheck(this, TimeGrid) - - _this = _super.call(this, props) - - _this.handleScroll = function (e) { - if (_this.scrollRef.current) { - _this.scrollRef.current.scrollLeft = e.target.scrollLeft - } - } - - _this.handleResize = function () { - animationFrame.cancel(_this.rafHandle) - _this.rafHandle = animationFrame.request(_this.checkOverflow) - } - - _this.handleSelectAlldayEvent = function () { - //cancel any pending selections so only the event click goes through. - _this.clearSelection() - - for ( - var _len = arguments.length, args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key] - } - - notify(_this.props.onSelectEvent, args) - } - - _this.handleSelectAllDaySlot = function (slots, slotInfo) { - var onSelectSlot = _this.props.onSelectSlot - var start = new Date(slots[0]) - var end = new Date(slots[slots.length - 1]) - end.setDate(slots[slots.length - 1].getDate() + 1) - notify(onSelectSlot, { - slots: slots, - start: start, - end: end, - action: slotInfo.action, - resourceId: slotInfo.resourceId, - }) - } - - _this.checkOverflow = function () { - if (_this._updatingOverflow) return - var content = _this.contentRef.current - var isOverflowing = content.scrollHeight > content.clientHeight - - if (_this.state.isOverflowing !== isOverflowing) { - _this._updatingOverflow = true - - _this.setState( - { - isOverflowing: isOverflowing, - }, - function () { - _this._updatingOverflow = false - } - ) - } - } - - _this.memoizedResources = memoize(function (resources, accessors) { - return Resources(resources, accessors) - }) - _this.state = { - gutterWidth: undefined, - isOverflowing: null, - } - _this.scrollRef = /*#__PURE__*/ React.createRef() - _this.contentRef = /*#__PURE__*/ React.createRef() - _this._scrollRatio = null - _this.gutterRef = /*#__PURE__*/ createRef() - return _this - } - - _createClass(TimeGrid, [ - { - key: 'getSnapshotBeforeUpdate', - value: function getSnapshotBeforeUpdate() { - this.checkOverflow() - return null - }, - }, - { - key: 'componentDidMount', - value: function componentDidMount() { - if (this.props.width == null) { - this.measureGutter() - } - - this.calculateScroll() - this.applyScroll() - window.addEventListener('resize', this.handleResize) - }, - }, - { - key: 'componentWillUnmount', - value: function componentWillUnmount() { - window.removeEventListener('resize', this.handleResize) - animationFrame.cancel(this.rafHandle) - - if (this.measureGutterAnimationFrameRequest) { - window.cancelAnimationFrame(this.measureGutterAnimationFrameRequest) - } - }, - }, - { - key: 'componentDidUpdate', - value: function componentDidUpdate() { - this.applyScroll() - }, - }, - { - key: 'renderEvents', - value: function renderEvents(range, events, backgroundEvents, now) { - var _this2 = this - - var _this$props = this.props, - min = _this$props.min, - max = _this$props.max, - components = _this$props.components, - accessors = _this$props.accessors, - localizer = _this$props.localizer, - dayLayoutAlgorithm = _this$props.dayLayoutAlgorithm - var resources = this.memoizedResources(this.props.resources, accessors) - var groupedEvents = resources.groupEvents(events) - var groupedBackgroundEvents = resources.groupEvents(backgroundEvents) - return resources.map(function (_ref, i) { - var _ref2 = _slicedToArray(_ref, 2), - id = _ref2[0], - resource = _ref2[1] - - return range.map(function (date, jj) { - var daysEvents = (groupedEvents.get(id) || []).filter(function ( - event - ) { - return localizer.inRange( - date, - accessors.start(event), - accessors.end(event), - 'day' - ) - }) - var daysBackgroundEvents = ( - groupedBackgroundEvents.get(id) || [] - ).filter(function (event) { - return localizer.inRange( - date, - accessors.start(event), - accessors.end(event), - 'day' - ) - }) - return /*#__PURE__*/ React.createElement( - DayColumn, - Object.assign({}, _this2.props, { - localizer: localizer, - min: localizer.merge(date, min), - max: localizer.merge(date, max), - resource: resource && id, - components: components, - isNow: localizer.isSameDate(date, now), - key: i + '-' + jj, - date: date, - events: daysEvents, - backgroundEvents: daysBackgroundEvents, - dayLayoutAlgorithm: dayLayoutAlgorithm, - }) - ) - }) - }) - }, - }, - { - key: 'render', - value: function render() { - var _this$props2 = this.props, - events = _this$props2.events, - backgroundEvents = _this$props2.backgroundEvents, - range = _this$props2.range, - width = _this$props2.width, - rtl = _this$props2.rtl, - selected = _this$props2.selected, - getNow = _this$props2.getNow, - resources = _this$props2.resources, - components = _this$props2.components, - accessors = _this$props2.accessors, - getters = _this$props2.getters, - localizer = _this$props2.localizer, - min = _this$props2.min, - max = _this$props2.max, - showMultiDayTimes = _this$props2.showMultiDayTimes, - longPressThreshold = _this$props2.longPressThreshold, - resizable = _this$props2.resizable - width = width || this.state.gutterWidth - var start = range[0], - end = range[range.length - 1] - this.slots = range.length - var allDayEvents = [], - rangeEvents = [], - rangeBackgroundEvents = [] - events.forEach(function (event) { - if (inRange(event, start, end, accessors, localizer)) { - var eStart = accessors.start(event), - eEnd = accessors.end(event) - - if ( - accessors.allDay(event) || - localizer.startAndEndAreDateOnly(eStart, eEnd) || - (!showMultiDayTimes && !localizer.isSameDate(eStart, eEnd)) - ) { - allDayEvents.push(event) - } else { - rangeEvents.push(event) - } - } - }) - backgroundEvents.forEach(function (event) { - if (inRange(event, start, end, accessors, localizer)) { - rangeBackgroundEvents.push(event) - } - }) - allDayEvents.sort(function (a, b) { - return sortEvents(a, b, accessors, localizer) - }) - return /*#__PURE__*/ React.createElement( - 'div', - { - className: clsx( - 'rbc-time-view', - resources && 'rbc-time-view-resources' - ), - }, - /*#__PURE__*/ React.createElement(TimeGridHeader, { - range: range, - events: allDayEvents, - width: width, - rtl: rtl, - getNow: getNow, - localizer: localizer, - selected: selected, - resources: this.memoizedResources(resources, accessors), - selectable: this.props.selectable, - accessors: accessors, - getters: getters, - components: components, - scrollRef: this.scrollRef, - isOverflowing: this.state.isOverflowing, - longPressThreshold: longPressThreshold, - onSelectSlot: this.handleSelectAllDaySlot, - onSelectEvent: this.handleSelectAlldayEvent, - onDoubleClickEvent: this.props.onDoubleClickEvent, - onKeyPressEvent: this.props.onKeyPressEvent, - onDrillDown: this.props.onDrillDown, - getDrilldownView: this.props.getDrilldownView, - resizable: resizable, - }), - /*#__PURE__*/ React.createElement( - 'div', - { - ref: this.contentRef, - className: 'rbc-time-content', - onScroll: this.handleScroll, - }, - /*#__PURE__*/ React.createElement(TimeGutter$1, { - date: start, - ref: this.gutterRef, - localizer: localizer, - min: localizer.merge(start, min), - max: localizer.merge(start, max), - step: this.props.step, - getNow: this.props.getNow, - timeslots: this.props.timeslots, - components: components, - className: 'rbc-time-gutter', - getters: getters, - }), - this.renderEvents( - range, - rangeEvents, - rangeBackgroundEvents, - getNow() - ) - ) - ) - }, - }, - { - key: 'clearSelection', - value: function clearSelection() { - clearTimeout(this._selectTimer) - this._pendingSelection = [] - }, - }, - { - key: 'measureGutter', - value: function measureGutter() { - var _this3 = this - - if (this.measureGutterAnimationFrameRequest) { - window.cancelAnimationFrame(this.measureGutterAnimationFrameRequest) - } - - this.measureGutterAnimationFrameRequest = window.requestAnimationFrame( - function () { - var _this3$gutterRef - - var width = getWidth( - (_this3$gutterRef = _this3.gutterRef) === null || - _this3$gutterRef === void 0 - ? void 0 - : _this3$gutterRef.current - ) - - if (width && _this3.state.gutterWidth !== width) { - _this3.setState({ - gutterWidth: width, - }) - } - } - ) - }, - }, - { - key: 'applyScroll', - value: function applyScroll() { - // If auto-scroll is disabled, we don't actually apply the scroll - if (this._scrollRatio != null && this.props.enableAutoScroll === true) { - var content = this.contentRef.current - content.scrollTop = content.scrollHeight * this._scrollRatio // Only do this once - - this._scrollRatio = null - } - }, - }, - { - key: 'calculateScroll', - value: function calculateScroll() { - var props = - arguments.length > 0 && arguments[0] !== undefined - ? arguments[0] - : this.props - var min = props.min, - max = props.max, - scrollToTime = props.scrollToTime, - localizer = props.localizer - var diffMillis = scrollToTime - localizer.startOf(scrollToTime, 'day') - var totalMillis = localizer.diff(min, max, 'milliseconds') - this._scrollRatio = diffMillis / totalMillis - }, - }, - ]) - - return TimeGrid -})(Component) -TimeGrid.defaultProps = { - step: 30, - timeslots: 2, -} - -var _excluded$4 = [ - 'date', - 'localizer', - 'min', - 'max', - 'scrollToTime', - 'enableAutoScroll', -] - -var Day = /*#__PURE__*/ (function (_React$Component) { - _inherits(Day, _React$Component) - - var _super = _createSuper(Day) - - function Day() { - _classCallCheck(this, Day) - - return _super.apply(this, arguments) - } - - _createClass(Day, [ - { - key: 'render', - value: function render() { - /** - * This allows us to default min, max, and scrollToTime - * using our localizer. This is necessary until such time - * as TimeGrid is converted to a functional component. - */ - var _this$props = this.props, - date = _this$props.date, - localizer = _this$props.localizer, - _this$props$min = _this$props.min, - min = - _this$props$min === void 0 - ? localizer.startOf(new Date(), 'day') - : _this$props$min, - _this$props$max = _this$props.max, - max = - _this$props$max === void 0 - ? localizer.endOf(new Date(), 'day') - : _this$props$max, - _this$props$scrollToT = _this$props.scrollToTime, - scrollToTime = - _this$props$scrollToT === void 0 - ? localizer.startOf(new Date(), 'day') - : _this$props$scrollToT, - _this$props$enableAut = _this$props.enableAutoScroll, - enableAutoScroll = - _this$props$enableAut === void 0 ? true : _this$props$enableAut, - props = _objectWithoutProperties(_this$props, _excluded$4) - - var range = Day.range(date, { - localizer: localizer, - }) - return /*#__PURE__*/ React.createElement( - TimeGrid, - Object.assign({}, props, { - range: range, - eventOffset: 10, - localizer: localizer, - min: min, - max: max, - scrollToTime: scrollToTime, - enableAutoScroll: enableAutoScroll, - }) - ) - }, - }, - ]) - - return Day -})(React.Component) - -Day.range = function (date, _ref) { - var localizer = _ref.localizer - return [localizer.startOf(date, 'day')] -} - -Day.navigate = function (date, action, _ref2) { - var localizer = _ref2.localizer - - switch (action) { - case navigate.PREVIOUS: - return localizer.add(date, -1, 'day') - - case navigate.NEXT: - return localizer.add(date, 1, 'day') - - default: - return date - } -} - -Day.title = function (date, _ref3) { - var localizer = _ref3.localizer - return localizer.format(date, 'dayHeaderFormat') -} - -var _excluded$3 = [ - 'date', - 'localizer', - 'min', - 'max', - 'scrollToTime', - 'enableAutoScroll', -] - -var Week = /*#__PURE__*/ (function (_React$Component) { - _inherits(Week, _React$Component) - - var _super = _createSuper(Week) - - function Week() { - _classCallCheck(this, Week) - - return _super.apply(this, arguments) - } - - _createClass(Week, [ - { - key: 'render', - value: function render() { - /** - * This allows us to default min, max, and scrollToTime - * using our localizer. This is necessary until such time - * as TimeGrid is converted to a functional component. - */ - var _this$props = this.props, - date = _this$props.date, - localizer = _this$props.localizer, - _this$props$min = _this$props.min, - min = - _this$props$min === void 0 - ? localizer.startOf(new Date(), 'day') - : _this$props$min, - _this$props$max = _this$props.max, - max = - _this$props$max === void 0 - ? localizer.endOf(new Date(), 'day') - : _this$props$max, - _this$props$scrollToT = _this$props.scrollToTime, - scrollToTime = - _this$props$scrollToT === void 0 - ? localizer.startOf(new Date(), 'day') - : _this$props$scrollToT, - _this$props$enableAut = _this$props.enableAutoScroll, - enableAutoScroll = - _this$props$enableAut === void 0 ? true : _this$props$enableAut, - props = _objectWithoutProperties(_this$props, _excluded$3) - - var range = Week.range(date, this.props) - return /*#__PURE__*/ React.createElement( - TimeGrid, - Object.assign({}, props, { - range: range, - eventOffset: 15, - localizer: localizer, - min: min, - max: max, - scrollToTime: scrollToTime, - enableAutoScroll: enableAutoScroll, - }) - ) - }, - }, - ]) - - return Week -})(React.Component) - -Week.propTypes = - process.env.NODE_ENV !== 'production' - ? { - date: PropTypes.instanceOf(Date).isRequired, - localizer: PropTypes.any, - min: PropTypes.instanceOf(Date), - max: PropTypes.instanceOf(Date), - scrollToTime: PropTypes.instanceOf(Date), - enableAutoScroll: PropTypes.bool, - } - : {} -Week.defaultProps = TimeGrid.defaultProps - -Week.navigate = function (date, action, _ref) { - var localizer = _ref.localizer - - switch (action) { - case navigate.PREVIOUS: - return localizer.add(date, -1, 'week') - - case navigate.NEXT: - return localizer.add(date, 1, 'week') - - default: - return date - } -} - -Week.range = function (date, _ref2) { - var localizer = _ref2.localizer - var firstOfWeek = localizer.startOfWeek() - var start = localizer.startOf(date, 'week', firstOfWeek) - var end = localizer.endOf(date, 'week', firstOfWeek) - return localizer.range(start, end) -} - -Week.title = function (date, _ref3) { - var localizer = _ref3.localizer - - var _Week$range = Week.range(date, { - localizer: localizer, - }), - _Week$range2 = _toArray(_Week$range), - start = _Week$range2[0], - rest = _Week$range2.slice(1) - - return localizer.format( - { - start: start, - end: rest.pop(), - }, - 'dayRangeHeaderFormat' - ) -} - -var _excluded$2 = [ - 'date', - 'localizer', - 'min', - 'max', - 'scrollToTime', - 'enableAutoScroll', -] - -function workWeekRange(date, options) { - return Week.range(date, options).filter(function (d) { - return [6, 0].indexOf(d.getDay()) === -1 - }) -} - -var WorkWeek = /*#__PURE__*/ (function (_React$Component) { - _inherits(WorkWeek, _React$Component) - - var _super = _createSuper(WorkWeek) - - function WorkWeek() { - _classCallCheck(this, WorkWeek) - - return _super.apply(this, arguments) - } - - _createClass(WorkWeek, [ - { - key: 'render', - value: function render() { - /** - * This allows us to default min, max, and scrollToTime - * using our localizer. This is necessary until such time - * as TimeGrid is converted to a functional component. - */ - var _this$props = this.props, - date = _this$props.date, - localizer = _this$props.localizer, - _this$props$min = _this$props.min, - min = - _this$props$min === void 0 - ? localizer.startOf(new Date(), 'day') - : _this$props$min, - _this$props$max = _this$props.max, - max = - _this$props$max === void 0 - ? localizer.endOf(new Date(), 'day') - : _this$props$max, - _this$props$scrollToT = _this$props.scrollToTime, - scrollToTime = - _this$props$scrollToT === void 0 - ? localizer.startOf(new Date(), 'day') - : _this$props$scrollToT, - _this$props$enableAut = _this$props.enableAutoScroll, - enableAutoScroll = - _this$props$enableAut === void 0 ? true : _this$props$enableAut, - props = _objectWithoutProperties(_this$props, _excluded$2) - - var range = workWeekRange(date, this.props) - return /*#__PURE__*/ React.createElement( - TimeGrid, - Object.assign({}, props, { - range: range, - eventOffset: 15, - localizer: localizer, - min: min, - max: max, - scrollToTime: scrollToTime, - enableAutoScroll: enableAutoScroll, - }) - ) - }, - }, - ]) - - return WorkWeek -})(React.Component) - -WorkWeek.propTypes = - process.env.NODE_ENV !== 'production' - ? { - date: PropTypes.instanceOf(Date).isRequired, - localizer: PropTypes.any, - min: PropTypes.instanceOf(Date), - max: PropTypes.instanceOf(Date), - scrollToTime: PropTypes.instanceOf(Date), - enableAutoScroll: PropTypes.bool, - } - : {} -WorkWeek.defaultProps = TimeGrid.defaultProps -WorkWeek.range = workWeekRange -WorkWeek.navigate = Week.navigate - -WorkWeek.title = function (date, _ref) { - var localizer = _ref.localizer - - var _workWeekRange = workWeekRange(date, { - localizer: localizer, - }), - _workWeekRange2 = _toArray(_workWeekRange), - start = _workWeekRange2[0], - rest = _workWeekRange2.slice(1) - - return localizer.format( - { - start: start, - end: rest.pop(), - }, - 'dayRangeHeaderFormat' - ) -} - -function Agenda(_ref) { - var accessors = _ref.accessors, - components = _ref.components, - date = _ref.date, - events = _ref.events, - getters = _ref.getters, - length = _ref.length, - localizer = _ref.localizer, - onDoubleClickEvent = _ref.onDoubleClickEvent, - onSelectEvent = _ref.onSelectEvent, - selected = _ref.selected - var headerRef = useRef(null) - var dateColRef = useRef(null) - var timeColRef = useRef(null) - var contentRef = useRef(null) - var tbodyRef = useRef(null) - useEffect(function () { - _adjustHeader() - }) - - var renderDay = function renderDay(day, events, dayKey) { - var Event = components.event, - AgendaDate = components.date - events = events.filter(function (e) { - return inRange( - e, - localizer.startOf(day, 'day'), - localizer.endOf(day, 'day'), - accessors, - localizer - ) - }) - return events.map(function (event, idx) { - var title = accessors.title(event) - var end = accessors.end(event) - var start = accessors.start(event) - var userProps = getters.eventProp( - event, - start, - end, - isSelected(event, selected) - ) - var dateLabel = idx === 0 && localizer.format(day, 'agendaDateFormat') - var first = - idx === 0 - ? /*#__PURE__*/ React.createElement( - 'td', - { - rowSpan: events.length, - className: 'rbc-agenda-date-cell', - }, - AgendaDate - ? /*#__PURE__*/ React.createElement(AgendaDate, { - day: day, - label: dateLabel, - }) - : dateLabel - ) - : false - return /*#__PURE__*/ React.createElement( - 'tr', - { - key: dayKey + '_' + idx, - className: userProps.className, - style: userProps.style, - }, - first, - /*#__PURE__*/ React.createElement( - 'td', - { - className: 'rbc-agenda-time-cell', - }, - timeRangeLabel(day, event) - ), - /*#__PURE__*/ React.createElement( - 'td', - { - className: 'rbc-agenda-event-cell', - onClick: function onClick(e) { - return onSelectEvent && onSelectEvent(event, e) - }, - onDoubleClick: function onDoubleClick(e) { - return onDoubleClickEvent && onDoubleClickEvent(event, e) - }, - }, - Event - ? /*#__PURE__*/ React.createElement(Event, { - event: event, - title: title, - }) - : title - ) - ) - }, []) - } - - var timeRangeLabel = function timeRangeLabel(day, event) { - var labelClass = '', - TimeComponent = components.time, - label = localizer.messages.allDay - var end = accessors.end(event) - var start = accessors.start(event) - - if (!accessors.allDay(event)) { - if (localizer.eq(start, end)) { - label = localizer.format(start, 'agendaTimeFormat') - } else if (localizer.isSameDate(start, end)) { - label = localizer.format( - { - start: start, - end: end, - }, - 'agendaTimeRangeFormat' - ) - } else if (localizer.isSameDate(day, start)) { - label = localizer.format(start, 'agendaTimeFormat') - } else if (localizer.isSameDate(day, end)) { - label = localizer.format(end, 'agendaTimeFormat') - } - } - - if (localizer.gt(day, start, 'day')) labelClass = 'rbc-continues-prior' - if (localizer.lt(day, end, 'day')) labelClass += ' rbc-continues-after' - return /*#__PURE__*/ React.createElement( - 'span', - { - className: labelClass.trim(), - }, - TimeComponent - ? /*#__PURE__*/ React.createElement(TimeComponent, { - event: event, - day: day, - label: label, - }) - : label - ) - } - - var _adjustHeader = function _adjustHeader() { - if (!tbodyRef.current) return - var header = headerRef.current - var firstRow = tbodyRef.current.firstChild - if (!firstRow) return - var isOverflowing = - contentRef.current.scrollHeight > contentRef.current.clientHeight - var _widths = [] - var widths = _widths - _widths = [getWidth(firstRow.children[0]), getWidth(firstRow.children[1])] - - if (widths[0] !== _widths[0] || widths[1] !== _widths[1]) { - dateColRef.current.style.width = _widths[0] + 'px' - timeColRef.current.style.width = _widths[1] + 'px' - } - - if (isOverflowing) { - addClass(header, 'rbc-header-overflowing') - header.style.marginRight = scrollbarSize() + 'px' - } else { - removeClass(header, 'rbc-header-overflowing') - } - } - - var messages = localizer.messages - var end = localizer.add(date, length, 'day') - var range = localizer.range(date, end, 'day') - events = events.filter(function (event) { - return inRange( - event, - localizer.startOf(date, 'day'), - localizer.endOf(end, 'day'), - accessors, - localizer - ) - }) - events.sort(function (a, b) { - return +accessors.start(a) - +accessors.start(b) - }) - return /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-agenda-view', - }, - events.length !== 0 - ? /*#__PURE__*/ React.createElement( - React.Fragment, - null, - /*#__PURE__*/ React.createElement( - 'table', - { - ref: headerRef, - className: 'rbc-agenda-table', - }, - /*#__PURE__*/ React.createElement( - 'thead', - null, - /*#__PURE__*/ React.createElement( - 'tr', - null, - /*#__PURE__*/ React.createElement( - 'th', - { - className: 'rbc-header', - ref: dateColRef, - }, - messages.date - ), - /*#__PURE__*/ React.createElement( - 'th', - { - className: 'rbc-header', - ref: timeColRef, - }, - messages.time - ), - /*#__PURE__*/ React.createElement( - 'th', - { - className: 'rbc-header', - }, - messages.event - ) - ) - ) - ), - /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-agenda-content', - ref: contentRef, - }, - /*#__PURE__*/ React.createElement( - 'table', - { - className: 'rbc-agenda-table', - }, - /*#__PURE__*/ React.createElement( - 'tbody', - { - ref: tbodyRef, - }, - range.map(function (day, idx) { - return renderDay(day, events, idx) - }) - ) - ) - ) - ) - : /*#__PURE__*/ React.createElement( - 'span', - { - className: 'rbc-agenda-empty', - }, - messages.noEventsInRange - ) - ) -} - -Agenda.defaultProps = { - length: 30, -} - -Agenda.range = function (start, _ref2) { - var _ref2$length = _ref2.length, - length = - _ref2$length === void 0 ? Agenda.defaultProps.length : _ref2$length, - localizer = _ref2.localizer - var end = localizer.add(start, length, 'day') - return { - start: start, - end: end, - } -} - -Agenda.navigate = function (date, action, _ref3) { - var _ref3$length = _ref3.length, - length = - _ref3$length === void 0 ? Agenda.defaultProps.length : _ref3$length, - localizer = _ref3.localizer - - switch (action) { - case navigate.PREVIOUS: - return localizer.add(date, -length, 'day') - - case navigate.NEXT: - return localizer.add(date, length, 'day') - - default: - return date - } -} - -Agenda.title = function (start, _ref4) { - var _ref4$length = _ref4.length, - length = - _ref4$length === void 0 ? Agenda.defaultProps.length : _ref4$length, - localizer = _ref4.localizer - var end = localizer.add(start, length, 'day') - return localizer.format( - { - start: start, - end: end, - }, - 'agendaHeaderFormat' - ) -} - -var _VIEWS -var VIEWS = - ((_VIEWS = {}), - _defineProperty(_VIEWS, views.MONTH, MonthView), - _defineProperty(_VIEWS, views.WEEK, Week), - _defineProperty(_VIEWS, views.WORK_WEEK, WorkWeek), - _defineProperty(_VIEWS, views.DAY, Day), - _defineProperty(_VIEWS, views.AGENDA, Agenda), - _VIEWS) - -var _excluded$1 = ['action', 'date', 'today'] -function moveDate(View, _ref) { - var action = _ref.action, - date = _ref.date, - today = _ref.today, - props = _objectWithoutProperties(_ref, _excluded$1) - - View = typeof View === 'string' ? VIEWS[View] : View - - switch (action) { - case navigate.TODAY: - date = today || new Date() - break - - case navigate.DATE: - break - - default: - invariant( - View && typeof View.navigate === 'function', - 'Calendar View components must implement a static `.navigate(date, action)` method.s' - ) - date = View.navigate(date, action, props) - } - - return date -} - -var Toolbar = /*#__PURE__*/ (function (_React$Component) { - _inherits(Toolbar, _React$Component) - - var _super = _createSuper(Toolbar) - - function Toolbar() { - var _this - - _classCallCheck(this, Toolbar) - - for ( - var _len = arguments.length, args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key] - } - - _this = _super.call.apply(_super, [this].concat(args)) - - _this.navigate = function (action) { - _this.props.onNavigate(action) - } - - _this.view = function (view) { - _this.props.onView(view) - } - - return _this - } - - _createClass(Toolbar, [ - { - key: 'render', - value: function render() { - var _this$props = this.props, - messages = _this$props.localizer.messages, - label = _this$props.label - return /*#__PURE__*/ React.createElement( - 'div', - { - className: 'rbc-toolbar', - }, - /*#__PURE__*/ React.createElement( - 'span', - { - className: 'rbc-btn-group', - }, - /*#__PURE__*/ React.createElement( - 'button', - { - type: 'button', - onClick: this.navigate.bind(null, navigate.TODAY), - }, - messages.today - ), - /*#__PURE__*/ React.createElement( - 'button', - { - type: 'button', - onClick: this.navigate.bind(null, navigate.PREVIOUS), - }, - messages.previous - ), - /*#__PURE__*/ React.createElement( - 'button', - { - type: 'button', - onClick: this.navigate.bind(null, navigate.NEXT), - }, - messages.next - ) - ), - /*#__PURE__*/ React.createElement( - 'span', - { - className: 'rbc-toolbar-label', - }, - label - ), - /*#__PURE__*/ React.createElement( - 'span', - { - className: 'rbc-btn-group', - }, - this.viewNamesGroup(messages) - ) - ) - }, - }, - { - key: 'viewNamesGroup', - value: function viewNamesGroup(messages) { - var _this2 = this - - var viewNames = this.props.views - var view = this.props.view - - if (viewNames.length > 1) { - return viewNames.map(function (name) { - return /*#__PURE__*/ React.createElement( - 'button', - { - type: 'button', - key: name, - className: clsx({ - 'rbc-active': view === name, - }), - onClick: _this2.view.bind(null, name), - }, - messages[name] - ) - }) - } - }, - }, - ]) - - return Toolbar -})(React.Component) - -/** - * Retrieve via an accessor-like property - * - * accessor(obj, 'name') // => retrieves obj['name'] - * accessor(data, func) // => retrieves func(data) - * ... otherwise null - */ -function accessor(data, field) { - var value = null - if (typeof field === 'function') value = field(data) - else if ( - typeof field === 'string' && - _typeof(data) === 'object' && - data != null && - field in data - ) - value = data[field] - return value -} -var wrapAccessor = function wrapAccessor(acc) { - return function (data) { - return accessor(data, acc) - } -} - -var _excluded = ['view', 'date', 'getNow', 'onNavigate'], - _excluded2 = [ - 'view', - 'toolbar', - 'events', - 'backgroundEvents', - 'style', - 'className', - 'elementProps', - 'date', - 'getNow', - 'length', - 'showMultiDayTimes', - 'onShowMore', - 'doShowMoreDrillDown', - 'components', - 'formats', - 'messages', - 'culture', - ] - -function viewNames(_views) { - return !Array.isArray(_views) ? Object.keys(_views) : _views -} - -function isValidView(view, _ref) { - var _views = _ref.views - var names = viewNames(_views) - return names.indexOf(view) !== -1 -} - -var Calendar = /*#__PURE__*/ (function (_React$Component) { - _inherits(Calendar, _React$Component) - - var _super = _createSuper(Calendar) - - function Calendar() { - var _this - - _classCallCheck(this, Calendar) - - for ( - var _len = arguments.length, _args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - _args[_key] = arguments[_key] - } - - _this = _super.call.apply(_super, [this].concat(_args)) - - _this.getViews = function () { - var views = _this.props.views - - if (Array.isArray(views)) { - return transform( - views, - function (obj, name) { - return (obj[name] = VIEWS[name]) - }, - {} - ) - } - - if (_typeof(views) === 'object') { - return mapValues(views, function (value, key) { - if (value === true) { - return VIEWS[key] - } - - return value - }) - } - - return VIEWS - } - - _this.getView = function () { - var views = _this.getViews() - - return views[_this.props.view] - } - - _this.getDrilldownView = function (date) { - var _this$props = _this.props, - view = _this$props.view, - drilldownView = _this$props.drilldownView, - getDrilldownView = _this$props.getDrilldownView - if (!getDrilldownView) return drilldownView - return getDrilldownView(date, view, Object.keys(_this.getViews())) - } - - _this.handleRangeChange = function (date, viewComponent, view) { - var _this$props2 = _this.props, - onRangeChange = _this$props2.onRangeChange, - localizer = _this$props2.localizer - - if (onRangeChange) { - if (viewComponent.range) { - onRangeChange( - viewComponent.range(date, { - localizer: localizer, - }), - view - ) - } else { - if (process.env.NODE_ENV !== 'production') { - console.error('onRangeChange prop not supported for this view') - } - } - } - } - - _this.handleNavigate = function (action, newDate) { - var _this$props3 = _this.props, - view = _this$props3.view, - date = _this$props3.date, - getNow = _this$props3.getNow, - onNavigate = _this$props3.onNavigate, - props = _objectWithoutProperties(_this$props3, _excluded) - - var ViewComponent = _this.getView() - - var today = getNow() - date = moveDate( - ViewComponent, - _objectSpread( - _objectSpread({}, props), - {}, - { - action: action, - date: newDate || date || today, - today: today, - } - ) - ) - onNavigate(date, view, action) - - _this.handleRangeChange(date, ViewComponent) - } - - _this.handleViewChange = function (view) { - if (view !== _this.props.view && isValidView(view, _this.props)) { - _this.props.onView(view) - } - - var views = _this.getViews() - - _this.handleRangeChange( - _this.props.date || _this.props.getNow(), - views[view], - view - ) - } - - _this.handleSelectEvent = function () { - for ( - var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; - _key2 < _len2; - _key2++ - ) { - args[_key2] = arguments[_key2] - } - - notify(_this.props.onSelectEvent, args) - } - - _this.handleDoubleClickEvent = function () { - for ( - var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; - _key3 < _len3; - _key3++ - ) { - args[_key3] = arguments[_key3] - } - - notify(_this.props.onDoubleClickEvent, args) - } - - _this.handleKeyPressEvent = function () { - for ( - var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; - _key4 < _len4; - _key4++ - ) { - args[_key4] = arguments[_key4] - } - - notify(_this.props.onKeyPressEvent, args) - } - - _this.handleSelectSlot = function (slotInfo) { - notify(_this.props.onSelectSlot, slotInfo) - } - - _this.handleDrillDown = function (date, view) { - var onDrillDown = _this.props.onDrillDown - - if (onDrillDown) { - onDrillDown(date, view, _this.drilldownView) - return - } - - if (view) _this.handleViewChange(view) - - _this.handleNavigate(navigate.DATE, date) - } - - _this.state = { - context: Calendar.getContext(_this.props), - } - return _this - } - - _createClass( - Calendar, - [ - { - key: 'render', - value: function render() { - var _this$props4 = this.props, - view = _this$props4.view, - toolbar = _this$props4.toolbar, - events = _this$props4.events, - backgroundEvents = _this$props4.backgroundEvents, - style = _this$props4.style, - className = _this$props4.className, - elementProps = _this$props4.elementProps, - current = _this$props4.date, - getNow = _this$props4.getNow, - length = _this$props4.length, - showMultiDayTimes = _this$props4.showMultiDayTimes, - onShowMore = _this$props4.onShowMore, - doShowMoreDrillDown = _this$props4.doShowMoreDrillDown - _this$props4.components - _this$props4.formats - _this$props4.messages - _this$props4.culture - var props = _objectWithoutProperties(_this$props4, _excluded2) - - current = current || getNow() - var View = this.getView() - var _this$state$context = this.state.context, - accessors = _this$state$context.accessors, - components = _this$state$context.components, - getters = _this$state$context.getters, - localizer = _this$state$context.localizer, - viewNames = _this$state$context.viewNames - var CalToolbar = components.toolbar || Toolbar - var label = View.title(current, { - localizer: localizer, - length: length, - }) - return /*#__PURE__*/ React.createElement( - 'div', - Object.assign({}, elementProps, { - className: clsx( - className, - 'rbc-calendar', - props.rtl && 'rbc-rtl' - ), - style: style, - }), - toolbar && - /*#__PURE__*/ React.createElement(CalToolbar, { - date: current, - view: view, - views: viewNames, - label: label, - onView: this.handleViewChange, - onNavigate: this.handleNavigate, - localizer: localizer, - }), - /*#__PURE__*/ React.createElement( - View, - Object.assign({}, props, { - events: events, - backgroundEvents: backgroundEvents, - date: current, - getNow: getNow, - length: length, - localizer: localizer, - getters: getters, - components: components, - accessors: accessors, - showMultiDayTimes: showMultiDayTimes, - getDrilldownView: this.getDrilldownView, - onNavigate: this.handleNavigate, - onDrillDown: this.handleDrillDown, - onSelectEvent: this.handleSelectEvent, - onDoubleClickEvent: this.handleDoubleClickEvent, - onKeyPressEvent: this.handleKeyPressEvent, - onSelectSlot: this.handleSelectSlot, - onShowMore: onShowMore, - doShowMoreDrillDown: doShowMoreDrillDown, - }) - ) - ) - }, - /** - * - * @param date - * @param viewComponent - * @param {'month'|'week'|'work_week'|'day'|'agenda'} [view] - optional - * parameter. It appears when range change on view changing. It could be handy - * when you need to have both: range and view type at once, i.e. for manage rbc - * state via url - */ - }, - ], - [ - { - key: 'getDerivedStateFromProps', - value: function getDerivedStateFromProps(nextProps) { - return { - context: Calendar.getContext(nextProps), - } - }, - }, - { - key: 'getContext', - value: function getContext(_ref2) { - var startAccessor = _ref2.startAccessor, - endAccessor = _ref2.endAccessor, - allDayAccessor = _ref2.allDayAccessor, - tooltipAccessor = _ref2.tooltipAccessor, - titleAccessor = _ref2.titleAccessor, - resourceAccessor = _ref2.resourceAccessor, - resourceIdAccessor = _ref2.resourceIdAccessor, - resourceTitleAccessor = _ref2.resourceTitleAccessor, - eventPropGetter = _ref2.eventPropGetter, - backgroundEventPropGetter = _ref2.backgroundEventPropGetter, - slotPropGetter = _ref2.slotPropGetter, - slotGroupPropGetter = _ref2.slotGroupPropGetter, - dayPropGetter = _ref2.dayPropGetter, - view = _ref2.view, - views = _ref2.views, - localizer = _ref2.localizer, - culture = _ref2.culture, - _ref2$messages = _ref2.messages, - messages$1 = _ref2$messages === void 0 ? {} : _ref2$messages, - _ref2$components = _ref2.components, - components = _ref2$components === void 0 ? {} : _ref2$components, - _ref2$formats = _ref2.formats, - formats = _ref2$formats === void 0 ? {} : _ref2$formats - var names = viewNames(views) - var msgs = messages(messages$1) - return { - viewNames: names, - localizer: mergeWithDefaults(localizer, culture, formats, msgs), - getters: { - eventProp: function eventProp() { - return ( - (eventPropGetter && - eventPropGetter.apply(void 0, arguments)) || - {} - ) - }, - backgroundEventProp: function backgroundEventProp() { - return ( - (backgroundEventPropGetter && - backgroundEventPropGetter.apply(void 0, arguments)) || - {} - ) - }, - slotProp: function slotProp() { - return ( - (slotPropGetter && slotPropGetter.apply(void 0, arguments)) || - {} - ) - }, - slotGroupProp: function slotGroupProp() { - return ( - (slotGroupPropGetter && - slotGroupPropGetter.apply(void 0, arguments)) || - {} - ) - }, - dayProp: function dayProp() { - return ( - (dayPropGetter && dayPropGetter.apply(void 0, arguments)) || - {} - ) - }, - }, - components: defaults( - components[view] || {}, - omit(components, names), - { - eventWrapper: NoopWrapper, - backgroundEventWrapper: NoopWrapper, - eventContainerWrapper: NoopWrapper, - dateCellWrapper: NoopWrapper, - weekWrapper: NoopWrapper, - timeSlotWrapper: NoopWrapper, - timeGutterWrapper: NoopWrapper, - } - ), - accessors: { - start: wrapAccessor(startAccessor), - end: wrapAccessor(endAccessor), - allDay: wrapAccessor(allDayAccessor), - tooltip: wrapAccessor(tooltipAccessor), - title: wrapAccessor(titleAccessor), - resource: wrapAccessor(resourceAccessor), - resourceId: wrapAccessor(resourceIdAccessor), - resourceTitle: wrapAccessor(resourceTitleAccessor), - }, - } - }, - }, - ] - ) - - return Calendar -})(React.Component) - -Calendar.defaultProps = { - events: [], - backgroundEvents: [], - elementProps: {}, - popup: false, - toolbar: true, - view: views.MONTH, - views: [views.MONTH, views.WEEK, views.DAY, views.AGENDA], - step: 30, - length: 30, - doShowMoreDrillDown: true, - drilldownView: views.DAY, - titleAccessor: 'title', - tooltipAccessor: 'title', - allDayAccessor: 'allDay', - startAccessor: 'start', - endAccessor: 'end', - resourceAccessor: 'resourceId', - resourceIdAccessor: 'id', - resourceTitleAccessor: 'title', - longPressThreshold: 250, - getNow: function getNow() { - return new Date() - }, - dayLayoutAlgorithm: 'overlap', -} -var Calendar$1 = uncontrollable(Calendar, { - view: 'onView', - date: 'onNavigate', - selected: 'onSelectEvent', -}) - -var weekRangeFormat$4 = function weekRangeFormat(_ref, culture, local) { - var start = _ref.start, - end = _ref.end - return ( - local.format(start, 'MMMM DD', culture) + - ' – ' + // updated to use this localizer 'eq()' method - local.format(end, local.eq(start, end, 'month') ? 'DD' : 'MMMM DD', culture) - ) -} - -var dateRangeFormat$4 = function dateRangeFormat(_ref2, culture, local) { - var start = _ref2.start, - end = _ref2.end - return ( - local.format(start, 'L', culture) + ' – ' + local.format(end, 'L', culture) - ) -} - -var timeRangeFormat$4 = function timeRangeFormat(_ref3, culture, local) { - var start = _ref3.start, - end = _ref3.end - return ( - local.format(start, 'LT', culture) + - ' – ' + - local.format(end, 'LT', culture) - ) -} - -var timeRangeStartFormat$4 = function timeRangeStartFormat( - _ref4, - culture, - local -) { - var start = _ref4.start - return local.format(start, 'LT', culture) + ' – ' -} - -var timeRangeEndFormat$4 = function timeRangeEndFormat(_ref5, culture, local) { - var end = _ref5.end - return ' – ' + local.format(end, 'LT', culture) -} - -var formats$4 = { - dateFormat: 'DD', - dayFormat: 'DD ddd', - weekdayFormat: 'ddd', - selectRangeFormat: timeRangeFormat$4, - eventTimeRangeFormat: timeRangeFormat$4, - eventTimeRangeStartFormat: timeRangeStartFormat$4, - eventTimeRangeEndFormat: timeRangeEndFormat$4, - timeGutterFormat: 'LT', - monthHeaderFormat: 'MMMM YYYY', - dayHeaderFormat: 'dddd MMM DD', - dayRangeHeaderFormat: weekRangeFormat$4, - agendaHeaderFormat: dateRangeFormat$4, - agendaDateFormat: 'ddd MMM DD', - agendaTimeFormat: 'LT', - agendaTimeRangeFormat: timeRangeFormat$4, -} - -function fixUnit$1(unit) { - var datePart = unit ? unit.toLowerCase() : unit - - if (datePart === 'FullYear') { - datePart = 'year' - } else if (!datePart) { - datePart = undefined - } - - return datePart -} - -function moment(moment) { - var locale = function locale(m, c) { - return c ? m.locale(c) : m - } - - function getTimezoneOffset(date) { - // ensures this gets cast to timezone - return moment(date).toDate().getTimezoneOffset() - } - - function getDstOffset(start, end) { - var _st$_z$name, _st$_z - - // convert to moment, in case - var st = moment(start) - var ed = moment(end) // if not using moment timezone - - if (!moment.tz) { - return st.toDate().getTimezoneOffset() - ed.toDate().getTimezoneOffset() - } - /** - * If using moment-timezone, and a timezone has been applied, then - * use this to get the proper timezone offset, otherwise default - * the timezone to the browser local - */ - - var tzName = - (_st$_z$name = - st === null || st === void 0 - ? void 0 - : (_st$_z = st._z) === null || _st$_z === void 0 - ? void 0 - : _st$_z.name) !== null && _st$_z$name !== void 0 - ? _st$_z$name - : moment.tz.guess() - var startOffset = moment.tz.zone(tzName).utcOffset(+st) - var endOffset = moment.tz.zone(tzName).utcOffset(+ed) - return startOffset - endOffset - } - - function getDayStartDstOffset(start) { - var dayStart = moment(start).startOf('day') - return getDstOffset(dayStart, start) - } - /*** BEGIN localized date arithmetic methods with moment ***/ - - function defineComparators(a, b, unit) { - var datePart = fixUnit$1(unit) - var dtA = datePart ? moment(a).startOf(datePart) : moment(a) - var dtB = datePart ? moment(b).startOf(datePart) : moment(b) - return [dtA, dtB, datePart] - } - - function startOf() { - var date = - arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null - var unit = arguments.length > 1 ? arguments[1] : undefined - var datePart = fixUnit$1(unit) - - if (datePart) { - return moment(date).startOf(datePart).toDate() - } - - return moment(date).toDate() - } - - function endOf() { - var date = - arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null - var unit = arguments.length > 1 ? arguments[1] : undefined - var datePart = fixUnit$1(unit) - - if (datePart) { - return moment(date).endOf(datePart).toDate() - } - - return moment(date).toDate() - } // moment comparison operations *always* convert both sides to moment objects - // prior to running the comparisons - - function eq(a, b, unit) { - var _defineComparators = defineComparators(a, b, unit), - _defineComparators2 = _slicedToArray(_defineComparators, 3), - dtA = _defineComparators2[0], - dtB = _defineComparators2[1], - datePart = _defineComparators2[2] - - return dtA.isSame(dtB, datePart) - } - - function neq(a, b, unit) { - return !eq(a, b, unit) - } - - function gt(a, b, unit) { - var _defineComparators3 = defineComparators(a, b, unit), - _defineComparators4 = _slicedToArray(_defineComparators3, 3), - dtA = _defineComparators4[0], - dtB = _defineComparators4[1], - datePart = _defineComparators4[2] - - return dtA.isAfter(dtB, datePart) - } - - function lt(a, b, unit) { - var _defineComparators5 = defineComparators(a, b, unit), - _defineComparators6 = _slicedToArray(_defineComparators5, 3), - dtA = _defineComparators6[0], - dtB = _defineComparators6[1], - datePart = _defineComparators6[2] - - return dtA.isBefore(dtB, datePart) - } - - function gte(a, b, unit) { - var _defineComparators7 = defineComparators(a, b, unit), - _defineComparators8 = _slicedToArray(_defineComparators7, 3), - dtA = _defineComparators8[0], - dtB = _defineComparators8[1], - datePart = _defineComparators8[2] - - return dtA.isSameOrBefore(dtB, datePart) - } - - function lte(a, b, unit) { - var _defineComparators9 = defineComparators(a, b, unit), - _defineComparators10 = _slicedToArray(_defineComparators9, 3), - dtA = _defineComparators10[0], - dtB = _defineComparators10[1], - datePart = _defineComparators10[2] - - return dtA.isSameOrBefore(dtB, datePart) - } - - function inRange(day, min, max) { - var unit = - arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'day' - var datePart = fixUnit$1(unit) - var mDay = moment(day) - var mMin = moment(min) - var mMax = moment(max) - return mDay.isBetween(mMin, mMax, datePart, '[]') - } - - function min(dateA, dateB) { - var dtA = moment(dateA) - var dtB = moment(dateB) - var minDt = moment.min(dtA, dtB) - return minDt.toDate() - } - - function max(dateA, dateB) { - var dtA = moment(dateA) - var dtB = moment(dateB) - var maxDt = moment.max(dtA, dtB) - return maxDt.toDate() - } - - function merge(date, time) { - if (!date && !time) return null - var tm = moment(time).format('HH:mm:ss') - var dt = moment(date).startOf('day').format('MM/DD/YYYY') // We do it this way to avoid issues when timezone switching - - return moment(''.concat(dt, ' ').concat(tm), 'MM/DD/YYYY HH:mm:ss').toDate() - } - - function add(date, adder, unit) { - var datePart = fixUnit$1(unit) - return moment(date).add(adder, datePart).toDate() - } - - function range(start, end) { - var unit = - arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'day' - var datePart = fixUnit$1(unit) // because the add method will put these in tz, we have to start that way - - var current = moment(start).toDate() - var days = [] - - while (lte(current, end)) { - days.push(current) - current = add(current, 1, datePart) - } - - return days - } - - function ceil(date, unit) { - var datePart = fixUnit$1(unit) - var floor = startOf(date, datePart) - return eq(floor, date) ? floor : add(floor, 1, datePart) - } - - function diff(a, b) { - var unit = - arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'day' - var datePart = fixUnit$1(unit) // don't use 'defineComparators' here, as we don't want to mutate the values - - var dtA = moment(a) - var dtB = moment(b) - return dtB.diff(dtA, datePart) - } - - function minutes(date) { - var dt = moment(date) - return dt.minutes() - } - - function firstOfWeek(culture) { - var data = culture ? moment.localeData(culture) : moment.localeData() - return data ? data.firstDayOfWeek() : 0 - } - - function firstVisibleDay(date) { - return moment(date).startOf('month').startOf('week').toDate() - } - - function lastVisibleDay(date) { - return moment(date).endOf('month').endOf('week').toDate() - } - - function visibleDays(date) { - var current = firstVisibleDay(date) - var last = lastVisibleDay(date) - var days = [] - - while (lte(current, last)) { - days.push(current) - current = add(current, 1, 'd') - } - - return days - } - /*** END localized date arithmetic methods with moment ***/ - - /** - * Moved from TimeSlots.js, this method overrides the method of the same name - * in the localizer.js, using moment to construct the js Date - * @param {Date} dt - date to start with - * @param {Number} minutesFromMidnight - * @param {Number} offset - * @returns {Date} - */ - - function getSlotDate(dt, minutesFromMidnight, offset) { - return moment(dt) - .startOf('day') - .minute(minutesFromMidnight + offset) - .toDate() - } // moment will automatically handle DST differences in it's calculations - - function getTotalMin(start, end) { - return diff(start, end, 'minutes') - } - - function getMinutesFromMidnight(start) { - var dayStart = moment(start).startOf('day') - var day = moment(start) - return day.diff(dayStart, 'minutes') + getDayStartDstOffset(start) - } // These two are used by DateSlotMetrics - - function continuesPrior(start, first) { - var mStart = moment(start) - var mFirst = moment(first) - return mStart.isBefore(mFirst, 'day') - } - - function continuesAfter(start, end, last) { - var mEnd = moment(end) - var mLast = moment(last) - return mEnd.isSameOrAfter(mLast, 'minutes') - } // These two are used by eventLevels - - function sortEvents(_ref6) { - var _ref6$evtA = _ref6.evtA, - aStart = _ref6$evtA.start, - aEnd = _ref6$evtA.end, - aAllDay = _ref6$evtA.allDay, - _ref6$evtB = _ref6.evtB, - bStart = _ref6$evtB.start, - bEnd = _ref6$evtB.end, - bAllDay = _ref6$evtB.allDay - var startSort = +startOf(aStart, 'day') - +startOf(bStart, 'day') - var durA = diff(aStart, ceil(aEnd, 'day'), 'day') - var durB = diff(bStart, ceil(bEnd, 'day'), 'day') - return ( - startSort || // sort by start Day first - Math.max(durB, 1) - Math.max(durA, 1) || // events spanning multiple days go first - !!bAllDay - !!aAllDay || // then allDay single day events - +aStart - +bStart || // then sort by start time *don't need moment conversion here - +aEnd - +bEnd // then sort by end time *don't need moment conversion here either - ) - } - - function inEventRange(_ref7) { - var _ref7$event = _ref7.event, - start = _ref7$event.start, - end = _ref7$event.end, - _ref7$range = _ref7.range, - rangeStart = _ref7$range.start, - rangeEnd = _ref7$range.end - var startOfDay = moment(start).startOf('day') - var eEnd = moment(end) - var rStart = moment(rangeStart) - var rEnd = moment(rangeEnd) - var startsBeforeEnd = startOfDay.isSameOrBefore(rEnd, 'day') // when the event is zero duration we need to handle a bit differently - - var sameMin = !startOfDay.isSame(eEnd, 'minutes') - var endsAfterStart = sameMin - ? eEnd.isAfter(rStart, 'minutes') - : eEnd.isSameOrAfter(rStart, 'minutes') - return startsBeforeEnd && endsAfterStart - } // moment treats 'day' and 'date' equality very different - // moment(date1).isSame(date2, 'day') would test that they were both the same day of the week - // moment(date1).isSame(date2, 'date') would test that they were both the same date of the month of the year - - function isSameDate(date1, date2) { - var dt = moment(date1) - var dt2 = moment(date2) - return dt.isSame(dt2, 'date') - } - /** - * This method, called once in the localizer constructor, is used by eventLevels - * 'eventSegments()' to assist in determining the 'span' of the event in the display, - * specifically when using a timezone that is greater than the browser native timezone. - * @returns number - */ - - function browserTZOffset() { - /** - * Date.prototype.getTimezoneOffset horrifically flips the positive/negative from - * what you see in it's string, so we have to jump through some hoops to get a value - * we can actually compare. - */ - var dt = new Date() - var neg = /-/.test(dt.toString()) ? '-' : '' - var dtOffset = dt.getTimezoneOffset() - var comparator = Number(''.concat(neg).concat(Math.abs(dtOffset))) // moment correctly provides positive/negative offset, as expected - - var mtOffset = moment().utcOffset() - return mtOffset > comparator ? 1 : 0 - } - - return new DateLocalizer({ - formats: formats$4, - firstOfWeek: firstOfWeek, - firstVisibleDay: firstVisibleDay, - lastVisibleDay: lastVisibleDay, - visibleDays: visibleDays, - format: function format(value, _format, culture) { - return locale(moment(value), culture).format(_format) - }, - lt: lt, - lte: lte, - gt: gt, - gte: gte, - eq: eq, - neq: neq, - merge: merge, - inRange: inRange, - startOf: startOf, - endOf: endOf, - range: range, - add: add, - diff: diff, - ceil: ceil, - min: min, - max: max, - minutes: minutes, - getSlotDate: getSlotDate, - getTimezoneOffset: getTimezoneOffset, - getDstOffset: getDstOffset, - getTotalMin: getTotalMin, - getMinutesFromMidnight: getMinutesFromMidnight, - continuesPrior: continuesPrior, - continuesAfter: continuesAfter, - sortEvents: sortEvents, - inEventRange: inEventRange, - isSameDate: isSameDate, - browserTZOffset: browserTZOffset, - }) -} - -function pluralizeUnit(unit) { - return /s$/.test(unit) ? unit : unit + 's' -} - -var weekRangeFormat$3 = function weekRangeFormat(_ref, culture, local) { - var start = _ref.start, - end = _ref.end - return ( - local.format(start, 'MMMM dd', culture) + - ' – ' + // updated to use this localizer 'eq()' method - local.format(end, local.eq(start, end, 'month') ? 'dd' : 'MMMM dd', culture) - ) -} - -var dateRangeFormat$3 = function dateRangeFormat(_ref2, culture, local) { - var start = _ref2.start, - end = _ref2.end - return ( - local.format(start, 'D', culture) + ' – ' + local.format(end, 'D', culture) - ) -} - -var timeRangeFormat$3 = function timeRangeFormat(_ref3, culture, local) { - var start = _ref3.start, - end = _ref3.end - return ( - local.format(start, 't', culture) + ' – ' + local.format(end, 't', culture) - ) -} - -var timeRangeStartFormat$3 = function timeRangeStartFormat( - _ref4, - culture, - local -) { - var start = _ref4.start - return local.format(start, 't', culture) + ' – ' -} - -var timeRangeEndFormat$3 = function timeRangeEndFormat(_ref5, culture, local) { - var end = _ref5.end - return ' – ' + local.format(end, 't', culture) -} - -var formats$3 = { - dateFormat: 'dd', - dayFormat: 'dd EEE', - weekdayFormat: 'EEE', - selectRangeFormat: timeRangeFormat$3, - eventTimeRangeFormat: timeRangeFormat$3, - eventTimeRangeStartFormat: timeRangeStartFormat$3, - eventTimeRangeEndFormat: timeRangeEndFormat$3, - timeGutterFormat: 't', - monthHeaderFormat: 'MMMM yyyy', - dayHeaderFormat: 'EEEE MMM dd', - dayRangeHeaderFormat: weekRangeFormat$3, - agendaHeaderFormat: dateRangeFormat$3, - agendaDateFormat: 'EEE MMM dd', - agendaTimeFormat: 't', - agendaTimeRangeFormat: timeRangeFormat$3, -} - -function fixUnit(unit) { - var datePart = unit ? pluralizeUnit(unit.toLowerCase()) : unit - - if (datePart === 'FullYear') { - datePart = 'year' - } else if (!datePart) { - datePart = undefined - } - - return datePart -} // Luxon does not currently have weekInfo by culture -// Luxon uses 1 based values for month and weekday -// So we default to Sunday (7) - -function luxon(DateTime) { - var _ref6 = - arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref6$firstDayOfWeek = _ref6.firstDayOfWeek, - firstDayOfWeek = _ref6$firstDayOfWeek === void 0 ? 7 : _ref6$firstDayOfWeek - - function formatDate(value, format) { - return DateTime.fromJSDate(value).toFormat(format) - } - - function formatDateWithCulture(value, culture, format) { - return DateTime.fromJSDate(value).setLocale(culture).toFormat(format) - } - /*** BEGIN localized date arithmetic methods with Luxon ***/ - - function defineComparators(a, b, unit) { - var datePart = fixUnit(unit) - var dtA = datePart - ? DateTime.fromJSDate(a).startOf(datePart) - : DateTime.fromJSDate(a) - var dtB = datePart - ? DateTime.fromJSDate(b).startOf(datePart) - : DateTime.fromJSDate(b) - return [dtA, dtB, datePart] - } // Since Luxon (and current Intl API) has no support - // for culture based weekInfo, we need to handle - // the start of the week differently - // depending on locale, the firstDayOfWeek could also be Saturday, Sunday or Monday - - function startOfDTWeek(dtObj) { - var weekday = dtObj.weekday - - if (weekday === firstDayOfWeek) { - return dtObj.startOf('day') // already beginning of week - } else if (firstDayOfWeek === 1) { - return dtObj.startOf('week') // fow is Monday, which is Luxon default - } - - var diff = firstDayOfWeek === 7 ? weekday : weekday + (7 - firstDayOfWeek) - return dtObj - .minus({ - day: diff, - }) - .startOf('day') - } - - function endOfDTWeek(dtObj) { - var weekday = dtObj.weekday - var eow = firstDayOfWeek === 1 ? 7 : firstDayOfWeek - 1 - - if (weekday === eow) { - return dtObj.endOf('day') // already last day of the week - } else if (firstDayOfWeek === 1) { - return dtObj.endOf('week') // use Luxon default (Sunday) - } - - var fromDate = - firstDayOfWeek > eow - ? dtObj.plus({ - day: firstDayOfWeek - eow, - }) - : dtObj - return fromDate - .set({ - weekday: eow, - }) - .endOf('day') - } // This returns a DateTime instance - - function startOfDT() { - var date = - arguments.length > 0 && arguments[0] !== undefined - ? arguments[0] - : new Date() - var unit = arguments.length > 1 ? arguments[1] : undefined - var datePart = fixUnit(unit) - - if (datePart) { - var dt = DateTime.fromJSDate(date) - return datePart.includes('week') - ? startOfDTWeek(dt) - : dt.startOf(datePart) - } - - return DateTime.fromJSDate(date) - } - - function firstOfWeek() { - return firstDayOfWeek - } // This returns a JS Date from a DateTime instance - - function startOf() { - var date = - arguments.length > 0 && arguments[0] !== undefined - ? arguments[0] - : new Date() - var unit = arguments.length > 1 ? arguments[1] : undefined - return startOfDT(date, unit).toJSDate() - } // This returns a DateTime instance - - function endOfDT() { - var date = - arguments.length > 0 && arguments[0] !== undefined - ? arguments[0] - : new Date() - var unit = arguments.length > 1 ? arguments[1] : undefined - var datePart = fixUnit(unit) - - if (datePart) { - var dt = DateTime.fromJSDate(date) - return datePart.includes('week') ? endOfDTWeek(dt) : dt.endOf(datePart) - } - - return DateTime.fromJSDate(date) - } - - function endOf() { - var date = - arguments.length > 0 && arguments[0] !== undefined - ? arguments[0] - : new Date() - var unit = arguments.length > 1 ? arguments[1] : undefined - return endOfDT(date, unit).toJSDate() - } - - function eq(a, b, unit) { - var _defineComparators = defineComparators(a, b, unit), - _defineComparators2 = _slicedToArray(_defineComparators, 2), - dtA = _defineComparators2[0], - dtB = _defineComparators2[1] - - return +dtA == +dtB - } - - function neq(a, b, unit) { - return !eq(a, b, unit) - } - - function gt(a, b, unit) { - var _defineComparators3 = defineComparators(a, b, unit), - _defineComparators4 = _slicedToArray(_defineComparators3, 2), - dtA = _defineComparators4[0], - dtB = _defineComparators4[1] - - return +dtA > +dtB - } - - function lt(a, b, unit) { - var _defineComparators5 = defineComparators(a, b, unit), - _defineComparators6 = _slicedToArray(_defineComparators5, 2), - dtA = _defineComparators6[0], - dtB = _defineComparators6[1] - - return +dtA < +dtB - } - - function gte(a, b, unit) { - var _defineComparators7 = defineComparators(a, b, unit), - _defineComparators8 = _slicedToArray(_defineComparators7, 2), - dtA = _defineComparators8[0], - dtB = _defineComparators8[1] - - return +dtA >= +dtB - } - - function lte(a, b, unit) { - var _defineComparators9 = defineComparators(a, b, unit), - _defineComparators10 = _slicedToArray(_defineComparators9, 2), - dtA = _defineComparators10[0], - dtB = _defineComparators10[1] - - return +dtA <= +dtB - } - - function inRange(day, min, max) { - var unit = - arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'day' - var datePart = fixUnit(unit) - var mDay = startOfDT(day, datePart) - var mMin = startOfDT(min, datePart) - var mMax = startOfDT(max, datePart) - return +mDay >= +mMin && +mDay <= +mMax - } - - function min(dateA, dateB) { - var dtA = DateTime.fromJSDate(dateA) - var dtB = DateTime.fromJSDate(dateB) - var minDt = DateTime.min(dtA, dtB) - return minDt.toJSDate() - } - - function max(dateA, dateB) { - var dtA = DateTime.fromJSDate(dateA) - var dtB = DateTime.fromJSDate(dateB) - var maxDt = DateTime.max(dtA, dtB) - return maxDt.toJSDate() - } - - function merge(date, time) { - if (!date && !time) return null - var tm = DateTime.fromJSDate(time) - var dt = startOfDT(date, 'day') - return dt - .set({ - hour: tm.hour, - minute: tm.minute, - second: tm.second, - millisecond: tm.millisecond, - }) - .toJSDate() - } - - function add(date, adder, unit) { - var datePart = fixUnit(unit) - return DateTime.fromJSDate(date) - .plus(_defineProperty({}, datePart, adder)) - .toJSDate() - } - - function range(start, end) { - var unit = - arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'day' - var datePart = fixUnit(unit) - var current = DateTime.fromJSDate(start).toJSDate() // this is to get it to tz - - var days = [] - - while (lte(current, end)) { - days.push(current) - current = add(current, 1, datePart) - } - - return days - } - - function ceil(date, unit) { - var datePart = fixUnit(unit) - var floor = startOf(date, datePart) - return eq(floor, date) ? floor : add(floor, 1, datePart) - } - - function diff(a, b) { - var unit = - arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'day' - var datePart = fixUnit(unit) // don't use 'defineComparators' here, as we don't want to mutate the values - - var dtA = DateTime.fromJSDate(a) - var dtB = DateTime.fromJSDate(b) - return Math.round( - dtB - .diff(dtA, datePart, { - conversionAccuracy: 'longterm', - }) - .toObject()[datePart] - ) - } - - function firstVisibleDay(date) { - var startOfMonth = startOfDT(date, 'month') - return startOfDTWeek(startOfMonth).toJSDate() - } - - function lastVisibleDay(date) { - var endOfMonth = endOfDT(date, 'month') - return endOfDTWeek(endOfMonth).toJSDate() - } - - function visibleDays(date) { - var current = firstVisibleDay(date) - var last = lastVisibleDay(date) - var days = [] - - while (lte(current, last)) { - days.push(current) - current = add(current, 1, 'day') - } - - return days - } - /*** END localized date arithmetic methods with moment ***/ - - /** - * Moved from TimeSlots.js, this method overrides the method of the same name - * in the localizer.js, using moment to construct the js Date - * @param {Date} dt - date to start with - * @param {Number} minutesFromMidnight - * @param {Number} offset - * @returns {Date} - */ - - function getSlotDate(dt, minutesFromMidnight, offset) { - return startOfDT(dt, 'day') - .set({ - minutes: minutesFromMidnight + offset, - }) - .toJSDate() - } // Luxon will automatically handle DST differences in it's calculations - - function getTotalMin(start, end) { - return diff(start, end, 'minutes') - } - - function getMinutesFromMidnight(start) { - var dayStart = startOfDT(start, 'day') - var day = DateTime.fromJSDate(start) - return Math.round( - day - .diff(dayStart, 'minutes', { - conversionAccuracy: 'longterm', - }) - .toObject().minutes - ) - } // These two are used by DateSlotMetrics - - function continuesPrior(start, first) { - return lt(start, first) - } - - function continuesAfter(start, end, last) { - return gte(end, last) - } // These two are used by eventLevels - - function sortEvents(_ref7) { - var _ref7$evtA = _ref7.evtA, - aStart = _ref7$evtA.start, - aEnd = _ref7$evtA.end, - aAllDay = _ref7$evtA.allDay, - _ref7$evtB = _ref7.evtB, - bStart = _ref7$evtB.start, - bEnd = _ref7$evtB.end, - bAllDay = _ref7$evtB.allDay - var startSort = +startOf(aStart, 'day') - +startOf(bStart, 'day') - var durA = diff(aStart, ceil(aEnd, 'day'), 'day') - var durB = diff(bStart, ceil(bEnd, 'day'), 'day') - return ( - startSort || // sort by start Day first - Math.max(durB, 1) - Math.max(durA, 1) || // events spanning multiple days go first - !!bAllDay - !!aAllDay || // then allDay single day events - +aStart - +bStart || // then sort by start time *don't need moment conversion here - +aEnd - +bEnd // then sort by end time *don't need moment conversion here either - ) - } - - function inEventRange(_ref8) { - var _ref8$event = _ref8.event, - start = _ref8$event.start, - end = _ref8$event.end, - _ref8$range = _ref8.range, - rangeStart = _ref8$range.start, - rangeEnd = _ref8$range.end - var eStart = startOf(start, 'day') - var startsBeforeEnd = lte(eStart, rangeEnd, 'day') // when the event is zero duration we need to handle a bit differently - - var sameMin = neq(eStart, end, 'minutes') - var endsAfterStart = sameMin - ? gt(end, rangeStart, 'minutes') - : gte(end, rangeStart, 'minutes') - return startsBeforeEnd && endsAfterStart - } // moment treats 'day' and 'date' equality very different - // moment(date1).isSame(date2, 'day') would test that they were both the same day of the week - // moment(date1).isSame(date2, 'date') would test that they were both the same date of the month of the year - - function isSameDate(date1, date2) { - var dt = DateTime.fromJSDate(date1) - var dt2 = DateTime.fromJSDate(date2) - return dt.hasSame(dt2, 'day') - } - /** - * This method, called once in the localizer constructor, is used by eventLevels - * 'eventSegments()' to assist in determining the 'span' of the event in the display, - * specifically when using a timezone that is greater than the browser native timezone. - * @returns number - */ - - function browserTZOffset() { - /** - * Date.prototype.getTimezoneOffset horrifically flips the positive/negative from - * what you see in it's string, so we have to jump through some hoops to get a value - * we can actually compare. - */ - var dt = new Date() - var neg = /-/.test(dt.toString()) ? '-' : '' - var dtOffset = dt.getTimezoneOffset() - var comparator = Number(''.concat(neg).concat(Math.abs(dtOffset))) // moment correctly provides positive/negative offset, as expected - - var mtOffset = DateTime.local().offset - return mtOffset > comparator ? 1 : 0 - } - - return new DateLocalizer({ - format: function format(value, _format, culture) { - if (culture) { - return formatDateWithCulture(value, culture, _format) - } - - return formatDate(value, _format) - }, - formats: formats$3, - firstOfWeek: firstOfWeek, - firstVisibleDay: firstVisibleDay, - lastVisibleDay: lastVisibleDay, - visibleDays: visibleDays, - lt: lt, - lte: lte, - gt: gt, - gte: gte, - eq: eq, - neq: neq, - merge: merge, - inRange: inRange, - startOf: startOf, - endOf: endOf, - range: range, - add: add, - diff: diff, - ceil: ceil, - min: min, - max: max, - getSlotDate: getSlotDate, - getTotalMin: getTotalMin, - getMinutesFromMidnight: getMinutesFromMidnight, - continuesPrior: continuesPrior, - continuesAfter: continuesAfter, - sortEvents: sortEvents, - inEventRange: inEventRange, - isSameDate: isSameDate, - browserTZOffset: browserTZOffset, - }) -} - -var dateRangeFormat$2 = function dateRangeFormat(_ref, culture, local) { - var start = _ref.start, - end = _ref.end - return ( - local.format(start, 'd', culture) + ' – ' + local.format(end, 'd', culture) - ) -} - -var timeRangeFormat$2 = function timeRangeFormat(_ref2, culture, local) { - var start = _ref2.start, - end = _ref2.end - return ( - local.format(start, 't', culture) + ' – ' + local.format(end, 't', culture) - ) -} - -var timeRangeStartFormat$2 = function timeRangeStartFormat( - _ref3, - culture, - local -) { - var start = _ref3.start - return local.format(start, 't', culture) + ' – ' -} - -var timeRangeEndFormat$2 = function timeRangeEndFormat(_ref4, culture, local) { - var end = _ref4.end - return ' – ' + local.format(end, 't', culture) -} - -var weekRangeFormat$2 = function weekRangeFormat(_ref5, culture, local) { - var start = _ref5.start, - end = _ref5.end - return ( - local.format(start, 'MMM dd', culture) + - ' – ' + - local.format(end, eq(start, end, 'month') ? 'dd' : 'MMM dd', culture) - ) -} - -var formats$2 = { - dateFormat: 'dd', - dayFormat: 'ddd dd/MM', - weekdayFormat: 'ddd', - selectRangeFormat: timeRangeFormat$2, - eventTimeRangeFormat: timeRangeFormat$2, - eventTimeRangeStartFormat: timeRangeStartFormat$2, - eventTimeRangeEndFormat: timeRangeEndFormat$2, - timeGutterFormat: 't', - monthHeaderFormat: 'Y', - dayHeaderFormat: 'dddd MMM dd', - dayRangeHeaderFormat: weekRangeFormat$2, - agendaHeaderFormat: dateRangeFormat$2, - agendaDateFormat: 'ddd MMM dd', - agendaTimeFormat: 't', - agendaTimeRangeFormat: timeRangeFormat$2, -} -function oldGlobalize(globalize) { - function getCulture(culture) { - return culture ? globalize.findClosestCulture(culture) : globalize.culture() - } - - function firstOfWeek(culture) { - culture = getCulture(culture) - return (culture && culture.calendar.firstDay) || 0 - } - - return new DateLocalizer({ - firstOfWeek: firstOfWeek, - formats: formats$2, - format: function format(value, _format, culture) { - return globalize.format(value, _format, culture) - }, - }) -} - -var dateRangeFormat$1 = function dateRangeFormat(_ref, culture, local) { - var start = _ref.start, - end = _ref.end - return ( - local.format( - start, - { - date: 'short', - }, - culture - ) + - ' – ' + - local.format( - end, - { - date: 'short', - }, - culture - ) - ) -} - -var timeRangeFormat$1 = function timeRangeFormat(_ref2, culture, local) { - var start = _ref2.start, - end = _ref2.end - return ( - local.format( - start, - { - time: 'short', - }, - culture - ) + - ' – ' + - local.format( - end, - { - time: 'short', - }, - culture - ) - ) -} - -var timeRangeStartFormat$1 = function timeRangeStartFormat( - _ref3, - culture, - local -) { - var start = _ref3.start - return ( - local.format( - start, - { - time: 'short', - }, - culture - ) + ' – ' - ) -} - -var timeRangeEndFormat$1 = function timeRangeEndFormat(_ref4, culture, local) { - var end = _ref4.end - return ( - ' – ' + - local.format( - end, - { - time: 'short', - }, - culture - ) - ) -} - -var weekRangeFormat$1 = function weekRangeFormat(_ref5, culture, local) { - var start = _ref5.start, - end = _ref5.end - return ( - local.format(start, 'MMM dd', culture) + - ' – ' + - local.format(end, eq(start, end, 'month') ? 'dd' : 'MMM dd', culture) - ) -} - -var formats$1 = { - dateFormat: 'dd', - dayFormat: 'eee dd/MM', - weekdayFormat: 'eee', - selectRangeFormat: timeRangeFormat$1, - eventTimeRangeFormat: timeRangeFormat$1, - eventTimeRangeStartFormat: timeRangeStartFormat$1, - eventTimeRangeEndFormat: timeRangeEndFormat$1, - timeGutterFormat: { - time: 'short', - }, - monthHeaderFormat: 'MMMM yyyy', - dayHeaderFormat: 'eeee MMM dd', - dayRangeHeaderFormat: weekRangeFormat$1, - agendaHeaderFormat: dateRangeFormat$1, - agendaDateFormat: 'eee MMM dd', - agendaTimeFormat: { - time: 'short', - }, - agendaTimeRangeFormat: timeRangeFormat$1, -} -function globalize(globalize) { - var locale = function locale(culture) { - return culture ? globalize(culture) : globalize - } // return the first day of the week from the locale data. Defaults to 'world' - // territory if no territory is derivable from CLDR. - // Failing to use CLDR supplemental (not loaded?), revert to the original - // method of getting first day of week. - - function firstOfWeek(culture) { - try { - var days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] - var cldr = locale(culture).cldr - var territory = cldr.attributes.territory - var weekData = cldr.get('supplemental').weekData - var firstDay = weekData.firstDay[territory || '001'] - return days.indexOf(firstDay) - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - console.error( - 'Failed to accurately determine first day of the week.' + - ' Is supplemental data loaded into CLDR?' - ) - } // maybe cldr supplemental is not loaded? revert to original method - - var date = new Date() //cldr-data doesn't seem to be zero based - - var localeDay = Math.max( - parseInt( - locale(culture).formatDate(date, { - raw: 'e', - }), - 10 - ) - 1, - 0 - ) - return Math.abs(date.getDay() - localeDay) - } - } - - if (!globalize.load) return oldGlobalize(globalize) - return new DateLocalizer({ - firstOfWeek: firstOfWeek, - formats: formats$1, - format: function format(value, _format, culture) { - _format = - typeof _format === 'string' - ? { - raw: _format, - } - : _format - return locale(culture).formatDate(value, _format) - }, - }) -} - -var dateRangeFormat = function dateRangeFormat(_ref, culture, local) { - var start = _ref.start, - end = _ref.end - return '' - .concat(local.format(start, 'P', culture), ' \u2013 ') - .concat(local.format(end, 'P', culture)) -} - -var timeRangeFormat = function timeRangeFormat(_ref2, culture, local) { - var start = _ref2.start, - end = _ref2.end - return '' - .concat(local.format(start, 'p', culture), ' \u2013 ') - .concat(local.format(end, 'p', culture)) -} - -var timeRangeStartFormat = function timeRangeStartFormat( - _ref3, - culture, - local -) { - var start = _ref3.start - return ''.concat(local.format(start, 'h:mma', culture), ' \u2013 ') -} - -var timeRangeEndFormat = function timeRangeEndFormat(_ref4, culture, local) { - var end = _ref4.end - return ' \u2013 '.concat(local.format(end, 'h:mma', culture)) -} - -var weekRangeFormat = function weekRangeFormat(_ref5, culture, local) { - var start = _ref5.start, - end = _ref5.end - return '' - .concat(local.format(start, 'MMMM dd', culture), ' \u2013 ') - .concat( - local.format(end, eq(start, end, 'month') ? 'dd' : 'MMMM dd', culture) - ) -} - -var formats = { - dateFormat: 'dd', - dayFormat: 'dd eee', - weekdayFormat: 'cccc', - selectRangeFormat: timeRangeFormat, - eventTimeRangeFormat: timeRangeFormat, - eventTimeRangeStartFormat: timeRangeStartFormat, - eventTimeRangeEndFormat: timeRangeEndFormat, - timeGutterFormat: 'p', - monthHeaderFormat: 'MMMM yyyy', - dayHeaderFormat: 'cccc MMM dd', - dayRangeHeaderFormat: weekRangeFormat, - agendaHeaderFormat: dateRangeFormat, - agendaDateFormat: 'ccc MMM dd', - agendaTimeFormat: 'p', - agendaTimeRangeFormat: timeRangeFormat, -} - -var dateFnsLocalizer = function dateFnsLocalizer(_ref6) { - var startOfWeek = _ref6.startOfWeek, - getDay = _ref6.getDay, - _format = _ref6.format, - locales = _ref6.locales - return new DateLocalizer({ - formats: formats, - firstOfWeek: function firstOfWeek(culture) { - return getDay( - startOfWeek(new Date(), { - locale: locales[culture], - }) - ) - }, - format: function format(value, formatString, culture) { - return _format(new Date(value), formatString, { - locale: locales[culture], - }) - }, - }) -} - -var components = { - eventWrapper: NoopWrapper, - timeSlotWrapper: NoopWrapper, - dateCellWrapper: NoopWrapper, -} - -export { - Calendar$1 as Calendar, - DateLocalizer, - navigate as Navigate, - views as Views, - components, - dateFnsLocalizer, - globalize as globalizeLocalizer, - luxon as luxonLocalizer, - moment as momentLocalizer, - moveDate as move, -} diff --git a/dist/react-big-calendar.js b/dist/react-big-calendar.js deleted file mode 100644 index 86b259aa5..000000000 --- a/dist/react-big-calendar.js +++ /dev/null @@ -1,56418 +0,0 @@ -;(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' - ? factory(exports) - : typeof define === 'function' && define.amd - ? define(['exports'], factory) - : ((global = - typeof globalThis !== 'undefined' ? globalThis : global || self), - factory((global.ReactBigCalendar = {}))) -})(this, function (exports) { - 'use strict' - - function NoopWrapper(props) { - return props.children - } - - function _defineProperty$1(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true, - }) - } else { - obj[key] = value - } - - return obj - } - - 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 _objectSpread2(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$1(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 - } - - function _objectWithoutPropertiesLoose$1(source, excluded) { - if (source == null) return {} - var target = {} - var sourceKeys = Object.keys(source) - var key, i - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i] - if (excluded.indexOf(key) >= 0) continue - target[key] = source[key] - } - - return target - } - - function _objectWithoutProperties(source, excluded) { - if (source == null) return {} - var target = _objectWithoutPropertiesLoose$1(source, excluded) - var key, i - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source) - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i] - if (excluded.indexOf(key) >= 0) continue - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue - target[key] = source[key] - } - } - - return target - } - - function _typeof(obj) { - '@babel/helpers - typeof' - - return ( - (_typeof = - 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator - ? function (obj) { - return typeof obj - } - : function (obj) { - return obj && - 'function' == typeof Symbol && - obj.constructor === Symbol && - obj !== Symbol.prototype - ? 'symbol' - : typeof obj - }), - _typeof(obj) - ) - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError('Cannot call a class as a function') - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i] - descriptor.enumerable = descriptor.enumerable || false - descriptor.configurable = true - if ('value' in descriptor) descriptor.writable = true - Object.defineProperty(target, descriptor.key, descriptor) - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps) - if (staticProps) _defineProperties(Constructor, staticProps) - Object.defineProperty(Constructor, 'prototype', { - writable: false, - }) - return Constructor - } - - function _setPrototypeOf$1(o, p) { - _setPrototypeOf$1 = Object.setPrototypeOf - ? Object.setPrototypeOf.bind() - : function _setPrototypeOf(o, p) { - o.__proto__ = p - return o - } - return _setPrototypeOf$1(o, p) - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== 'function' && superClass !== null) { - throw new TypeError('Super expression must either be null or a function') - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true, - }, - }) - Object.defineProperty(subClass, 'prototype', { - writable: false, - }) - if (superClass) _setPrototypeOf$1(subClass, superClass) - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf - ? Object.getPrototypeOf.bind() - : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o) - } - return _getPrototypeOf(o) - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === 'undefined' || !Reflect.construct) return false - if (Reflect.construct.sham) return false - if (typeof Proxy === 'function') return true - - try { - Boolean.prototype.valueOf.call( - Reflect.construct(Boolean, [], function () {}) - ) - return true - } catch (e) { - return false - } - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ) - } - - return self - } - - function _possibleConstructorReturn(self, call) { - if (call && (_typeof(call) === 'object' || typeof call === 'function')) { - return call - } else if (call !== void 0) { - throw new TypeError( - 'Derived constructors may only return object or undefined' - ) - } - - return _assertThisInitialized(self) - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct() - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor - result = Reflect.construct(Super, arguments, NewTarget) - } else { - result = Super.apply(this, arguments) - } - - return _possibleConstructorReturn(this, result) - } - } - - var commonjsGlobal = - typeof globalThis !== 'undefined' - ? globalThis - : typeof window !== 'undefined' - ? window - : typeof global !== 'undefined' - ? global - : typeof self !== 'undefined' - ? self - : {} - - function getDefaultExportFromCjs(x) { - return x && - x.__esModule && - Object.prototype.hasOwnProperty.call(x, 'default') - ? x['default'] - : x - } - - var react = { exports: {} } - - var react_development = {} - - /* - object-assign - (c) Sindre Sorhus - @license MIT - */ - /* eslint-disable no-unused-vars */ - var getOwnPropertySymbols = Object.getOwnPropertySymbols - var hasOwnProperty$e = Object.prototype.hasOwnProperty - var propIsEnumerable = Object.prototype.propertyIsEnumerable - - function toObject(val) { - if (val === null || val === undefined) { - throw new TypeError( - 'Object.assign cannot be called with null or undefined' - ) - } - - return Object(val) - } - - function shouldUseNative() { - try { - if (!Object.assign) { - return false - } - - // Detect buggy property enumeration order in older V8 versions. - - // https://bugs.chromium.org/p/v8/issues/detail?id=4118 - var test1 = new String('abc') // eslint-disable-line no-new-wrappers - test1[5] = 'de' - if (Object.getOwnPropertyNames(test1)[0] === '5') { - return false - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test2 = {} - for (var i = 0; i < 10; i++) { - test2['_' + String.fromCharCode(i)] = i - } - var order2 = Object.getOwnPropertyNames(test2).map(function (n) { - return test2[n] - }) - if (order2.join('') !== '0123456789') { - return false - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test3 = {} - 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { - test3[letter] = letter - }) - if ( - Object.keys(Object.assign({}, test3)).join('') !== - 'abcdefghijklmnopqrst' - ) { - return false - } - - return true - } catch (err) { - // We don't expect any of the above to throw, but better to be safe. - return false - } - } - - var objectAssign = shouldUseNative() - ? Object.assign - : function (target, source) { - var from - var to = toObject(target) - var symbols - - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments[s]) - - for (var key in from) { - if (hasOwnProperty$e.call(from, key)) { - to[key] = from[key] - } - } - - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from) - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]] - } - } - } - } - - return to - } - - /** @license React v17.0.2 - * react.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - ;(function (exports) { - { - ;(function () { - var _assign = objectAssign - - // TODO: this is special because it gets imported during build. - var ReactVersion = '17.0.2' - - // ATTENTION - // When adding new symbols to this file, - // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' - // The Symbol used to tag the ReactElement-like types. If there is no native Symbol - // nor polyfill, then a plain number is used for performance. - var REACT_ELEMENT_TYPE = 0xeac7 - var REACT_PORTAL_TYPE = 0xeaca - exports.Fragment = 0xeacb - exports.StrictMode = 0xeacc - exports.Profiler = 0xead2 - var REACT_PROVIDER_TYPE = 0xeacd - var REACT_CONTEXT_TYPE = 0xeace - var REACT_FORWARD_REF_TYPE = 0xead0 - exports.Suspense = 0xead1 - var REACT_SUSPENSE_LIST_TYPE = 0xead8 - var REACT_MEMO_TYPE = 0xead3 - var REACT_LAZY_TYPE = 0xead4 - var REACT_BLOCK_TYPE = 0xead9 - var REACT_SERVER_BLOCK_TYPE = 0xeada - var REACT_FUNDAMENTAL_TYPE = 0xead5 - var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1 - var REACT_LEGACY_HIDDEN_TYPE = 0xeae3 - - if (typeof Symbol === 'function' && Symbol.for) { - var symbolFor = Symbol.for - REACT_ELEMENT_TYPE = symbolFor('react.element') - REACT_PORTAL_TYPE = symbolFor('react.portal') - exports.Fragment = symbolFor('react.fragment') - exports.StrictMode = symbolFor('react.strict_mode') - exports.Profiler = symbolFor('react.profiler') - REACT_PROVIDER_TYPE = symbolFor('react.provider') - REACT_CONTEXT_TYPE = symbolFor('react.context') - REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref') - exports.Suspense = symbolFor('react.suspense') - REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list') - REACT_MEMO_TYPE = symbolFor('react.memo') - REACT_LAZY_TYPE = symbolFor('react.lazy') - REACT_BLOCK_TYPE = symbolFor('react.block') - REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block') - REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental') - symbolFor('react.scope') - symbolFor('react.opaque.id') - REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode') - symbolFor('react.offscreen') - REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden') - } - - var MAYBE_ITERATOR_SYMBOL = - typeof Symbol === 'function' && Symbol.iterator - var FAUX_ITERATOR_SYMBOL = '@@iterator' - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== 'object') { - return null - } - - var maybeIterator = - (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || - maybeIterable[FAUX_ITERATOR_SYMBOL] - - if (typeof maybeIterator === 'function') { - return maybeIterator - } - - return null - } - - /** - * Keeps track of the current dispatcher. - */ - var ReactCurrentDispatcher = { - /** - * @internal - * @type {ReactComponent} - */ - current: null, - } - - /** - * Keeps track of the current batch's configuration such as how long an update - * should suspend for if it needs to. - */ - var ReactCurrentBatchConfig = { - transition: 0, - } - - /** - * Keeps track of the current owner. - * - * The current owner is the component who should own any components that are - * currently being constructed. - */ - var ReactCurrentOwner = { - /** - * @internal - * @type {ReactComponent} - */ - current: null, - } - - var ReactDebugCurrentFrame = {} - var currentExtraStackFrame = null - function setExtraStackFrame(stack) { - { - currentExtraStackFrame = stack - } - } - - { - ReactDebugCurrentFrame.setExtraStackFrame = function (stack) { - { - currentExtraStackFrame = stack - } - } // Stack implementation injected by the current renderer. - - ReactDebugCurrentFrame.getCurrentStack = null - - ReactDebugCurrentFrame.getStackAddendum = function () { - var stack = '' // Add an extra top frame while an element is being validated - - if (currentExtraStackFrame) { - stack += currentExtraStackFrame - } // Delegate to the injected renderer-specific implementation - - var impl = ReactDebugCurrentFrame.getCurrentStack - - if (impl) { - stack += impl() || '' - } - - return stack - } - } - - /** - * Used by act() to track whether you're inside an act() scope. - */ - var IsSomeRendererActing = { - current: false, - } - - var ReactSharedInternals = { - ReactCurrentDispatcher: ReactCurrentDispatcher, - ReactCurrentBatchConfig: ReactCurrentBatchConfig, - ReactCurrentOwner: ReactCurrentOwner, - IsSomeRendererActing: IsSomeRendererActing, - // Used by renderers to avoid bundling object-assign twice in UMD bundles: - assign: _assign, - } - - { - ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame - } - - // by calls to these methods by a Babel plugin. - // - // In PROD (or in packages without access to React internals), - // they are left as they are instead. - - function warn(format) { - { - for ( - var _len = arguments.length, - args = new Array(_len > 1 ? _len - 1 : 0), - _key = 1; - _key < _len; - _key++ - ) { - args[_key - 1] = arguments[_key] - } - - printWarning('warn', format, args) - } - } - function error(format) { - { - for ( - var _len2 = arguments.length, - args = new Array(_len2 > 1 ? _len2 - 1 : 0), - _key2 = 1; - _key2 < _len2; - _key2++ - ) { - args[_key2 - 1] = arguments[_key2] - } - - printWarning('error', format, args) - } - } - - function printWarning(level, format, args) { - // When changing this logic, you might want to also - // update consoleWithStackDev.www.js as well. - { - var ReactDebugCurrentFrame = - ReactSharedInternals.ReactDebugCurrentFrame - var stack = ReactDebugCurrentFrame.getStackAddendum() - - if (stack !== '') { - format += '%s' - args = args.concat([stack]) - } - - var argsWithFormat = args.map(function (item) { - return '' + item - }) // Careful: RN currently depends on this prefix - - argsWithFormat.unshift('Warning: ' + format) // We intentionally don't use spread (or .apply) directly because it - // breaks IE9: https://github.com/facebook/react/issues/13610 - // eslint-disable-next-line react-internal/no-production-logging - - Function.prototype.apply.call( - console[level], - console, - argsWithFormat - ) - } - } - - var didWarnStateUpdateForUnmountedComponent = {} - - function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor - var componentName = - (_constructor && - (_constructor.displayName || _constructor.name)) || - 'ReactClass' - var warningKey = componentName + '.' + callerName - - if (didWarnStateUpdateForUnmountedComponent[warningKey]) { - return - } - - error( - "Can't call %s on a component that is not yet mounted. " + - 'This is a no-op, but it might indicate a bug in your application. ' + - 'Instead, assign to `this.state` directly or define a `state = {};` ' + - 'class property with the desired state in the %s component.', - callerName, - componentName - ) - - didWarnStateUpdateForUnmountedComponent[warningKey] = true - } - } - /** - * This is the abstract API for an update queue. - */ - - var ReactNoopUpdateQueue = { - /** - * Checks whether or not this composite component is mounted. - * @param {ReactClass} publicInstance The instance we want to test. - * @return {boolean} True if mounted, false otherwise. - * @protected - * @final - */ - isMounted: function (publicInstance) { - return false - }, - - /** - * Forces an update. This should only be invoked when it is known with - * certainty that we are **not** in a DOM transaction. - * - * You may want to call this when you know that some deeper aspect of the - * component's state has changed but `setState` was not called. - * - * This will not invoke `shouldComponentUpdate`, but it will invoke - * `componentWillUpdate` and `componentDidUpdate`. - * - * @param {ReactClass} publicInstance The instance that should rerender. - * @param {?function} callback Called after component is updated. - * @param {?string} callerName name of the calling function in the public API. - * @internal - */ - enqueueForceUpdate: function (publicInstance, callback, callerName) { - warnNoop(publicInstance, 'forceUpdate') - }, - - /** - * Replaces all of the state. Always use this or `setState` to mutate state. - * You should treat `this.state` as immutable. - * - * There is no guarantee that `this.state` will be immediately updated, so - * accessing `this.state` after calling this method may return the old value. - * - * @param {ReactClass} publicInstance The instance that should rerender. - * @param {object} completeState Next state. - * @param {?function} callback Called after component is updated. - * @param {?string} callerName name of the calling function in the public API. - * @internal - */ - enqueueReplaceState: function ( - publicInstance, - completeState, - callback, - callerName - ) { - warnNoop(publicInstance, 'replaceState') - }, - - /** - * Sets a subset of the state. This only exists because _pendingState is - * internal. This provides a merging strategy that is not available to deep - * properties which is confusing. TODO: Expose pendingState or don't use it - * during the merge. - * - * @param {ReactClass} publicInstance The instance that should rerender. - * @param {object} partialState Next partial state to be merged with state. - * @param {?function} callback Called after component is updated. - * @param {?string} Name of the calling function in the public API. - * @internal - */ - enqueueSetState: function ( - publicInstance, - partialState, - callback, - callerName - ) { - warnNoop(publicInstance, 'setState') - }, - } - - var emptyObject = {} - - { - Object.freeze(emptyObject) - } - /** - * Base class helpers for the updating state of a component. - */ - - function Component(props, context, updater) { - this.props = props - this.context = context // If a component has string refs, we will assign a different object later. - - this.refs = emptyObject // We initialize the default updater but the real one gets injected by the - // renderer. - - this.updater = updater || ReactNoopUpdateQueue - } - - Component.prototype.isReactComponent = {} - /** - * Sets a subset of the state. Always use this to mutate - * state. You should treat `this.state` as immutable. - * - * There is no guarantee that `this.state` will be immediately updated, so - * accessing `this.state` after calling this method may return the old value. - * - * There is no guarantee that calls to `setState` will run synchronously, - * as they may eventually be batched together. You can provide an optional - * callback that will be executed when the call to setState is actually - * completed. - * - * When a function is provided to setState, it will be called at some point in - * the future (not synchronously). It will be called with the up to date - * component arguments (state, props, context). These values can be different - * from this.* because your function may be called after receiveProps but before - * shouldComponentUpdate, and this new state, props, and context will not yet be - * assigned to this. - * - * @param {object|function} partialState Next partial state or function to - * produce next partial state to be merged with current state. - * @param {?function} callback Called after state is updated. - * @final - * @protected - */ - - Component.prototype.setState = function (partialState, callback) { - if ( - !( - typeof partialState === 'object' || - typeof partialState === 'function' || - partialState == null - ) - ) { - { - throw Error( - 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.' - ) - } - } - - this.updater.enqueueSetState(this, partialState, callback, 'setState') - } - /** - * Forces an update. This should only be invoked when it is known with - * certainty that we are **not** in a DOM transaction. - * - * You may want to call this when you know that some deeper aspect of the - * component's state has changed but `setState` was not called. - * - * This will not invoke `shouldComponentUpdate`, but it will invoke - * `componentWillUpdate` and `componentDidUpdate`. - * - * @param {?function} callback Called after update is complete. - * @final - * @protected - */ - - Component.prototype.forceUpdate = function (callback) { - this.updater.enqueueForceUpdate(this, callback, 'forceUpdate') - } - /** - * Deprecated APIs. These APIs used to exist on classic React classes but since - * we would like to deprecate them, we're not going to move them over to this - * modern base class. Instead, we define a getter that warns if it's accessed. - */ - - { - var deprecatedAPIs = { - isMounted: [ - 'isMounted', - 'Instead, make sure to clean up subscriptions and pending requests in ' + - 'componentWillUnmount to prevent memory leaks.', - ], - replaceState: [ - 'replaceState', - 'Refactor your code to use setState instead (see ' + - 'https://github.com/facebook/react/issues/3236).', - ], - } - - var defineDeprecationWarning = function (methodName, info) { - Object.defineProperty(Component.prototype, methodName, { - get: function () { - warn( - '%s(...) is deprecated in plain JavaScript React classes. %s', - info[0], - info[1] - ) - - return undefined - }, - }) - } - - for (var fnName in deprecatedAPIs) { - if (deprecatedAPIs.hasOwnProperty(fnName)) { - defineDeprecationWarning(fnName, deprecatedAPIs[fnName]) - } - } - } - - function ComponentDummy() {} - - ComponentDummy.prototype = Component.prototype - /** - * Convenience component with default shallow equality check for sCU. - */ - - function PureComponent(props, context, updater) { - this.props = props - this.context = context // If a component has string refs, we will assign a different object later. - - this.refs = emptyObject - this.updater = updater || ReactNoopUpdateQueue - } - - var pureComponentPrototype = (PureComponent.prototype = - new ComponentDummy()) - pureComponentPrototype.constructor = PureComponent // Avoid an extra prototype jump for these methods. - - _assign(pureComponentPrototype, Component.prototype) - - pureComponentPrototype.isPureReactComponent = true - - // an immutable object with a single mutable value - function createRef() { - var refObject = { - current: null, - } - - { - Object.seal(refObject) - } - - return refObject - } - - function getWrappedName(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || '' - return ( - outerType.displayName || - (functionName !== '' - ? wrapperName + '(' + functionName + ')' - : wrapperName) - ) - } - - function getContextName(type) { - return type.displayName || 'Context' - } - - function getComponentName(type) { - if (type == null) { - // Host root, text node or just invalid type. - return null - } - - { - if (typeof type.tag === 'number') { - error( - 'Received an unexpected object in getComponentName(). ' + - 'This is likely a bug in React. Please file an issue.' - ) - } - } - - if (typeof type === 'function') { - return type.displayName || type.name || null - } - - if (typeof type === 'string') { - return type - } - - switch (type) { - case exports.Fragment: - return 'Fragment' - - case REACT_PORTAL_TYPE: - return 'Portal' - - case exports.Profiler: - return 'Profiler' - - case exports.StrictMode: - return 'StrictMode' - - case exports.Suspense: - return 'Suspense' - - case REACT_SUSPENSE_LIST_TYPE: - return 'SuspenseList' - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type - return getContextName(context) + '.Consumer' - - case REACT_PROVIDER_TYPE: - var provider = type - return getContextName(provider._context) + '.Provider' - - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, 'ForwardRef') - - case REACT_MEMO_TYPE: - return getComponentName(type.type) - - case REACT_BLOCK_TYPE: - return getComponentName(type._render) - - case REACT_LAZY_TYPE: { - var lazyComponent = type - var payload = lazyComponent._payload - var init = lazyComponent._init - - try { - return getComponentName(init(payload)) - } catch (x) { - return null - } - } - } - } - - return null - } - - var hasOwnProperty = Object.prototype.hasOwnProperty - var RESERVED_PROPS = { - key: true, - ref: true, - __self: true, - __source: true, - } - var specialPropKeyWarningShown, - specialPropRefWarningShown, - didWarnAboutStringRefs - - { - didWarnAboutStringRefs = {} - } - - function hasValidRef(config) { - { - if (hasOwnProperty.call(config, 'ref')) { - var getter = Object.getOwnPropertyDescriptor(config, 'ref').get - - if (getter && getter.isReactWarning) { - return false - } - } - } - - return config.ref !== undefined - } - - function hasValidKey(config) { - { - if (hasOwnProperty.call(config, 'key')) { - var getter = Object.getOwnPropertyDescriptor(config, 'key').get - - if (getter && getter.isReactWarning) { - return false - } - } - } - - return config.key !== undefined - } - - function defineKeyPropWarningGetter(props, displayName) { - var warnAboutAccessingKey = function () { - { - if (!specialPropKeyWarningShown) { - specialPropKeyWarningShown = true - - error( - '%s: `key` is not a prop. Trying to access it will result ' + - 'in `undefined` being returned. If you need to access the same ' + - 'value within the child component, you should pass it as a different ' + - 'prop. (https://reactjs.org/link/special-props)', - displayName - ) - } - } - } - - warnAboutAccessingKey.isReactWarning = true - Object.defineProperty(props, 'key', { - get: warnAboutAccessingKey, - configurable: true, - }) - } - - function defineRefPropWarningGetter(props, displayName) { - var warnAboutAccessingRef = function () { - { - if (!specialPropRefWarningShown) { - specialPropRefWarningShown = true - - error( - '%s: `ref` is not a prop. Trying to access it will result ' + - 'in `undefined` being returned. If you need to access the same ' + - 'value within the child component, you should pass it as a different ' + - 'prop. (https://reactjs.org/link/special-props)', - displayName - ) - } - } - } - - warnAboutAccessingRef.isReactWarning = true - Object.defineProperty(props, 'ref', { - get: warnAboutAccessingRef, - configurable: true, - }) - } - - function warnIfStringRefCannotBeAutoConverted(config) { - { - if ( - typeof config.ref === 'string' && - ReactCurrentOwner.current && - config.__self && - ReactCurrentOwner.current.stateNode !== config.__self - ) { - var componentName = getComponentName( - ReactCurrentOwner.current.type - ) - - if (!didWarnAboutStringRefs[componentName]) { - error( - 'Component "%s" contains the string ref "%s". ' + - 'Support for string refs will be removed in a future major release. ' + - 'This case cannot be automatically converted to an arrow function. ' + - 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + - 'Learn more about using refs safely here: ' + - 'https://reactjs.org/link/strict-mode-string-ref', - componentName, - config.ref - ) - - didWarnAboutStringRefs[componentName] = true - } - } - } - } - /** - * Factory method to create a new React element. This no longer adheres to - * the class pattern, so do not use new to call it. Also, instanceof check - * will not work. Instead test $$typeof field against Symbol.for('react.element') to check - * if something is a React Element. - * - * @param {*} type - * @param {*} props - * @param {*} key - * @param {string|object} ref - * @param {*} owner - * @param {*} self A *temporary* helper to detect places where `this` is - * different from the `owner` when React.createElement is called, so that we - * can warn. We want to get rid of owner and replace string `ref`s with arrow - * functions, and as long as `this` and owner are the same, there will be no - * change in behavior. - * @param {*} source An annotation object (added by a transpiler or otherwise) - * indicating filename, line number, and/or other information. - * @internal - */ - - var ReactElement = function ( - type, - key, - ref, - self, - source, - owner, - props - ) { - var element = { - // This tag allows us to uniquely identify this as a React Element - $$typeof: REACT_ELEMENT_TYPE, - // Built-in properties that belong on the element - type: type, - key: key, - ref: ref, - props: props, - // Record the component responsible for creating this element. - _owner: owner, - } - - { - // The validation flag is currently mutative. We put it on - // an external backing store so that we can freeze the whole object. - // This can be replaced with a WeakMap once they are implemented in - // commonly used development environments. - element._store = {} // To make comparing ReactElements easier for testing purposes, we make - // the validation flag non-enumerable (where possible, which should - // include every environment we run tests in), so the test framework - // ignores it. - - Object.defineProperty(element._store, 'validated', { - configurable: false, - enumerable: false, - writable: true, - value: false, - }) // self and source are DEV only properties. - - Object.defineProperty(element, '_self', { - configurable: false, - enumerable: false, - writable: false, - value: self, - }) // Two elements created in two different places should be considered - // equal for testing purposes and therefore we hide it from enumeration. - - Object.defineProperty(element, '_source', { - configurable: false, - enumerable: false, - writable: false, - value: source, - }) - - if (Object.freeze) { - Object.freeze(element.props) - Object.freeze(element) - } - } - - return element - } - /** - * Create and return a new ReactElement of the given type. - * See https://reactjs.org/docs/react-api.html#createelement - */ - - function createElement(type, config, children) { - var propName // Reserved names are extracted - - var props = {} - var key = null - var ref = null - var self = null - var source = null - - if (config != null) { - if (hasValidRef(config)) { - ref = config.ref - - { - warnIfStringRefCannotBeAutoConverted(config) - } - } - - if (hasValidKey(config)) { - key = '' + config.key - } - - self = config.__self === undefined ? null : config.__self - source = config.__source === undefined ? null : config.__source // Remaining properties are added to a new props object - - for (propName in config) { - if ( - hasOwnProperty.call(config, propName) && - !RESERVED_PROPS.hasOwnProperty(propName) - ) { - props[propName] = config[propName] - } - } - } // Children can be more than one argument, and those are transferred onto - // the newly allocated props object. - - var childrenLength = arguments.length - 2 - - if (childrenLength === 1) { - props.children = children - } else if (childrenLength > 1) { - var childArray = Array(childrenLength) - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 2] - } - - { - if (Object.freeze) { - Object.freeze(childArray) - } - } - - props.children = childArray - } // Resolve default props - - if (type && type.defaultProps) { - var defaultProps = type.defaultProps - - for (propName in defaultProps) { - if (props[propName] === undefined) { - props[propName] = defaultProps[propName] - } - } - } - - { - if (key || ref) { - var displayName = - typeof type === 'function' - ? type.displayName || type.name || 'Unknown' - : type - - if (key) { - defineKeyPropWarningGetter(props, displayName) - } - - if (ref) { - defineRefPropWarningGetter(props, displayName) - } - } - } - - return ReactElement( - type, - key, - ref, - self, - source, - ReactCurrentOwner.current, - props - ) - } - function cloneAndReplaceKey(oldElement, newKey) { - var newElement = ReactElement( - oldElement.type, - newKey, - oldElement.ref, - oldElement._self, - oldElement._source, - oldElement._owner, - oldElement.props - ) - return newElement - } - /** - * Clone and return a new ReactElement using element as the starting point. - * See https://reactjs.org/docs/react-api.html#cloneelement - */ - - function cloneElement(element, config, children) { - if (!!(element === null || element === undefined)) { - { - throw Error( - 'React.cloneElement(...): The argument must be a React element, but you passed ' + - element + - '.' - ) - } - } - - var propName // Original props are copied - - var props = _assign({}, element.props) // Reserved names are extracted - - var key = element.key - var ref = element.ref // Self is preserved since the owner is preserved. - - var self = element._self // Source is preserved since cloneElement is unlikely to be targeted by a - // transpiler, and the original source is probably a better indicator of the - // true owner. - - var source = element._source // Owner will be preserved, unless ref is overridden - - var owner = element._owner - - if (config != null) { - if (hasValidRef(config)) { - // Silently steal the ref from the parent. - ref = config.ref - owner = ReactCurrentOwner.current - } - - if (hasValidKey(config)) { - key = '' + config.key - } // Remaining properties override existing props - - var defaultProps - - if (element.type && element.type.defaultProps) { - defaultProps = element.type.defaultProps - } - - for (propName in config) { - if ( - hasOwnProperty.call(config, propName) && - !RESERVED_PROPS.hasOwnProperty(propName) - ) { - if ( - config[propName] === undefined && - defaultProps !== undefined - ) { - // Resolve default props - props[propName] = defaultProps[propName] - } else { - props[propName] = config[propName] - } - } - } - } // Children can be more than one argument, and those are transferred onto - // the newly allocated props object. - - var childrenLength = arguments.length - 2 - - if (childrenLength === 1) { - props.children = children - } else if (childrenLength > 1) { - var childArray = Array(childrenLength) - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 2] - } - - props.children = childArray - } - - return ReactElement( - element.type, - key, - ref, - self, - source, - owner, - props - ) - } - /** - * Verifies the object is a ReactElement. - * See https://reactjs.org/docs/react-api.html#isvalidelement - * @param {?object} object - * @return {boolean} True if `object` is a ReactElement. - * @final - */ - - function isValidElement(object) { - return ( - typeof object === 'object' && - object !== null && - object.$$typeof === REACT_ELEMENT_TYPE - ) - } - - var SEPARATOR = '.' - var SUBSEPARATOR = ':' - /** - * Escape and wrap key so it is safe to use as a reactid - * - * @param {string} key to be escaped. - * @return {string} the escaped key. - */ - - function escape(key) { - var escapeRegex = /[=:]/g - var escaperLookup = { - '=': '=0', - ':': '=2', - } - var escapedString = key.replace(escapeRegex, function (match) { - return escaperLookup[match] - }) - return '$' + escapedString - } - /** - * TODO: Test that a single child and an array with one item have the same key - * pattern. - */ - - var didWarnAboutMaps = false - var userProvidedKeyEscapeRegex = /\/+/g - - function escapeUserProvidedKey(text) { - return text.replace(userProvidedKeyEscapeRegex, '$&/') - } - /** - * Generate a key string that identifies a element within a set. - * - * @param {*} element A element that could contain a manual key. - * @param {number} index Index that is used if a manual key is not provided. - * @return {string} - */ - - function getElementKey(element, index) { - // Do some typechecking here since we call this blindly. We want to ensure - // that we don't block potential future ES APIs. - if ( - typeof element === 'object' && - element !== null && - element.key != null - ) { - // Explicit key - return escape('' + element.key) - } // Implicit key determined by the index in the set - - return index.toString(36) - } - - function mapIntoArray( - children, - array, - escapedPrefix, - nameSoFar, - callback - ) { - var type = typeof children - - if (type === 'undefined' || type === 'boolean') { - // All of the above are perceived as null. - children = null - } - - var invokeCallback = false - - if (children === null) { - invokeCallback = true - } else { - switch (type) { - case 'string': - case 'number': - invokeCallback = true - break - - case 'object': - switch (children.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - invokeCallback = true - } - } - } - - if (invokeCallback) { - var _child = children - var mappedChild = callback(_child) // If it's the only child, treat the name as if it was wrapped in an array - // so that it's consistent if the number of children grows: - - var childKey = - nameSoFar === '' - ? SEPARATOR + getElementKey(_child, 0) - : nameSoFar - - if (Array.isArray(mappedChild)) { - var escapedChildKey = '' - - if (childKey != null) { - escapedChildKey = escapeUserProvidedKey(childKey) + '/' - } - - mapIntoArray( - mappedChild, - array, - escapedChildKey, - '', - function (c) { - return c - } - ) - } else if (mappedChild != null) { - if (isValidElement(mappedChild)) { - mappedChild = cloneAndReplaceKey( - mappedChild, // Keep both the (mapped) and old keys if they differ, just as - // traverseAllChildren used to do for objects as children - escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key - (mappedChild.key && - (!_child || _child.key !== mappedChild.key) // $FlowFixMe Flow incorrectly thinks existing element's key can be a number - ? escapeUserProvidedKey('' + mappedChild.key) + '/' - : '') + - childKey - ) - } - - array.push(mappedChild) - } - - return 1 - } - - var child - var nextName - var subtreeCount = 0 // Count of children found in the current subtree. - - var nextNamePrefix = - nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR - - if (Array.isArray(children)) { - for (var i = 0; i < children.length; i++) { - child = children[i] - nextName = nextNamePrefix + getElementKey(child, i) - subtreeCount += mapIntoArray( - child, - array, - escapedPrefix, - nextName, - callback - ) - } - } else { - var iteratorFn = getIteratorFn(children) - - if (typeof iteratorFn === 'function') { - var iterableChildren = children - - { - // Warn about using Maps as children - if (iteratorFn === iterableChildren.entries) { - if (!didWarnAboutMaps) { - warn( - 'Using Maps as children is not supported. ' + - 'Use an array of keyed ReactElements instead.' - ) - } - - didWarnAboutMaps = true - } - } - - var iterator = iteratorFn.call(iterableChildren) - var step - var ii = 0 - - while (!(step = iterator.next()).done) { - child = step.value - nextName = nextNamePrefix + getElementKey(child, ii++) - subtreeCount += mapIntoArray( - child, - array, - escapedPrefix, - nextName, - callback - ) - } - } else if (type === 'object') { - var childrenString = '' + children - - { - { - throw Error( - 'Objects are not valid as a React child (found: ' + - (childrenString === '[object Object]' - ? 'object with keys {' + - Object.keys(children).join(', ') + - '}' - : childrenString) + - '). If you meant to render a collection of children, use an array instead.' - ) - } - } - } - } - - return subtreeCount - } - - /** - * Maps children that are typically specified as `props.children`. - * - * See https://reactjs.org/docs/react-api.html#reactchildrenmap - * - * The provided mapFunction(child, index) will be called for each - * leaf child. - * - * @param {?*} children Children tree container. - * @param {function(*, int)} func The map function. - * @param {*} context Context for mapFunction. - * @return {object} Object containing the ordered map of results. - */ - function mapChildren(children, func, context) { - if (children == null) { - return children - } - - var result = [] - var count = 0 - mapIntoArray(children, result, '', '', function (child) { - return func.call(context, child, count++) - }) - return result - } - /** - * Count the number of children that are typically specified as - * `props.children`. - * - * See https://reactjs.org/docs/react-api.html#reactchildrencount - * - * @param {?*} children Children tree container. - * @return {number} The number of children. - */ - - function countChildren(children) { - var n = 0 - mapChildren(children, function () { - n++ // Don't return anything - }) - return n - } - - /** - * Iterates through children that are typically specified as `props.children`. - * - * See https://reactjs.org/docs/react-api.html#reactchildrenforeach - * - * The provided forEachFunc(child, index) will be called for each - * leaf child. - * - * @param {?*} children Children tree container. - * @param {function(*, int)} forEachFunc - * @param {*} forEachContext Context for forEachContext. - */ - function forEachChildren(children, forEachFunc, forEachContext) { - mapChildren( - children, - function () { - forEachFunc.apply(this, arguments) // Don't return anything. - }, - forEachContext - ) - } - /** - * Flatten a children object (typically specified as `props.children`) and - * return an array with appropriately re-keyed children. - * - * See https://reactjs.org/docs/react-api.html#reactchildrentoarray - */ - - function toArray(children) { - return ( - mapChildren(children, function (child) { - return child - }) || [] - ) - } - /** - * Returns the first child in a collection of children and verifies that there - * is only one child in the collection. - * - * See https://reactjs.org/docs/react-api.html#reactchildrenonly - * - * The current implementation of this function assumes that a single child gets - * passed without a wrapper, but the purpose of this helper function is to - * abstract away the particular structure of children. - * - * @param {?object} children Child collection structure. - * @return {ReactElement} The first and only `ReactElement` contained in the - * structure. - */ - - function onlyChild(children) { - if (!isValidElement(children)) { - { - throw Error( - 'React.Children.only expected to receive a single React element child.' - ) - } - } - - return children - } - - function createContext(defaultValue, calculateChangedBits) { - if (calculateChangedBits === undefined) { - calculateChangedBits = null - } else { - { - if ( - calculateChangedBits !== null && - typeof calculateChangedBits !== 'function' - ) { - error( - 'createContext: Expected the optional second argument to be a ' + - 'function. Instead received: %s', - calculateChangedBits - ) - } - } - } - - var context = { - $$typeof: REACT_CONTEXT_TYPE, - _calculateChangedBits: calculateChangedBits, - // As a workaround to support multiple concurrent renderers, we categorize - // some renderers as primary and others as secondary. We only expect - // there to be two concurrent renderers at most: React Native (primary) and - // Fabric (secondary); React DOM (primary) and React ART (secondary). - // Secondary renderers store their context values on separate fields. - _currentValue: defaultValue, - _currentValue2: defaultValue, - // Used to track how many concurrent renderers this context currently - // supports within in a single renderer. Such as parallel server rendering. - _threadCount: 0, - // These are circular - Provider: null, - Consumer: null, - } - context.Provider = { - $$typeof: REACT_PROVIDER_TYPE, - _context: context, - } - var hasWarnedAboutUsingNestedContextConsumers = false - var hasWarnedAboutUsingConsumerProvider = false - var hasWarnedAboutDisplayNameOnConsumer = false - - { - // A separate object, but proxies back to the original context object for - // backwards compatibility. It has a different $$typeof, so we can properly - // warn for the incorrect usage of Context as a Consumer. - var Consumer = { - $$typeof: REACT_CONTEXT_TYPE, - _context: context, - _calculateChangedBits: context._calculateChangedBits, - } // $FlowFixMe: Flow complains about not setting a value, which is intentional here - - Object.defineProperties(Consumer, { - Provider: { - get: function () { - if (!hasWarnedAboutUsingConsumerProvider) { - hasWarnedAboutUsingConsumerProvider = true - - error( - 'Rendering is not supported and will be removed in ' + - 'a future major release. Did you mean to render instead?' - ) - } - - return context.Provider - }, - set: function (_Provider) { - context.Provider = _Provider - }, - }, - _currentValue: { - get: function () { - return context._currentValue - }, - set: function (_currentValue) { - context._currentValue = _currentValue - }, - }, - _currentValue2: { - get: function () { - return context._currentValue2 - }, - set: function (_currentValue2) { - context._currentValue2 = _currentValue2 - }, - }, - _threadCount: { - get: function () { - return context._threadCount - }, - set: function (_threadCount) { - context._threadCount = _threadCount - }, - }, - Consumer: { - get: function () { - if (!hasWarnedAboutUsingNestedContextConsumers) { - hasWarnedAboutUsingNestedContextConsumers = true - - error( - 'Rendering is not supported and will be removed in ' + - 'a future major release. Did you mean to render instead?' - ) - } - - return context.Consumer - }, - }, - displayName: { - get: function () { - return context.displayName - }, - set: function (displayName) { - if (!hasWarnedAboutDisplayNameOnConsumer) { - warn( - 'Setting `displayName` on Context.Consumer has no effect. ' + - "You should set it directly on the context with Context.displayName = '%s'.", - displayName - ) - - hasWarnedAboutDisplayNameOnConsumer = true - } - }, - }, - }) // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty - - context.Consumer = Consumer - } - - { - context._currentRenderer = null - context._currentRenderer2 = null - } - - return context - } - - var Uninitialized = -1 - var Pending = 0 - var Resolved = 1 - var Rejected = 2 - - function lazyInitializer(payload) { - if (payload._status === Uninitialized) { - var ctor = payload._result - var thenable = ctor() // Transition to the next state. - - var pending = payload - pending._status = Pending - pending._result = thenable - thenable.then( - function (moduleObject) { - if (payload._status === Pending) { - var defaultExport = moduleObject.default - - { - if (defaultExport === undefined) { - error( - 'lazy: Expected the result of a dynamic import() call. ' + - 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. - 'const MyComponent = lazy(() => imp' + - "ort('./MyComponent'))", - moduleObject - ) - } - } // Transition to the next state. - - var resolved = payload - resolved._status = Resolved - resolved._result = defaultExport - } - }, - function (error) { - if (payload._status === Pending) { - // Transition to the next state. - var rejected = payload - rejected._status = Rejected - rejected._result = error - } - } - ) - } - - if (payload._status === Resolved) { - return payload._result - } else { - throw payload._result - } - } - - function lazy(ctor) { - var payload = { - // We use these fields to store the result. - _status: -1, - _result: ctor, - } - var lazyType = { - $$typeof: REACT_LAZY_TYPE, - _payload: payload, - _init: lazyInitializer, - } - - { - // In production, this would just set it on the object. - var defaultProps - var propTypes // $FlowFixMe - - Object.defineProperties(lazyType, { - defaultProps: { - configurable: true, - get: function () { - return defaultProps - }, - set: function (newDefaultProps) { - error( - 'React.lazy(...): It is not supported to assign `defaultProps` to ' + - 'a lazy component import. Either specify them where the component ' + - 'is defined, or create a wrapping component around it.' - ) - - defaultProps = newDefaultProps // Match production behavior more closely: - // $FlowFixMe - - Object.defineProperty(lazyType, 'defaultProps', { - enumerable: true, - }) - }, - }, - propTypes: { - configurable: true, - get: function () { - return propTypes - }, - set: function (newPropTypes) { - error( - 'React.lazy(...): It is not supported to assign `propTypes` to ' + - 'a lazy component import. Either specify them where the component ' + - 'is defined, or create a wrapping component around it.' - ) - - propTypes = newPropTypes // Match production behavior more closely: - // $FlowFixMe - - Object.defineProperty(lazyType, 'propTypes', { - enumerable: true, - }) - }, - }, - }) - } - - return lazyType - } - - function forwardRef(render) { - { - if (render != null && render.$$typeof === REACT_MEMO_TYPE) { - error( - 'forwardRef requires a render function but received a `memo` ' + - 'component. Instead of forwardRef(memo(...)), use ' + - 'memo(forwardRef(...)).' - ) - } else if (typeof render !== 'function') { - error( - 'forwardRef requires a render function but was given %s.', - render === null ? 'null' : typeof render - ) - } else { - if (render.length !== 0 && render.length !== 2) { - error( - 'forwardRef render functions accept exactly two parameters: props and ref. %s', - render.length === 1 - ? 'Did you forget to use the ref parameter?' - : 'Any additional parameter will be undefined.' - ) - } - } - - if (render != null) { - if (render.defaultProps != null || render.propTypes != null) { - error( - 'forwardRef render functions do not support propTypes or defaultProps. ' + - 'Did you accidentally pass a React component?' - ) - } - } - } - - var elementType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render: render, - } - - { - var ownName - Object.defineProperty(elementType, 'displayName', { - enumerable: false, - configurable: true, - get: function () { - return ownName - }, - set: function (name) { - ownName = name - - if (render.displayName == null) { - render.displayName = name - } - }, - }) - } - - return elementType - } - - // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. - - var enableScopeAPI = false // Experimental Create Event Handle API. - - function isValidElementType(type) { - if (typeof type === 'string' || typeof type === 'function') { - return true - } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). - - if ( - type === exports.Fragment || - type === exports.Profiler || - type === REACT_DEBUG_TRACING_MODE_TYPE || - type === exports.StrictMode || - type === exports.Suspense || - type === REACT_SUSPENSE_LIST_TYPE || - type === REACT_LEGACY_HIDDEN_TYPE || - enableScopeAPI - ) { - return true - } - - if (typeof type === 'object' && type !== null) { - if ( - type.$$typeof === REACT_LAZY_TYPE || - type.$$typeof === REACT_MEMO_TYPE || - type.$$typeof === REACT_PROVIDER_TYPE || - type.$$typeof === REACT_CONTEXT_TYPE || - type.$$typeof === REACT_FORWARD_REF_TYPE || - type.$$typeof === REACT_FUNDAMENTAL_TYPE || - type.$$typeof === REACT_BLOCK_TYPE || - type[0] === REACT_SERVER_BLOCK_TYPE - ) { - return true - } - } - - return false - } - - function memo(type, compare) { - { - if (!isValidElementType(type)) { - error( - 'memo: The first argument must be a component. Instead ' + - 'received: %s', - type === null ? 'null' : typeof type - ) - } - } - - var elementType = { - $$typeof: REACT_MEMO_TYPE, - type: type, - compare: compare === undefined ? null : compare, - } - - { - var ownName - Object.defineProperty(elementType, 'displayName', { - enumerable: false, - configurable: true, - get: function () { - return ownName - }, - set: function (name) { - ownName = name - - if (type.displayName == null) { - type.displayName = name - } - }, - }) - } - - return elementType - } - - function resolveDispatcher() { - var dispatcher = ReactCurrentDispatcher.current - - if (!(dispatcher !== null)) { - { - throw Error( - 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.' - ) - } - } - - return dispatcher - } - - function useContext(Context, unstable_observedBits) { - var dispatcher = resolveDispatcher() - - { - if (unstable_observedBits !== undefined) { - error( - 'useContext() second argument is reserved for future ' + - 'use in React. Passing it is not supported. ' + - 'You passed: %s.%s', - unstable_observedBits, - typeof unstable_observedBits === 'number' && - Array.isArray(arguments[2]) - ? '\n\nDid you call array.map(useContext)? ' + - 'Calling Hooks inside a loop is not supported. ' + - 'Learn more at https://reactjs.org/link/rules-of-hooks' - : '' - ) - } // TODO: add a more generic warning for invalid values. - - if (Context._context !== undefined) { - var realContext = Context._context // Don't deduplicate because this legitimately causes bugs - // and nobody should be using this in existing code. - - if (realContext.Consumer === Context) { - error( - 'Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + - 'removed in a future major release. Did you mean to call useContext(Context) instead?' - ) - } else if (realContext.Provider === Context) { - error( - 'Calling useContext(Context.Provider) is not supported. ' + - 'Did you mean to call useContext(Context) instead?' - ) - } - } - } - - return dispatcher.useContext(Context, unstable_observedBits) - } - function useState(initialState) { - var dispatcher = resolveDispatcher() - return dispatcher.useState(initialState) - } - function useReducer(reducer, initialArg, init) { - var dispatcher = resolveDispatcher() - return dispatcher.useReducer(reducer, initialArg, init) - } - function useRef(initialValue) { - var dispatcher = resolveDispatcher() - return dispatcher.useRef(initialValue) - } - function useEffect(create, deps) { - var dispatcher = resolveDispatcher() - return dispatcher.useEffect(create, deps) - } - function useLayoutEffect(create, deps) { - var dispatcher = resolveDispatcher() - return dispatcher.useLayoutEffect(create, deps) - } - function useCallback(callback, deps) { - var dispatcher = resolveDispatcher() - return dispatcher.useCallback(callback, deps) - } - function useMemo(create, deps) { - var dispatcher = resolveDispatcher() - return dispatcher.useMemo(create, deps) - } - function useImperativeHandle(ref, create, deps) { - var dispatcher = resolveDispatcher() - return dispatcher.useImperativeHandle(ref, create, deps) - } - function useDebugValue(value, formatterFn) { - { - var dispatcher = resolveDispatcher() - return dispatcher.useDebugValue(value, formatterFn) - } - } - - // Helpers to patch console.logs to avoid logging during side-effect free - // replaying on render function. This currently only patches the object - // lazily which won't cover if the log function was extracted eagerly. - // We could also eagerly patch the method. - var disabledDepth = 0 - var prevLog - var prevInfo - var prevWarn - var prevError - var prevGroup - var prevGroupCollapsed - var prevGroupEnd - - function disabledLog() {} - - disabledLog.__reactDisabledLog = true - function disableLogs() { - { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log - prevInfo = console.info - prevWarn = console.warn - prevError = console.error - prevGroup = console.group - prevGroupCollapsed = console.groupCollapsed - prevGroupEnd = console.groupEnd // https://github.com/facebook/react/issues/19099 - - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true, - } // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props, - }) - /* eslint-enable react-internal/no-production-logging */ - } - - disabledDepth++ - } - } - function reenableLogs() { - { - disabledDepth-- - - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true, - } // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - log: _assign({}, props, { - value: prevLog, - }), - info: _assign({}, props, { - value: prevInfo, - }), - warn: _assign({}, props, { - value: prevWarn, - }), - error: _assign({}, props, { - value: prevError, - }), - group: _assign({}, props, { - value: prevGroup, - }), - groupCollapsed: _assign({}, props, { - value: prevGroupCollapsed, - }), - groupEnd: _assign({}, props, { - value: prevGroupEnd, - }), - }) - /* eslint-enable react-internal/no-production-logging */ - } - - if (disabledDepth < 0) { - error( - 'disabledDepth fell below zero. ' + - 'This is a bug in React. Please file an issue.' - ) - } - } - } - - var ReactCurrentDispatcher$1 = - ReactSharedInternals.ReactCurrentDispatcher - var prefix - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error() - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/) - prefix = (match && match[1]) || '' - } - } // We use the prefix to ensure our stacks line up with native stack frames. - - return '\n' + prefix + name - } - } - var reentry = false - var componentFrameCache - - { - var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map - componentFrameCache = new PossiblyWeakMap() - } - - function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if (!fn || reentry) { - return '' - } - - { - var frame = componentFrameCache.get(fn) - - if (frame !== undefined) { - return frame - } - } - - var control - reentry = true - var previousPrepareStackTrace = Error.prepareStackTrace // $FlowFixMe It does accept undefined. - - Error.prepareStackTrace = undefined - var previousDispatcher - - { - previousDispatcher = ReactCurrentDispatcher$1.current // Set the dispatcher in DEV because this might be call in the render function - // for warnings. - - ReactCurrentDispatcher$1.current = null - disableLogs() - } - - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error() - } // $FlowFixMe - - Object.defineProperty(Fake.prototype, 'props', { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error() - }, - }) - - if (typeof Reflect === 'object' && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []) - } catch (x) { - control = x - } - - Reflect.construct(fn, [], Fake) - } else { - try { - Fake.call() - } catch (x) { - control = x - } - - fn.call(Fake.prototype) - } - } else { - try { - throw Error() - } catch (x) { - control = x - } - - fn() - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === 'string') { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sample.stack.split('\n') - var controlLines = control.stack.split('\n') - var s = sampleLines.length - 1 - var c = controlLines.length - 1 - - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c-- - } - - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s-- - c-- // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. - - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = - '\n' + sampleLines[s].replace(' at new ', ' at ') - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, _frame) - } - } // Return the line we found. - - return _frame - } - } while (s >= 1 && c >= 0) - } - - break - } - } - } - } finally { - reentry = false - - { - ReactCurrentDispatcher$1.current = previousDispatcher - reenableLogs() - } - - Error.prepareStackTrace = previousPrepareStackTrace - } // Fallback to just using the name if we couldn't make it throw. - - var name = fn ? fn.displayName || fn.name : '' - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '' - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, syntheticFrame) - } - } - - return syntheticFrame - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false) - } - } - - function shouldConstruct(Component) { - var prototype = Component.prototype - return !!(prototype && prototype.isReactComponent) - } - - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return '' - } - - if (typeof type === 'function') { - { - return describeNativeComponentFrame(type, shouldConstruct(type)) - } - } - - if (typeof type === 'string') { - return describeBuiltInComponentFrame(type) - } - - switch (type) { - case exports.Suspense: - return describeBuiltInComponentFrame('Suspense') - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame('SuspenseList') - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render) - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - type.type, - source, - ownerFn - ) - - case REACT_BLOCK_TYPE: - return describeFunctionComponentFrame(type._render) - - case REACT_LAZY_TYPE: { - var lazyComponent = type - var payload = lazyComponent._payload - var init = lazyComponent._init - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - source, - ownerFn - ) - } catch (x) {} - } - } - } - - return '' - } - - var loggedTypeFailures = {} - var ReactDebugCurrentFrame$1 = - ReactSharedInternals.ReactDebugCurrentFrame - - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - element._source, - owner ? owner.type : null - ) - ReactDebugCurrentFrame$1.setExtraStackFrame(stack) - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null) - } - } - } - - function checkPropTypes( - typeSpecs, - values, - location, - componentName, - element - ) { - { - // $FlowFixMe This is okay but Flow doesn't know it. - var has = Function.call.bind(Object.prototype.hasOwnProperty) - - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0 // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== 'function') { - var err = Error( - (componentName || 'React class') + - ': ' + - location + - ' type `' + - typeSpecName + - '` is invalid; ' + - 'it must be a function, usually from the `prop-types` package, but received `' + - typeof typeSpecs[typeSpecName] + - '`.' + - 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.' - ) - err.name = 'Invariant Violation' - throw err - } - - error$1 = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED' - ) - } catch (ex) { - error$1 = ex - } - - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element) - - error( - '%s: type specification of %s' + - ' `%s` is invalid; the type checker ' + - 'function must return `null` or an `Error` but returned a %s. ' + - 'You may have forgotten to pass an argument to the type checker ' + - 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + - 'shape all require an argument).', - componentName || 'React class', - location, - typeSpecName, - typeof error$1 - ) - - setCurrentlyValidatingElement(null) - } - - if ( - error$1 instanceof Error && - !(error$1.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true - setCurrentlyValidatingElement(element) - - error('Failed %s type: %s', location, error$1.message) - - setCurrentlyValidatingElement(null) - } - } - } - } - } - - function setCurrentlyValidatingElement$1(element) { - { - if (element) { - var owner = element._owner - var stack = describeUnknownElementTypeFrameInDEV( - element.type, - element._source, - owner ? owner.type : null - ) - setExtraStackFrame(stack) - } else { - setExtraStackFrame(null) - } - } - } - - var propTypesMisspellWarningShown - - { - propTypesMisspellWarningShown = false - } - - function getDeclarationErrorAddendum() { - if (ReactCurrentOwner.current) { - var name = getComponentName(ReactCurrentOwner.current.type) - - if (name) { - return '\n\nCheck the render method of `' + name + '`.' - } - } - - return '' - } - - function getSourceInfoErrorAddendum(source) { - if (source !== undefined) { - var fileName = source.fileName.replace(/^.*[\\\/]/, '') - var lineNumber = source.lineNumber - return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.' - } - - return '' - } - - function getSourceInfoErrorAddendumForProps(elementProps) { - if (elementProps !== null && elementProps !== undefined) { - return getSourceInfoErrorAddendum(elementProps.__source) - } - - return '' - } - /** - * Warn if there's no key explicitly set on dynamic arrays of children or - * object keys are not valid. This allows us to keep track of children between - * updates. - */ - - var ownerHasKeyUseWarning = {} - - function getCurrentComponentErrorInfo(parentType) { - var info = getDeclarationErrorAddendum() - - if (!info) { - var parentName = - typeof parentType === 'string' - ? parentType - : parentType.displayName || parentType.name - - if (parentName) { - info = - '\n\nCheck the top-level render call using <' + - parentName + - '>.' - } - } - - return info - } - /** - * Warn if the element doesn't have an explicit key assigned to it. - * This element is in an array. The array could grow and shrink or be - * reordered. All children that haven't already been validated are required to - * have a "key" property assigned to it. Error statuses are cached so a warning - * will only be shown once. - * - * @internal - * @param {ReactElement} element Element that requires a key. - * @param {*} parentType element's parent's type. - */ - - function validateExplicitKey(element, parentType) { - if ( - !element._store || - element._store.validated || - element.key != null - ) { - return - } - - element._store.validated = true - var currentComponentErrorInfo = - getCurrentComponentErrorInfo(parentType) - - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return - } - - ownerHasKeyUseWarning[currentComponentErrorInfo] = true // Usually the current owner is the offender, but if it accepts children as a - // property, it may be the creator of the child that's responsible for - // assigning it a key. - - var childOwner = '' - - if ( - element && - element._owner && - element._owner !== ReactCurrentOwner.current - ) { - // Give the component that originally created this child. - childOwner = - ' It was passed a child from ' + - getComponentName(element._owner.type) + - '.' - } - - { - setCurrentlyValidatingElement$1(element) - - error( - 'Each child in a list should have a unique "key" prop.' + - '%s%s See https://reactjs.org/link/warning-keys for more information.', - currentComponentErrorInfo, - childOwner - ) - - setCurrentlyValidatingElement$1(null) - } - } - /** - * Ensure that every element either is passed in a static location, in an - * array with an explicit keys property defined, or in an object literal - * with valid key property. - * - * @internal - * @param {ReactNode} node Statically passed child of any type. - * @param {*} parentType node's parent's type. - */ - - function validateChildKeys(node, parentType) { - if (typeof node !== 'object') { - return - } - - if (Array.isArray(node)) { - for (var i = 0; i < node.length; i++) { - var child = node[i] - - if (isValidElement(child)) { - validateExplicitKey(child, parentType) - } - } - } else if (isValidElement(node)) { - // This element was passed in a valid location. - if (node._store) { - node._store.validated = true - } - } else if (node) { - var iteratorFn = getIteratorFn(node) - - if (typeof iteratorFn === 'function') { - // Entry iterators used to provide implicit keys, - // but now we print a separate warning for them later. - if (iteratorFn !== node.entries) { - var iterator = iteratorFn.call(node) - var step - - while (!(step = iterator.next()).done) { - if (isValidElement(step.value)) { - validateExplicitKey(step.value, parentType) - } - } - } - } - } - } - /** - * Given an element, validate that its props follow the propTypes definition, - * provided by the type. - * - * @param {ReactElement} element - */ - - function validatePropTypes(element) { - { - var type = element.type - - if ( - type === null || - type === undefined || - typeof type === 'string' - ) { - return - } - - var propTypes - - if (typeof type === 'function') { - propTypes = type.propTypes - } else if ( - typeof type === 'object' && - (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. - // Inner props are checked in the reconciler. - type.$$typeof === REACT_MEMO_TYPE) - ) { - propTypes = type.propTypes - } else { - return - } - - if (propTypes) { - // Intentionally inside to avoid triggering lazy initializers: - var name = getComponentName(type) - checkPropTypes(propTypes, element.props, 'prop', name, element) - } else if ( - type.PropTypes !== undefined && - !propTypesMisspellWarningShown - ) { - propTypesMisspellWarningShown = true // Intentionally inside to avoid triggering lazy initializers: - - var _name = getComponentName(type) - - error( - 'Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', - _name || 'Unknown' - ) - } - - if ( - typeof type.getDefaultProps === 'function' && - !type.getDefaultProps.isReactClassApproved - ) { - error( - 'getDefaultProps is only used on classic React.createClass ' + - 'definitions. Use a static property named `defaultProps` instead.' - ) - } - } - } - /** - * Given a fragment, validate that it can only be provided with fragment props - * @param {ReactElement} fragment - */ - - function validateFragmentProps(fragment) { - { - var keys = Object.keys(fragment.props) - - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - - if (key !== 'children' && key !== 'key') { - setCurrentlyValidatingElement$1(fragment) - - error( - 'Invalid prop `%s` supplied to `React.Fragment`. ' + - 'React.Fragment can only have `key` and `children` props.', - key - ) - - setCurrentlyValidatingElement$1(null) - break - } - } - - if (fragment.ref !== null) { - setCurrentlyValidatingElement$1(fragment) - - error('Invalid attribute `ref` supplied to `React.Fragment`.') - - setCurrentlyValidatingElement$1(null) - } - } - } - function createElementWithValidation(type, props, children) { - var validType = isValidElementType(type) // We warn in this case but don't throw. We expect the element creation to - // succeed and there will likely be errors in render. - - if (!validType) { - var info = '' - - if ( - type === undefined || - (typeof type === 'object' && - type !== null && - Object.keys(type).length === 0) - ) { - info += - ' You likely forgot to export your component from the file ' + - "it's defined in, or you might have mixed up default and named imports." - } - - var sourceInfo = getSourceInfoErrorAddendumForProps(props) - - if (sourceInfo) { - info += sourceInfo - } else { - info += getDeclarationErrorAddendum() - } - - var typeString - - if (type === null) { - typeString = 'null' - } else if (Array.isArray(type)) { - typeString = 'array' - } else if ( - type !== undefined && - type.$$typeof === REACT_ELEMENT_TYPE - ) { - typeString = - '<' + (getComponentName(type.type) || 'Unknown') + ' />' - info = - ' Did you accidentally export a JSX literal instead of a component?' - } else { - typeString = typeof type - } - - { - error( - 'React.createElement: type is invalid -- expected a string (for ' + - 'built-in components) or a class/function (for composite ' + - 'components) but got: %s.%s', - typeString, - info - ) - } - } - - var element = createElement.apply(this, arguments) // The result can be nullish if a mock or a custom function is used. - // TODO: Drop this when these are no longer allowed as the type argument. - - if (element == null) { - return element - } // Skip key warning if the type isn't valid since our key validation logic - // doesn't expect a non-string/function type and can throw confusing errors. - // We don't want exception behavior to differ between dev and prod. - // (Rendering will throw with a helpful message and as soon as the type is - // fixed, the key warnings will appear.) - - if (validType) { - for (var i = 2; i < arguments.length; i++) { - validateChildKeys(arguments[i], type) - } - } - - if (type === exports.Fragment) { - validateFragmentProps(element) - } else { - validatePropTypes(element) - } - - return element - } - var didWarnAboutDeprecatedCreateFactory = false - function createFactoryWithValidation(type) { - var validatedFactory = createElementWithValidation.bind(null, type) - validatedFactory.type = type - - { - if (!didWarnAboutDeprecatedCreateFactory) { - didWarnAboutDeprecatedCreateFactory = true - - warn( - 'React.createFactory() is deprecated and will be removed in ' + - 'a future major release. Consider using JSX ' + - 'or use React.createElement() directly instead.' - ) - } // Legacy hook: remove it - - Object.defineProperty(validatedFactory, 'type', { - enumerable: false, - get: function () { - warn( - 'Factory.type is deprecated. Access the class directly ' + - 'before passing it to createFactory.' - ) - - Object.defineProperty(this, 'type', { - value: type, - }) - return type - }, - }) - } - - return validatedFactory - } - function cloneElementWithValidation(element, props, children) { - var newElement = cloneElement.apply(this, arguments) - - for (var i = 2; i < arguments.length; i++) { - validateChildKeys(arguments[i], newElement.type) - } - - validatePropTypes(newElement) - return newElement - } - - { - try { - var frozenObject = Object.freeze({}) - /* eslint-disable no-new */ - - new Map([[frozenObject, null]]) - new Set([frozenObject]) - /* eslint-enable no-new */ - } catch (e) {} - } - - var createElement$1 = createElementWithValidation - var cloneElement$1 = cloneElementWithValidation - var createFactory = createFactoryWithValidation - var Children = { - map: mapChildren, - forEach: forEachChildren, - count: countChildren, - toArray: toArray, - only: onlyChild, - } - - exports.Children = Children - exports.Component = Component - exports.PureComponent = PureComponent - exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = - ReactSharedInternals - exports.cloneElement = cloneElement$1 - exports.createContext = createContext - exports.createElement = createElement$1 - exports.createFactory = createFactory - exports.createRef = createRef - exports.forwardRef = forwardRef - exports.isValidElement = isValidElement - exports.lazy = lazy - exports.memo = memo - exports.useCallback = useCallback - exports.useContext = useContext - exports.useDebugValue = useDebugValue - exports.useEffect = useEffect - exports.useImperativeHandle = useImperativeHandle - exports.useLayoutEffect = useLayoutEffect - exports.useMemo = useMemo - exports.useReducer = useReducer - exports.useRef = useRef - exports.useState = useState - exports.version = ReactVersion - })() - } - })(react_development) - - ;(function (module) { - { - module.exports = react_development - } - })(react) - - var React = /*@__PURE__*/ getDefaultExportFromCjs(react.exports) - - function _extends$2() { - _extends$2 = - Object.assign || - function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target - } - - return _extends$2.apply(this, arguments) - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {} - var target = {} - var sourceKeys = Object.keys(source) - var key, i - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i] - if (excluded.indexOf(key) >= 0) continue - target[key] = source[key] - } - - return target - } - - /** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - var invariant = function (condition, format, a, b, c, d, e, f) { - { - if (format === undefined) { - throw new Error('invariant requires an error message argument') - } - } - - if (!condition) { - var error - if (format === undefined) { - error = new Error( - 'Minified exception occurred; use the non-minified dev environment ' + - 'for the full error message and additional helpful warnings.' - ) - } else { - var args = [a, b, c, d, e, f] - var argIndex = 0 - error = new Error( - format.replace(/%s/g, function () { - return args[argIndex++] - }) - ) - error.name = 'Invariant Violation' - } - - error.framesToPop = 1 // we don't care about invariant's own frame - throw error - } - } - - var invariant_1 = invariant - - var noop$3 = function noop() {} - - function readOnlyPropType(handler, name) { - return function (props, propName) { - if (props[propName] !== undefined) { - if (!props[handler]) { - return new Error( - 'You have provided a `' + - propName + - '` prop to `' + - name + - '` ' + - ('without an `' + - handler + - '` handler prop. This will render a read-only field. ') + - ('If the field should be mutable use `' + - defaultKey(propName) + - '`. ') + - ('Otherwise, set `' + handler + '`.') - ) - } - } - } - } - - function uncontrolledPropTypes(controlledValues, displayName) { - var propTypes = {} - Object.keys(controlledValues).forEach(function (prop) { - // add default propTypes for folks that use runtime checks - propTypes[defaultKey(prop)] = noop$3 - - { - var handler = controlledValues[prop] - !(typeof handler === 'string' && handler.trim().length) - ? invariant_1( - false, - 'Uncontrollable - [%s]: the prop `%s` needs a valid handler key name in order to make it uncontrollable', - displayName, - prop - ) - : void 0 - propTypes[prop] = readOnlyPropType(handler, displayName) - } - }) - return propTypes - } - function isProp(props, prop) { - return props[prop] !== undefined - } - function defaultKey(key) { - return 'default' + key.charAt(0).toUpperCase() + key.substr(1) - } - /** - * Copyright (c) 2013-present, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. - */ - - function canAcceptRef(component) { - return ( - !!component && - (typeof component !== 'function' || - (component.prototype && component.prototype.isReactComponent)) - ) - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = - Object.setPrototypeOf || - function _setPrototypeOf(o, p) { - o.__proto__ = p - return o - } - - return _setPrototypeOf(o, p) - } - - function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype) - subClass.prototype.constructor = subClass - _setPrototypeOf(subClass, superClass) - } - - /** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - function componentWillMount() { - // Call this.constructor.gDSFP to support sub-classes. - var state = this.constructor.getDerivedStateFromProps( - this.props, - this.state - ) - if (state !== null && state !== undefined) { - this.setState(state) - } - } - - function componentWillReceiveProps(nextProps) { - // Call this.constructor.gDSFP to support sub-classes. - // Use the setState() updater to ensure state isn't stale in certain edge cases. - function updater(prevState) { - var state = this.constructor.getDerivedStateFromProps( - nextProps, - prevState - ) - return state !== null && state !== undefined ? state : null - } - // Binding "this" is important for shallow renderer support. - this.setState(updater.bind(this)) - } - - function componentWillUpdate(nextProps, nextState) { - try { - var prevProps = this.props - var prevState = this.state - this.props = nextProps - this.state = nextState - this.__reactInternalSnapshotFlag = true - this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate( - prevProps, - prevState - ) - } finally { - this.props = prevProps - this.state = prevState - } - } - - // React may warn about cWM/cWRP/cWU methods being deprecated. - // Add a flag to suppress these warnings for this special case. - componentWillMount.__suppressDeprecationWarning = true - componentWillReceiveProps.__suppressDeprecationWarning = true - componentWillUpdate.__suppressDeprecationWarning = true - - function polyfill(Component) { - var prototype = Component.prototype - - if (!prototype || !prototype.isReactComponent) { - throw new Error('Can only polyfill class components') - } - - if ( - typeof Component.getDerivedStateFromProps !== 'function' && - typeof prototype.getSnapshotBeforeUpdate !== 'function' - ) { - return Component - } - - // If new component APIs are defined, "unsafe" lifecycles won't be called. - // Error if any of these lifecycles are present, - // Because they would work differently between older and newer (16.3+) versions of React. - var foundWillMountName = null - var foundWillReceivePropsName = null - var foundWillUpdateName = null - if (typeof prototype.componentWillMount === 'function') { - foundWillMountName = 'componentWillMount' - } else if (typeof prototype.UNSAFE_componentWillMount === 'function') { - foundWillMountName = 'UNSAFE_componentWillMount' - } - if (typeof prototype.componentWillReceiveProps === 'function') { - foundWillReceivePropsName = 'componentWillReceiveProps' - } else if ( - typeof prototype.UNSAFE_componentWillReceiveProps === 'function' - ) { - foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps' - } - if (typeof prototype.componentWillUpdate === 'function') { - foundWillUpdateName = 'componentWillUpdate' - } else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') { - foundWillUpdateName = 'UNSAFE_componentWillUpdate' - } - if ( - foundWillMountName !== null || - foundWillReceivePropsName !== null || - foundWillUpdateName !== null - ) { - var componentName = Component.displayName || Component.name - var newApiName = - typeof Component.getDerivedStateFromProps === 'function' - ? 'getDerivedStateFromProps()' - : 'getSnapshotBeforeUpdate()' - - throw Error( - 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + - componentName + - ' uses ' + - newApiName + - ' but also contains the following legacy lifecycles:' + - (foundWillMountName !== null ? '\n ' + foundWillMountName : '') + - (foundWillReceivePropsName !== null - ? '\n ' + foundWillReceivePropsName - : '') + - (foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '') + - '\n\nThe above lifecycles should be removed. Learn more about this warning here:\n' + - 'https://fb.me/react-async-component-lifecycle-hooks' - ) - } - - // React <= 16.2 does not support static getDerivedStateFromProps. - // As a workaround, use cWM and cWRP to invoke the new static lifecycle. - // Newer versions of React will ignore these lifecycles if gDSFP exists. - if (typeof Component.getDerivedStateFromProps === 'function') { - prototype.componentWillMount = componentWillMount - prototype.componentWillReceiveProps = componentWillReceiveProps - } - - // React <= 16.2 does not support getSnapshotBeforeUpdate. - // As a workaround, use cWU to invoke the new lifecycle. - // Newer versions of React will ignore that lifecycle if gSBU exists. - if (typeof prototype.getSnapshotBeforeUpdate === 'function') { - if (typeof prototype.componentDidUpdate !== 'function') { - throw new Error( - 'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype' - ) - } - - prototype.componentWillUpdate = componentWillUpdate - - var componentDidUpdate = prototype.componentDidUpdate - - prototype.componentDidUpdate = function componentDidUpdatePolyfill( - prevProps, - prevState, - maybeSnapshot - ) { - // 16.3+ will not execute our will-update method; - // It will pass a snapshot value to did-update though. - // Older versions will require our polyfilled will-update value. - // We need to handle both cases, but can't just check for the presence of "maybeSnapshot", - // Because for <= 15.x versions this might be a "prevContext" object. - // We also can't just check "__reactInternalSnapshot", - // Because get-snapshot might return a falsy value. - // So check for the explicit __reactInternalSnapshotFlag flag to determine behavior. - var snapshot = this.__reactInternalSnapshotFlag - ? this.__reactInternalSnapshot - : maybeSnapshot - - componentDidUpdate.call(this, prevProps, prevState, snapshot) - } - } - - return Component - } - - var _jsxFileName = '/Users/jquense/src/uncontrollable/src/uncontrollable.js' - function uncontrollable(Component, controlledValues, methods) { - if (methods === void 0) { - methods = [] - } - - var displayName = Component.displayName || Component.name || 'Component' - var canAcceptRef$1 = canAcceptRef(Component) - var controlledProps = Object.keys(controlledValues) - var PROPS_TO_OMIT = controlledProps.map(defaultKey) - !(canAcceptRef$1 || !methods.length) - ? invariant_1( - false, - '[uncontrollable] stateless function components cannot pass through methods ' + - 'because they have no associated instances. Check component: ' + - displayName + - ', ' + - 'attempting to pass through methods: ' + - methods.join(', ') - ) - : void 0 - - var UncontrolledComponent = - /*#__PURE__*/ - (function (_React$Component) { - _inheritsLoose(UncontrolledComponent, _React$Component) - - function UncontrolledComponent() { - var _this - - for ( - var _len = arguments.length, args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key] - } - - _this = - _React$Component.call.apply( - _React$Component, - [this].concat(args) - ) || this - _this.handlers = Object.create(null) - controlledProps.forEach(function (propName) { - var handlerName = controlledValues[propName] - - var handleChange = function handleChange(value) { - if (_this.props[handlerName]) { - var _this$props - - _this._notifying = true - - for ( - var _len2 = arguments.length, - args = new Array(_len2 > 1 ? _len2 - 1 : 0), - _key2 = 1; - _key2 < _len2; - _key2++ - ) { - args[_key2 - 1] = arguments[_key2] - } - - ;(_this$props = _this.props)[handlerName].apply( - _this$props, - [value].concat(args) - ) - - _this._notifying = false - } - - if (!_this.unmounted) - _this.setState(function (_ref) { - var _extends2 - - var values = _ref.values - return { - values: _extends$2( - Object.create(null), - values, - ((_extends2 = {}), - (_extends2[propName] = value), - _extends2) - ), - } - }) - } - - _this.handlers[handlerName] = handleChange - }) - if (methods.length) - _this.attachRef = function (ref) { - _this.inner = ref - } - var values = Object.create(null) - controlledProps.forEach(function (key) { - values[key] = _this.props[defaultKey(key)] - }) - _this.state = { - values: values, - prevProps: {}, - } - return _this - } - - var _proto = UncontrolledComponent.prototype - - _proto.shouldComponentUpdate = function shouldComponentUpdate() { - //let setState trigger the update - return !this._notifying - } - - UncontrolledComponent.getDerivedStateFromProps = - function getDerivedStateFromProps(props, _ref2) { - var values = _ref2.values, - prevProps = _ref2.prevProps - var nextState = { - values: _extends$2(Object.create(null), values), - prevProps: {}, - } - controlledProps.forEach(function (key) { - /** - * If a prop switches from controlled to Uncontrolled - * reset its value to the defaultValue - */ - nextState.prevProps[key] = props[key] - - if (!isProp(props, key) && isProp(prevProps, key)) { - nextState.values[key] = props[defaultKey(key)] - } - }) - return nextState - } - - _proto.componentWillUnmount = function componentWillUnmount() { - this.unmounted = true - } - - _proto.render = function render() { - var _this2 = this - - var _this$props2 = this.props, - innerRef = _this$props2.innerRef, - props = _objectWithoutPropertiesLoose(_this$props2, ['innerRef']) - - PROPS_TO_OMIT.forEach(function (prop) { - delete props[prop] - }) - var newProps = {} - controlledProps.forEach(function (propName) { - var propValue = _this2.props[propName] - newProps[propName] = - propValue !== undefined - ? propValue - : _this2.state.values[propName] - }) - return React.createElement( - Component, - _extends$2({}, props, newProps, this.handlers, { - ref: innerRef || this.attachRef, - }) - ) - } - - return UncontrolledComponent - })(React.Component) - - polyfill(UncontrolledComponent) - UncontrolledComponent.displayName = 'Uncontrolled(' + displayName + ')' - UncontrolledComponent.propTypes = _extends$2( - { - innerRef: function innerRef() {}, - }, - uncontrolledPropTypes(controlledValues, displayName) - ) - methods.forEach(function (method) { - UncontrolledComponent.prototype[method] = function $proxiedMethod() { - var _this$inner - - return (_this$inner = this.inner)[method].apply(_this$inner, arguments) - } - }) - var WrappedComponent = UncontrolledComponent - - if (React.forwardRef) { - WrappedComponent = React.forwardRef(function (props, ref) { - return React.createElement( - UncontrolledComponent, - _extends$2({}, props, { - innerRef: ref, - __source: { - fileName: _jsxFileName, - lineNumber: 128, - }, - __self: this, - }) - ) - }) - WrappedComponent.propTypes = UncontrolledComponent.propTypes - } - - WrappedComponent.ControlledComponent = Component - /** - * useful when wrapping a Component and you want to control - * everything - */ - - WrappedComponent.deferControlTo = function ( - newComponent, - additions, - nextMethods - ) { - if (additions === void 0) { - additions = {} - } - - return uncontrollable( - newComponent, - _extends$2({}, controlledValues, additions), - nextMethods - ) - } - - return WrappedComponent - } - - function r(e) { - var t, - f, - n = '' - if ('string' == typeof e || 'number' == typeof e) n += e - else if ('object' == typeof e) - if (Array.isArray(e)) - for (t = 0; t < e.length; t++) - e[t] && (f = r(e[t])) && (n && (n += ' '), (n += f)) - else for (t in e) e[t] && (n && (n += ' '), (n += t)) - return n - } - function clsx() { - for (var e, t, f = 0, n = ''; f < arguments.length; ) - (e = arguments[f++]) && (t = r(e)) && (n && (n += ' '), (n += t)) - return n - } - - var propTypes$3 = { exports: {} } - - var reactIs = { exports: {} } - - var reactIs_development = {} - - /** @license React v16.13.1 - * react-is.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - { - ;(function () { - // The Symbol used to tag the ReactElement-like types. If there is no native Symbol - // nor polyfill, then a plain number is used for performance. - var hasSymbol = typeof Symbol === 'function' && Symbol.for - var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7 - var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca - var REACT_FRAGMENT_TYPE = hasSymbol - ? Symbol.for('react.fragment') - : 0xeacb - var REACT_STRICT_MODE_TYPE = hasSymbol - ? Symbol.for('react.strict_mode') - : 0xeacc - var REACT_PROFILER_TYPE = hasSymbol - ? Symbol.for('react.profiler') - : 0xead2 - var REACT_PROVIDER_TYPE = hasSymbol - ? Symbol.for('react.provider') - : 0xeacd - var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary - // (unstable) APIs that have been removed. Can we remove the symbols? - - var REACT_ASYNC_MODE_TYPE = hasSymbol - ? Symbol.for('react.async_mode') - : 0xeacf - var REACT_CONCURRENT_MODE_TYPE = hasSymbol - ? Symbol.for('react.concurrent_mode') - : 0xeacf - var REACT_FORWARD_REF_TYPE = hasSymbol - ? Symbol.for('react.forward_ref') - : 0xead0 - var REACT_SUSPENSE_TYPE = hasSymbol - ? Symbol.for('react.suspense') - : 0xead1 - var REACT_SUSPENSE_LIST_TYPE = hasSymbol - ? Symbol.for('react.suspense_list') - : 0xead8 - var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3 - var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4 - var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9 - var REACT_FUNDAMENTAL_TYPE = hasSymbol - ? Symbol.for('react.fundamental') - : 0xead5 - var REACT_RESPONDER_TYPE = hasSymbol - ? Symbol.for('react.responder') - : 0xead6 - var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7 - - function isValidElementType(type) { - return ( - typeof type === 'string' || - typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. - type === REACT_FRAGMENT_TYPE || - type === REACT_CONCURRENT_MODE_TYPE || - type === REACT_PROFILER_TYPE || - type === REACT_STRICT_MODE_TYPE || - type === REACT_SUSPENSE_TYPE || - type === REACT_SUSPENSE_LIST_TYPE || - (typeof type === 'object' && - type !== null && - (type.$$typeof === REACT_LAZY_TYPE || - type.$$typeof === REACT_MEMO_TYPE || - type.$$typeof === REACT_PROVIDER_TYPE || - type.$$typeof === REACT_CONTEXT_TYPE || - type.$$typeof === REACT_FORWARD_REF_TYPE || - type.$$typeof === REACT_FUNDAMENTAL_TYPE || - type.$$typeof === REACT_RESPONDER_TYPE || - type.$$typeof === REACT_SCOPE_TYPE || - type.$$typeof === REACT_BLOCK_TYPE)) - ) - } - - function typeOf(object) { - if (typeof object === 'object' && object !== null) { - var $$typeof = object.$$typeof - - switch ($$typeof) { - case REACT_ELEMENT_TYPE: - var type = object.type - - switch (type) { - case REACT_ASYNC_MODE_TYPE: - case REACT_CONCURRENT_MODE_TYPE: - case REACT_FRAGMENT_TYPE: - case REACT_PROFILER_TYPE: - case REACT_STRICT_MODE_TYPE: - case REACT_SUSPENSE_TYPE: - return type - - default: - var $$typeofType = type && type.$$typeof - - switch ($$typeofType) { - case REACT_CONTEXT_TYPE: - case REACT_FORWARD_REF_TYPE: - case REACT_LAZY_TYPE: - case REACT_MEMO_TYPE: - case REACT_PROVIDER_TYPE: - return $$typeofType - - default: - return $$typeof - } - } - - case REACT_PORTAL_TYPE: - return $$typeof - } - } - - return undefined - } // AsyncMode is deprecated along with isAsyncMode - - var AsyncMode = REACT_ASYNC_MODE_TYPE - var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE - var ContextConsumer = REACT_CONTEXT_TYPE - var ContextProvider = REACT_PROVIDER_TYPE - var Element = REACT_ELEMENT_TYPE - var ForwardRef = REACT_FORWARD_REF_TYPE - var Fragment = REACT_FRAGMENT_TYPE - var Lazy = REACT_LAZY_TYPE - var Memo = REACT_MEMO_TYPE - var Portal = REACT_PORTAL_TYPE - var Profiler = REACT_PROFILER_TYPE - var StrictMode = REACT_STRICT_MODE_TYPE - var Suspense = REACT_SUSPENSE_TYPE - var hasWarnedAboutDeprecatedIsAsyncMode = false // AsyncMode should be deprecated - - function isAsyncMode(object) { - { - if (!hasWarnedAboutDeprecatedIsAsyncMode) { - hasWarnedAboutDeprecatedIsAsyncMode = true // Using console['warn'] to evade Babel and ESLint - - console['warn']( - 'The ReactIs.isAsyncMode() alias has been deprecated, ' + - 'and will be removed in React 17+. Update your code to use ' + - 'ReactIs.isConcurrentMode() instead. It has the exact same API.' - ) - } - } - - return ( - isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE - ) - } - function isConcurrentMode(object) { - return typeOf(object) === REACT_CONCURRENT_MODE_TYPE - } - function isContextConsumer(object) { - return typeOf(object) === REACT_CONTEXT_TYPE - } - function isContextProvider(object) { - return typeOf(object) === REACT_PROVIDER_TYPE - } - function isElement(object) { - return ( - typeof object === 'object' && - object !== null && - object.$$typeof === REACT_ELEMENT_TYPE - ) - } - function isForwardRef(object) { - return typeOf(object) === REACT_FORWARD_REF_TYPE - } - function isFragment(object) { - return typeOf(object) === REACT_FRAGMENT_TYPE - } - function isLazy(object) { - return typeOf(object) === REACT_LAZY_TYPE - } - function isMemo(object) { - return typeOf(object) === REACT_MEMO_TYPE - } - function isPortal(object) { - return typeOf(object) === REACT_PORTAL_TYPE - } - function isProfiler(object) { - return typeOf(object) === REACT_PROFILER_TYPE - } - function isStrictMode(object) { - return typeOf(object) === REACT_STRICT_MODE_TYPE - } - function isSuspense(object) { - return typeOf(object) === REACT_SUSPENSE_TYPE - } - - reactIs_development.AsyncMode = AsyncMode - reactIs_development.ConcurrentMode = ConcurrentMode - reactIs_development.ContextConsumer = ContextConsumer - reactIs_development.ContextProvider = ContextProvider - reactIs_development.Element = Element - reactIs_development.ForwardRef = ForwardRef - reactIs_development.Fragment = Fragment - reactIs_development.Lazy = Lazy - reactIs_development.Memo = Memo - reactIs_development.Portal = Portal - reactIs_development.Profiler = Profiler - reactIs_development.StrictMode = StrictMode - reactIs_development.Suspense = Suspense - reactIs_development.isAsyncMode = isAsyncMode - reactIs_development.isConcurrentMode = isConcurrentMode - reactIs_development.isContextConsumer = isContextConsumer - reactIs_development.isContextProvider = isContextProvider - reactIs_development.isElement = isElement - reactIs_development.isForwardRef = isForwardRef - reactIs_development.isFragment = isFragment - reactIs_development.isLazy = isLazy - reactIs_development.isMemo = isMemo - reactIs_development.isPortal = isPortal - reactIs_development.isProfiler = isProfiler - reactIs_development.isStrictMode = isStrictMode - reactIs_development.isSuspense = isSuspense - reactIs_development.isValidElementType = isValidElementType - reactIs_development.typeOf = typeOf - })() - } - - ;(function (module) { - { - module.exports = reactIs_development - } - })(reactIs) - - /** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - var ReactPropTypesSecret$2 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED' - - var ReactPropTypesSecret_1 = ReactPropTypesSecret$2 - - var has$2 = Function.call.bind(Object.prototype.hasOwnProperty) - - /** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - var printWarning$2 = function () {} - - { - var ReactPropTypesSecret$1 = ReactPropTypesSecret_1 - var loggedTypeFailures = {} - var has$1 = has$2 - - printWarning$2 = function (text) { - var message = 'Warning: ' + text - if (typeof console !== 'undefined') { - console.error(message) - } - try { - // --- Welcome to debugging React --- - // This error was thrown as a convenience so that you can use this stack - // to find the callsite that caused this warning to fire. - throw new Error(message) - } catch (x) { - /**/ - } - } - } - - /** - * Assert that the values match with the type specs. - * Error messages are memorized and will only be shown once. - * - * @param {object} typeSpecs Map of name to a ReactPropType - * @param {object} values Runtime values that need to be type-checked - * @param {string} location e.g. "prop", "context", "child context" - * @param {string} componentName Name of the component for error messages. - * @param {?Function} getStack Returns the component stack. - * @private - */ - function checkPropTypes$1( - typeSpecs, - values, - location, - componentName, - getStack - ) { - { - for (var typeSpecName in typeSpecs) { - if (has$1(typeSpecs, typeSpecName)) { - var error - // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== 'function') { - var err = Error( - (componentName || 'React class') + - ': ' + - location + - ' type `' + - typeSpecName + - '` is invalid; ' + - 'it must be a function, usually from the `prop-types` package, but received `' + - typeof typeSpecs[typeSpecName] + - '`.' + - 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.' - ) - err.name = 'Invariant Violation' - throw err - } - error = typeSpecs[typeSpecName]( - values, - typeSpecName, - componentName, - location, - null, - ReactPropTypesSecret$1 - ) - } catch (ex) { - error = ex - } - if (error && !(error instanceof Error)) { - printWarning$2( - (componentName || 'React class') + - ': type specification of ' + - location + - ' `' + - typeSpecName + - '` is invalid; the type checker ' + - 'function must return `null` or an `Error` but returned a ' + - typeof error + - '. ' + - 'You may have forgotten to pass an argument to the type checker ' + - 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + - 'shape all require an argument).' - ) - } - if ( - error instanceof Error && - !(error.message in loggedTypeFailures) - ) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error.message] = true - - var stack = getStack ? getStack() : '' - - printWarning$2( - 'Failed ' + - location + - ' type: ' + - error.message + - (stack != null ? stack : '') - ) - } - } - } - } - } - - /** - * Resets warning cache when testing. - * - * @private - */ - checkPropTypes$1.resetWarningCache = function () { - { - loggedTypeFailures = {} - } - } - - var checkPropTypes_1 = checkPropTypes$1 - - /** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - var ReactIs$1 = reactIs.exports - var assign = objectAssign - - var ReactPropTypesSecret = ReactPropTypesSecret_1 - var has = has$2 - var checkPropTypes = checkPropTypes_1 - - var printWarning$1 = function () {} - - { - printWarning$1 = function (text) { - var message = 'Warning: ' + text - if (typeof console !== 'undefined') { - console.error(message) - } - try { - // --- Welcome to debugging React --- - // This error was thrown as a convenience so that you can use this stack - // to find the callsite that caused this warning to fire. - throw new Error(message) - } catch (x) {} - } - } - - function emptyFunctionThatReturnsNull() { - return null - } - - var factoryWithTypeCheckers = function (isValidElement, throwOnDirectAccess) { - /* global Symbol */ - var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator - var FAUX_ITERATOR_SYMBOL = '@@iterator' // Before Symbol spec. - - /** - * Returns the iterator method function contained on the iterable object. - * - * Be sure to invoke the function with the iterable as context: - * - * var iteratorFn = getIteratorFn(myIterable); - * if (iteratorFn) { - * var iterator = iteratorFn.call(myIterable); - * ... - * } - * - * @param {?object} maybeIterable - * @return {?function} - */ - function getIteratorFn(maybeIterable) { - var iteratorFn = - maybeIterable && - ((ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL]) || - maybeIterable[FAUX_ITERATOR_SYMBOL]) - if (typeof iteratorFn === 'function') { - return iteratorFn - } - } - - /** - * Collection of methods that allow declaration and validation of props that are - * supplied to React components. Example usage: - * - * var Props = require('ReactPropTypes'); - * var MyArticle = React.createClass({ - * propTypes: { - * // An optional string prop named "description". - * description: Props.string, - * - * // A required enum prop named "category". - * category: Props.oneOf(['News','Photos']).isRequired, - * - * // A prop named "dialog" that requires an instance of Dialog. - * dialog: Props.instanceOf(Dialog).isRequired - * }, - * render: function() { ... } - * }); - * - * A more formal specification of how these methods are used: - * - * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) - * decl := ReactPropTypes.{type}(.isRequired)? - * - * Each and every declaration produces a function with the same signature. This - * allows the creation of custom validation functions. For example: - * - * var MyLink = React.createClass({ - * propTypes: { - * // An optional string or URI prop named "href". - * href: function(props, propName, componentName) { - * var propValue = props[propName]; - * if (propValue != null && typeof propValue !== 'string' && - * !(propValue instanceof URI)) { - * return new Error( - * 'Expected a string or an URI for ' + propName + ' in ' + - * componentName - * ); - * } - * } - * }, - * render: function() {...} - * }); - * - * @internal - */ - - var ANONYMOUS = '<>' - - // Important! - // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. - var ReactPropTypes = { - array: createPrimitiveTypeChecker('array'), - bigint: createPrimitiveTypeChecker('bigint'), - bool: createPrimitiveTypeChecker('boolean'), - func: createPrimitiveTypeChecker('function'), - number: createPrimitiveTypeChecker('number'), - object: createPrimitiveTypeChecker('object'), - string: createPrimitiveTypeChecker('string'), - symbol: createPrimitiveTypeChecker('symbol'), - - any: createAnyTypeChecker(), - arrayOf: createArrayOfTypeChecker, - element: createElementTypeChecker(), - elementType: createElementTypeTypeChecker(), - instanceOf: createInstanceTypeChecker, - node: createNodeChecker(), - objectOf: createObjectOfTypeChecker, - oneOf: createEnumTypeChecker, - oneOfType: createUnionTypeChecker, - shape: createShapeTypeChecker, - exact: createStrictShapeTypeChecker, - } - - /** - * inlined Object.is polyfill to avoid requiring consumers ship their own - * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is - */ - /*eslint-disable no-self-compare*/ - function is(x, y) { - // SameValue algorithm - if (x === y) { - // Steps 1-5, 7-10 - // Steps 6.b-6.e: +0 != -0 - return x !== 0 || 1 / x === 1 / y - } else { - // Step 6.a: NaN == NaN - return x !== x && y !== y - } - } - /*eslint-enable no-self-compare*/ - - /** - * We use an Error-like object for backward compatibility as people may call - * PropTypes directly and inspect their output. However, we don't use real - * Errors anymore. We don't inspect their stack anyway, and creating them - * is prohibitively expensive if they are created too often, such as what - * happens in oneOfType() for any type before the one that matched. - */ - function PropTypeError(message, data) { - this.message = message - this.data = data && typeof data === 'object' ? data : {} - this.stack = '' - } - // Make `instanceof Error` still work for returned errors. - PropTypeError.prototype = Error.prototype - - function createChainableTypeChecker(validate) { - { - var manualPropTypeCallCache = {} - var manualPropTypeWarningCount = 0 - } - function checkType( - isRequired, - props, - propName, - componentName, - location, - propFullName, - secret - ) { - componentName = componentName || ANONYMOUS - propFullName = propFullName || propName - - if (secret !== ReactPropTypesSecret) { - if (throwOnDirectAccess) { - // New behavior only for users of `prop-types` package - var err = new Error( - 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + - 'Use `PropTypes.checkPropTypes()` to call them. ' + - 'Read more at http://fb.me/use-check-prop-types' - ) - err.name = 'Invariant Violation' - throw err - } else if (typeof console !== 'undefined') { - // Old behavior for people using React.PropTypes - var cacheKey = componentName + ':' + propName - if ( - !manualPropTypeCallCache[cacheKey] && - // Avoid spamming the console because they are often not actionable except for lib authors - manualPropTypeWarningCount < 3 - ) { - printWarning$1( - 'You are manually calling a React.PropTypes validation ' + - 'function for the `' + - propFullName + - '` prop on `' + - componentName + - '`. This is deprecated ' + - 'and will throw in the standalone `prop-types` package. ' + - 'You may be seeing this warning due to a third-party PropTypes ' + - 'library. See https://fb.me/react-warning-dont-call-proptypes ' + - 'for details.' - ) - manualPropTypeCallCache[cacheKey] = true - manualPropTypeWarningCount++ - } - } - } - if (props[propName] == null) { - if (isRequired) { - if (props[propName] === null) { - return new PropTypeError( - 'The ' + - location + - ' `' + - propFullName + - '` is marked as required ' + - ('in `' + componentName + '`, but its value is `null`.') - ) - } - return new PropTypeError( - 'The ' + - location + - ' `' + - propFullName + - '` is marked as required in ' + - ('`' + componentName + '`, but its value is `undefined`.') - ) - } - return null - } else { - return validate( - props, - propName, - componentName, - location, - propFullName - ) - } - } - - var chainedCheckType = checkType.bind(null, false) - chainedCheckType.isRequired = checkType.bind(null, true) - - return chainedCheckType - } - - function createPrimitiveTypeChecker(expectedType) { - function validate( - props, - propName, - componentName, - location, - propFullName, - secret - ) { - var propValue = props[propName] - var propType = getPropType(propValue) - if (propType !== expectedType) { - // `propValue` being instance of, say, date/regexp, pass the 'object' - // check, but we can offer a more precise error message here rather than - // 'of type `object`'. - var preciseType = getPreciseType(propValue) - - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` of type ' + - ('`' + - preciseType + - '` supplied to `' + - componentName + - '`, expected ') + - ('`' + expectedType + '`.'), - { expectedType: expectedType } - ) - } - return null - } - return createChainableTypeChecker(validate) - } - - function createAnyTypeChecker() { - return createChainableTypeChecker(emptyFunctionThatReturnsNull) - } - - function createArrayOfTypeChecker(typeChecker) { - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - if (typeof typeChecker !== 'function') { - return new PropTypeError( - 'Property `' + - propFullName + - '` of component `' + - componentName + - '` has invalid PropType notation inside arrayOf.' - ) - } - var propValue = props[propName] - if (!Array.isArray(propValue)) { - var propType = getPropType(propValue) - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` of type ' + - ('`' + - propType + - '` supplied to `' + - componentName + - '`, expected an array.') - ) - } - for (var i = 0; i < propValue.length; i++) { - var error = typeChecker( - propValue, - i, - componentName, - location, - propFullName + '[' + i + ']', - ReactPropTypesSecret - ) - if (error instanceof Error) { - return error - } - } - return null - } - return createChainableTypeChecker(validate) - } - - function createElementTypeChecker() { - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - var propValue = props[propName] - if (!isValidElement(propValue)) { - var propType = getPropType(propValue) - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` of type ' + - ('`' + - propType + - '` supplied to `' + - componentName + - '`, expected a single ReactElement.') - ) - } - return null - } - return createChainableTypeChecker(validate) - } - - function createElementTypeTypeChecker() { - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - var propValue = props[propName] - if (!ReactIs$1.isValidElementType(propValue)) { - var propType = getPropType(propValue) - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` of type ' + - ('`' + - propType + - '` supplied to `' + - componentName + - '`, expected a single ReactElement type.') - ) - } - return null - } - return createChainableTypeChecker(validate) - } - - function createInstanceTypeChecker(expectedClass) { - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - if (!(props[propName] instanceof expectedClass)) { - var expectedClassName = expectedClass.name || ANONYMOUS - var actualClassName = getClassName(props[propName]) - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` of type ' + - ('`' + - actualClassName + - '` supplied to `' + - componentName + - '`, expected ') + - ('instance of `' + expectedClassName + '`.') - ) - } - return null - } - return createChainableTypeChecker(validate) - } - - function createEnumTypeChecker(expectedValues) { - if (!Array.isArray(expectedValues)) { - { - if (arguments.length > 1) { - printWarning$1( - 'Invalid arguments supplied to oneOf, expected an array, got ' + - arguments.length + - ' arguments. ' + - 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).' - ) - } else { - printWarning$1( - 'Invalid argument supplied to oneOf, expected an array.' - ) - } - } - return emptyFunctionThatReturnsNull - } - - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - var propValue = props[propName] - for (var i = 0; i < expectedValues.length; i++) { - if (is(propValue, expectedValues[i])) { - return null - } - } - - var valuesString = JSON.stringify( - expectedValues, - function replacer(key, value) { - var type = getPreciseType(value) - if (type === 'symbol') { - return String(value) - } - return value - } - ) - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` of value `' + - String(propValue) + - '` ' + - ('supplied to `' + - componentName + - '`, expected one of ' + - valuesString + - '.') - ) - } - return createChainableTypeChecker(validate) - } - - function createObjectOfTypeChecker(typeChecker) { - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - if (typeof typeChecker !== 'function') { - return new PropTypeError( - 'Property `' + - propFullName + - '` of component `' + - componentName + - '` has invalid PropType notation inside objectOf.' - ) - } - var propValue = props[propName] - var propType = getPropType(propValue) - if (propType !== 'object') { - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` of type ' + - ('`' + - propType + - '` supplied to `' + - componentName + - '`, expected an object.') - ) - } - for (var key in propValue) { - if (has(propValue, key)) { - var error = typeChecker( - propValue, - key, - componentName, - location, - propFullName + '.' + key, - ReactPropTypesSecret - ) - if (error instanceof Error) { - return error - } - } - } - return null - } - return createChainableTypeChecker(validate) - } - - function createUnionTypeChecker(arrayOfTypeCheckers) { - if (!Array.isArray(arrayOfTypeCheckers)) { - printWarning$1( - 'Invalid argument supplied to oneOfType, expected an instance of array.' - ) - return emptyFunctionThatReturnsNull - } - - for (var i = 0; i < arrayOfTypeCheckers.length; i++) { - var checker = arrayOfTypeCheckers[i] - if (typeof checker !== 'function') { - printWarning$1( - 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + - 'received ' + - getPostfixForTypeWarning(checker) + - ' at index ' + - i + - '.' - ) - return emptyFunctionThatReturnsNull - } - } - - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - var expectedTypes = [] - for (var i = 0; i < arrayOfTypeCheckers.length; i++) { - var checker = arrayOfTypeCheckers[i] - var checkerResult = checker( - props, - propName, - componentName, - location, - propFullName, - ReactPropTypesSecret - ) - if (checkerResult == null) { - return null - } - if (checkerResult.data && has(checkerResult.data, 'expectedType')) { - expectedTypes.push(checkerResult.data.expectedType) - } - } - var expectedTypesMessage = - expectedTypes.length > 0 - ? ', expected one of type [' + expectedTypes.join(', ') + ']' - : '' - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` supplied to ' + - ('`' + componentName + '`' + expectedTypesMessage + '.') - ) - } - return createChainableTypeChecker(validate) - } - - function createNodeChecker() { - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - if (!isNode(props[propName])) { - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` supplied to ' + - ('`' + componentName + '`, expected a ReactNode.') - ) - } - return null - } - return createChainableTypeChecker(validate) - } - - function invalidValidatorError( - componentName, - location, - propFullName, - key, - type - ) { - return new PropTypeError( - (componentName || 'React class') + - ': ' + - location + - ' type `' + - propFullName + - '.' + - key + - '` is invalid; ' + - 'it must be a function, usually from the `prop-types` package, but received `' + - type + - '`.' - ) - } - - function createShapeTypeChecker(shapeTypes) { - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - var propValue = props[propName] - var propType = getPropType(propValue) - if (propType !== 'object') { - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` of type `' + - propType + - '` ' + - ('supplied to `' + componentName + '`, expected `object`.') - ) - } - for (var key in shapeTypes) { - var checker = shapeTypes[key] - if (typeof checker !== 'function') { - return invalidValidatorError( - componentName, - location, - propFullName, - key, - getPreciseType(checker) - ) - } - var error = checker( - propValue, - key, - componentName, - location, - propFullName + '.' + key, - ReactPropTypesSecret - ) - if (error) { - return error - } - } - return null - } - return createChainableTypeChecker(validate) - } - - function createStrictShapeTypeChecker(shapeTypes) { - function validate( - props, - propName, - componentName, - location, - propFullName - ) { - var propValue = props[propName] - var propType = getPropType(propValue) - if (propType !== 'object') { - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` of type `' + - propType + - '` ' + - ('supplied to `' + componentName + '`, expected `object`.') - ) - } - // We need to check all keys in case some are required but missing from props. - var allKeys = assign({}, props[propName], shapeTypes) - for (var key in allKeys) { - var checker = shapeTypes[key] - if (has(shapeTypes, key) && typeof checker !== 'function') { - return invalidValidatorError( - componentName, - location, - propFullName, - key, - getPreciseType(checker) - ) - } - if (!checker) { - return new PropTypeError( - 'Invalid ' + - location + - ' `' + - propFullName + - '` key `' + - key + - '` supplied to `' + - componentName + - '`.' + - '\nBad object: ' + - JSON.stringify(props[propName], null, ' ') + - '\nValid keys: ' + - JSON.stringify(Object.keys(shapeTypes), null, ' ') - ) - } - var error = checker( - propValue, - key, - componentName, - location, - propFullName + '.' + key, - ReactPropTypesSecret - ) - if (error) { - return error - } - } - return null - } - - return createChainableTypeChecker(validate) - } - - function isNode(propValue) { - switch (typeof propValue) { - case 'number': - case 'string': - case 'undefined': - return true - case 'boolean': - return !propValue - case 'object': - if (Array.isArray(propValue)) { - return propValue.every(isNode) - } - if (propValue === null || isValidElement(propValue)) { - return true - } - - var iteratorFn = getIteratorFn(propValue) - if (iteratorFn) { - var iterator = iteratorFn.call(propValue) - var step - if (iteratorFn !== propValue.entries) { - while (!(step = iterator.next()).done) { - if (!isNode(step.value)) { - return false - } - } - } else { - // Iterator will provide entry [k,v] tuples rather than values. - while (!(step = iterator.next()).done) { - var entry = step.value - if (entry) { - if (!isNode(entry[1])) { - return false - } - } - } - } - } else { - return false - } - - return true - default: - return false - } - } - - function isSymbol(propType, propValue) { - // Native Symbol. - if (propType === 'symbol') { - return true - } - - // falsy value can't be a Symbol - if (!propValue) { - return false - } - - // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' - if (propValue['@@toStringTag'] === 'Symbol') { - return true - } - - // Fallback for non-spec compliant Symbols which are polyfilled. - if (typeof Symbol === 'function' && propValue instanceof Symbol) { - return true - } - - return false - } - - // Equivalent of `typeof` but with special handling for array and regexp. - function getPropType(propValue) { - var propType = typeof propValue - if (Array.isArray(propValue)) { - return 'array' - } - if (propValue instanceof RegExp) { - // Old webkits (at least until Android 4.0) return 'function' rather than - // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ - // passes PropTypes.object. - return 'object' - } - if (isSymbol(propType, propValue)) { - return 'symbol' - } - return propType - } - - // This handles more types than `getPropType`. Only used for error messages. - // See `createPrimitiveTypeChecker`. - function getPreciseType(propValue) { - if (typeof propValue === 'undefined' || propValue === null) { - return '' + propValue - } - var propType = getPropType(propValue) - if (propType === 'object') { - if (propValue instanceof Date) { - return 'date' - } else if (propValue instanceof RegExp) { - return 'regexp' - } - } - return propType - } - - // Returns a string that is postfixed to a warning about an invalid type. - // For example, "undefined" or "of type array" - function getPostfixForTypeWarning(value) { - var type = getPreciseType(value) - switch (type) { - case 'array': - case 'object': - return 'an ' + type - case 'boolean': - case 'date': - case 'regexp': - return 'a ' + type - default: - return type - } - } - - // Returns class name of the object, if any. - function getClassName(propValue) { - if (!propValue.constructor || !propValue.constructor.name) { - return ANONYMOUS - } - return propValue.constructor.name - } - - ReactPropTypes.checkPropTypes = checkPropTypes - ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache - ReactPropTypes.PropTypes = ReactPropTypes - - return ReactPropTypes - } - - /** - * Copyright (c) 2013-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - { - var ReactIs = reactIs.exports - - // By explicitly using `prop-types` you are opting into new development behavior. - // http://fb.me/prop-types-in-prod - var throwOnDirectAccess = true - propTypes$3.exports = factoryWithTypeCheckers( - ReactIs.isElement, - throwOnDirectAccess - ) - } - - var navigate = { - PREVIOUS: 'PREV', - NEXT: 'NEXT', - TODAY: 'TODAY', - DATE: 'DATE', - } - var views = { - MONTH: 'month', - WEEK: 'week', - WORK_WEEK: 'work_week', - DAY: 'day', - AGENDA: 'agenda', - } - - var viewNames$1 = Object.keys(views).map(function (k) { - return views[k] - }) - propTypes$3.exports.oneOfType([ - propTypes$3.exports.string, - propTypes$3.exports.func, - ]) - propTypes$3.exports.any - propTypes$3.exports.func - /** - * accepts either an array of builtin view names: - * - * ``` - * views={['month', 'day', 'agenda']} - * ``` - * - * or an object hash of the view name and the component (or boolean for builtin) - * - * ``` - * views={{ - * month: true, - * week: false, - * workweek: WorkWeekViewComponent, - * }} - * ``` - */ - - propTypes$3.exports.oneOfType([ - propTypes$3.exports.arrayOf(propTypes$3.exports.oneOf(viewNames$1)), - propTypes$3.exports.objectOf(function (prop, key) { - var isBuiltinView = - viewNames$1.indexOf(key) !== -1 && typeof prop[key] === 'boolean' - - if (isBuiltinView) { - return null - } else { - for ( - var _len = arguments.length, - args = new Array(_len > 2 ? _len - 2 : 0), - _key = 2; - _key < _len; - _key++ - ) { - args[_key - 2] = arguments[_key] - } - - return propTypes$3.exports.elementType.apply( - propTypes$3.exports, - [prop, key].concat(args) - ) - } - }), - ]) - propTypes$3.exports.oneOfType([ - propTypes$3.exports.oneOf(['overlap', 'no-overlap']), - propTypes$3.exports.func, - ]) - - function notify(handler, args) { - handler && handler.apply(null, [].concat(args)) - } - - var MILI = 'milliseconds', - SECONDS = 'seconds', - MINUTES = 'minutes', - HOURS = 'hours', - DAY = 'day', - WEEK = 'week', - MONTH = 'month', - YEAR = 'year', - DECADE = 'decade', - CENTURY = 'century' - - var multiplierMilli = { - milliseconds: 1, - seconds: 1000, - minutes: 60 * 1000, - hours: 60 * 60 * 1000, - day: 24 * 60 * 60 * 1000, - week: 7 * 24 * 60 * 60 * 1000, - } - - var multiplierMonth = { - month: 1, - year: 12, - decade: 10 * 12, - century: 100 * 12, - } - - function daysOf(year) { - return [31, daysInFeb(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - } - - function daysInFeb(year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28 - } - - function add(d, num, unit) { - d = new Date(d) - - switch (unit) { - case MILI: - case SECONDS: - case MINUTES: - case HOURS: - case DAY: - case WEEK: - return addMillis(d, num * multiplierMilli[unit]) - case MONTH: - case YEAR: - case DECADE: - case CENTURY: - return addMonths(d, num * multiplierMonth[unit]) - } - - throw new TypeError('Invalid units: "' + unit + '"') - } - - function addMillis(d, num) { - var nextDate = new Date(+d + num) - - return solveDST(d, nextDate) - } - - function addMonths(d, num) { - var year = d.getFullYear(), - month = d.getMonth(), - day = d.getDate(), - totalMonths = year * 12 + month + num, - nextYear = Math.trunc(totalMonths / 12), - nextMonth = totalMonths % 12, - nextDay = Math.min(day, daysOf(nextYear)[nextMonth]) - - var nextDate = new Date(d) - nextDate.setFullYear(nextYear) - - // To avoid a bug when sets the Feb month - // with a date > 28 or date > 29 (leap year) - nextDate.setDate(1) - - nextDate.setMonth(nextMonth) - nextDate.setDate(nextDay) - - return nextDate - } - - function solveDST(currentDate, nextDate) { - var currentOffset = currentDate.getTimezoneOffset(), - nextOffset = nextDate.getTimezoneOffset() - - // if is DST, add the difference in minutes - // else the difference is zero - var diffMinutes = nextOffset - currentOffset - - return new Date(+nextDate + diffMinutes * multiplierMilli['minutes']) - } - - function subtract(d, num, unit) { - return add(d, -num, unit) - } - - function startOf(d, unit, firstOfWeek) { - d = new Date(d) - - switch (unit) { - case CENTURY: - case DECADE: - case YEAR: - d = month(d, 0) - case MONTH: - d = date(d, 1) - case WEEK: - case DAY: - d = hours(d, 0) - case HOURS: - d = minutes(d, 0) - case MINUTES: - d = seconds(d, 0) - case SECONDS: - d = milliseconds(d, 0) - } - - if (unit === DECADE) d = subtract(d, year(d) % 10, 'year') - - if (unit === CENTURY) d = subtract(d, year(d) % 100, 'year') - - if (unit === WEEK) d = weekday(d, 0, firstOfWeek) - - return d - } - - function endOf(d, unit, firstOfWeek) { - d = new Date(d) - d = startOf(d, unit, firstOfWeek) - switch (unit) { - case CENTURY: - case DECADE: - case YEAR: - case MONTH: - case WEEK: - d = add(d, 1, unit) - d = subtract(d, 1, DAY) - d.setHours(23, 59, 59, 999) - break - case DAY: - d.setHours(23, 59, 59, 999) - break - case HOURS: - case MINUTES: - case SECONDS: - d = add(d, 1, unit) - d = subtract(d, 1, MILI) - } - return d - } - - var eq$6 = createComparer(function (a, b) { - return a === b - }) - var neq = createComparer(function (a, b) { - return a !== b - }) - var gt = createComparer(function (a, b) { - return a > b - }) - var gte = createComparer(function (a, b) { - return a >= b - }) - var lt = createComparer(function (a, b) { - return a < b - }) - var lte = createComparer(function (a, b) { - return a <= b - }) - - function min$1() { - return new Date(Math.min.apply(Math, arguments)) - } - - function max$1() { - return new Date(Math.max.apply(Math, arguments)) - } - - function inRange$1(day, min, max, unit) { - unit = unit || 'day' - - return (!min || gte(day, min, unit)) && (!max || lte(day, max, unit)) - } - - var milliseconds = createAccessor('Milliseconds') - var seconds = createAccessor('Seconds') - var minutes = createAccessor('Minutes') - var hours = createAccessor('Hours') - var day = createAccessor('Day') - var date = createAccessor('Date') - var month = createAccessor('Month') - var year = createAccessor('FullYear') - - function weekday(d, val, firstDay) { - var w = (day(d) + 7 - (firstDay || 0)) % 7 - - return val === undefined ? w : add(d, val - w, DAY) - } - - function createAccessor(method) { - var hourLength = (function (method) { - switch (method) { - case 'Milliseconds': - return 3600000 - case 'Seconds': - return 3600 - case 'Minutes': - return 60 - case 'Hours': - return 1 - default: - return null - } - })(method) - - return function (d, val) { - if (val === undefined) return d['get' + method]() - - var dateOut = new Date(d) - dateOut['set' + method](val) - - if ( - hourLength && - dateOut['get' + method]() != val && - (method === 'Hours' || - (val >= hourLength && - dateOut.getHours() - d.getHours() < Math.floor(val / hourLength))) - ) { - //Skip DST hour, if it occurs - dateOut['set' + method](val + hourLength) - } - - return dateOut - } - } - - function createComparer(operator) { - return function (a, b, unit) { - return operator(+startOf(a, unit), +startOf(b, unit)) - } - } - - /* eslint no-fallthrough: off */ - var MILLI = { - seconds: 1000, - minutes: 1000 * 60, - hours: 1000 * 60 * 60, - day: 1000 * 60 * 60 * 24, - } - function firstVisibleDay(date, localizer) { - var firstOfMonth = startOf(date, 'month') - return startOf(firstOfMonth, 'week', localizer.startOfWeek()) - } - function lastVisibleDay(date, localizer) { - var endOfMonth = endOf(date, 'month') - return endOf(endOfMonth, 'week', localizer.startOfWeek()) - } - function visibleDays(date, localizer) { - var current = firstVisibleDay(date, localizer), - last = lastVisibleDay(date, localizer), - days = [] - - while (lte(current, last, 'day')) { - days.push(current) - current = add(current, 1, 'day') - } - - return days - } - function ceil(date, unit) { - var floor = startOf(date, unit) - return eq$6(floor, date) ? floor : add(floor, 1, unit) - } - function range$1(start, end) { - var unit = - arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'day' - var current = start, - days = [] - - while (lte(current, end, unit)) { - days.push(current) - current = add(current, 1, unit) - } - - return days - } - function merge(date, time) { - if (time == null && date == null) return null - if (time == null) time = new Date() - if (date == null) date = new Date() - date = startOf(date, 'day') - date = hours(date, hours(time)) - date = minutes(date, minutes(time)) - date = seconds(date, seconds(time)) - return milliseconds(date, milliseconds(time)) - } - function isJustDate(date) { - return ( - hours(date) === 0 && - minutes(date) === 0 && - seconds(date) === 0 && - milliseconds(date) === 0 - ) - } - function diff(dateA, dateB, unit) { - if (!unit || unit === 'milliseconds') return Math.abs(+dateA - +dateB) // the .round() handles an edge case - // with DST where the total won't be exact - // since one day in the range may be shorter/longer by an hour - - return Math.round( - Math.abs( - +startOf(dateA, unit) / MILLI[unit] - - +startOf(dateB, unit) / MILLI[unit] - ) - ) - } - - var localePropType = propTypes$3.exports.oneOfType([ - propTypes$3.exports.string, - propTypes$3.exports.func, - ]) - - function _format(localizer, formatter, value, format, culture) { - var result = - typeof format === 'function' - ? format(value, culture, localizer) - : formatter.call(localizer, value, format, culture) - invariant_1( - result == null || typeof result === 'string', - '`localizer format(..)` must return a string, null, or undefined' - ) - return result - } - /** - * This date conversion was moved out of TimeSlots.js, to - * allow for localizer override - * @param {Date} dt - The date to start from - * @param {Number} minutesFromMidnight - * @param {Number} offset - * @returns {Date} - */ - - function getSlotDate(dt, minutesFromMidnight, offset) { - return new Date( - dt.getFullYear(), - dt.getMonth(), - dt.getDate(), - 0, - minutesFromMidnight + offset, - 0, - 0 - ) - } - - function getDstOffset(start, end) { - return start.getTimezoneOffset() - end.getTimezoneOffset() - } // if the start is on a DST-changing day but *after* the moment of DST - // transition we need to add those extra minutes to our minutesFromMidnight - - function getTotalMin(start, end) { - return diff(start, end, 'minutes') + getDstOffset(start, end) - } - - function getMinutesFromMidnight(start) { - var daystart = startOf(start, 'day') - return diff(daystart, start, 'minutes') + getDstOffset(daystart, start) - } // These two are used by DateSlotMetrics - - function continuesPrior(start, first) { - return lt(start, first, 'day') - } - - function continuesAfter(start, end, last) { - var singleDayDuration = eq$6(start, end, 'minutes') - return singleDayDuration - ? gte(end, last, 'minutes') - : gt(end, last, 'minutes') - } // These two are used by eventLevels - - function sortEvents$1(_ref) { - var _ref$evtA = _ref.evtA, - aStart = _ref$evtA.start, - aEnd = _ref$evtA.end, - aAllDay = _ref$evtA.allDay, - _ref$evtB = _ref.evtB, - bStart = _ref$evtB.start, - bEnd = _ref$evtB.end, - bAllDay = _ref$evtB.allDay - var startSort = +startOf(aStart, 'day') - +startOf(bStart, 'day') - var durA = diff(aStart, ceil(aEnd, 'day'), 'day') - var durB = diff(bStart, ceil(bEnd, 'day'), 'day') - return ( - startSort || // sort by start Day first - Math.max(durB, 1) - Math.max(durA, 1) || // events spanning multiple days go first - !!bAllDay - !!aAllDay || // then allDay single day events - +aStart - +bStart || // then sort by start time - +aEnd - +bEnd // then sort by end time - ) - } - - function inEventRange(_ref2) { - var _ref2$event = _ref2.event, - start = _ref2$event.start, - end = _ref2$event.end, - _ref2$range = _ref2.range, - rangeStart = _ref2$range.start, - rangeEnd = _ref2$range.end - var eStart = startOf(start, 'day') - var startsBeforeEnd = lte(eStart, rangeEnd, 'day') // when the event is zero duration we need to handle a bit differently - - var sameMin = neq(eStart, end, 'minutes') - var endsAfterStart = sameMin - ? gt(end, rangeStart, 'minutes') - : gte(end, rangeStart, 'minutes') - return startsBeforeEnd && endsAfterStart - } // other localizers treats 'day' and 'date' equality very differently, so we - // abstract the change the 'localizer.eq(date1, date2, 'day') into this - // new method, where they can be treated correctly by the localizer overrides - - function isSameDate(date1, date2) { - return eq$6(date1, date2, 'day') - } - - function startAndEndAreDateOnly(start, end) { - return isJustDate(start) && isJustDate(end) - } - - var DateLocalizer = /*#__PURE__*/ _createClass(function DateLocalizer(spec) { - var _this = this - - _classCallCheck(this, DateLocalizer) - - invariant_1( - typeof spec.format === 'function', - 'date localizer `format(..)` must be a function' - ) - invariant_1( - typeof spec.firstOfWeek === 'function', - 'date localizer `firstOfWeek(..)` must be a function' - ) - this.propType = spec.propType || localePropType - this.formats = spec.formats - - this.format = function () { - for ( - var _len = arguments.length, args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key] - } - - return _format.apply(void 0, [_this, spec.format].concat(args)) - } // These date arithmetic methods can be overriden by the localizer - - this.startOfWeek = spec.firstOfWeek - this.merge = spec.merge || merge - this.inRange = spec.inRange || inRange$1 - this.lt = spec.lt || lt - this.lte = spec.lte || lte - this.gt = spec.gt || gt - this.gte = spec.gte || gte - this.eq = spec.eq || eq$6 - this.neq = spec.neq || neq - this.startOf = spec.startOf || startOf - this.endOf = spec.endOf || endOf - this.add = spec.add || add - this.range = spec.range || range$1 - this.diff = spec.diff || diff - this.ceil = spec.ceil || ceil - this.min = spec.min || min$1 - this.max = spec.max || max$1 - this.minutes = spec.minutes || minutes - this.firstVisibleDay = spec.firstVisibleDay || firstVisibleDay - this.lastVisibleDay = spec.lastVisibleDay || lastVisibleDay - this.visibleDays = spec.visibleDays || visibleDays - this.getSlotDate = spec.getSlotDate || getSlotDate - - this.getTimezoneOffset = - spec.getTimezoneOffset || - function (value) { - return value.getTimezoneOffset() - } - - this.getDstOffset = spec.getDstOffset || getDstOffset - this.getTotalMin = spec.getTotalMin || getTotalMin - this.getMinutesFromMidnight = - spec.getMinutesFromMidnight || getMinutesFromMidnight - this.continuesPrior = spec.continuesPrior || continuesPrior - this.continuesAfter = spec.continuesAfter || continuesAfter - this.sortEvents = spec.sortEvents || sortEvents$1 - this.inEventRange = spec.inEventRange || inEventRange - this.isSameDate = spec.isSameDate || isSameDate - this.startAndEndAreDateOnly = - spec.startAndEndAreDateOnly || startAndEndAreDateOnly - this.segmentOffset = spec.browserTZOffset ? spec.browserTZOffset() : 0 - }) - function mergeWithDefaults(localizer, culture, formatOverrides, messages) { - var formats = _objectSpread2( - _objectSpread2({}, localizer.formats), - formatOverrides - ) - - return _objectSpread2( - _objectSpread2({}, localizer), - {}, - { - messages: messages, - startOfWeek: function startOfWeek() { - return localizer.startOfWeek(culture) - }, - format: function format(value, _format2) { - return localizer.format(value, formats[_format2] || _format2, culture) - }, - } - ) - } - - var defaultMessages = { - date: 'Date', - time: 'Time', - event: 'Event', - allDay: 'All Day', - week: 'Week', - work_week: 'Work Week', - day: 'Day', - month: 'Month', - previous: 'Back', - next: 'Next', - yesterday: 'Yesterday', - tomorrow: 'Tomorrow', - today: 'Today', - agenda: 'Agenda', - noEventsInRange: 'There are no events in this range.', - showMore: function showMore(total) { - return '+'.concat(total, ' more') - }, - } - function messages(msgs) { - return _objectSpread2(_objectSpread2({}, defaultMessages), msgs) - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length - - for (var i = 0, arr2 = new Array(len); i < len; i++) { - arr2[i] = arr[i] - } - - return arr2 - } - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr) - } - - function _iterableToArray(iter) { - if ( - (typeof Symbol !== 'undefined' && iter[Symbol.iterator] != null) || - iter['@@iterator'] != null - ) - return Array.from(iter) - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return - if (typeof o === 'string') return _arrayLikeToArray(o, minLen) - var n = Object.prototype.toString.call(o).slice(8, -1) - if (n === 'Object' && o.constructor) n = o.constructor.name - if (n === 'Map' || n === 'Set') return Array.from(o) - if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) - return _arrayLikeToArray(o, minLen) - } - - function _nonIterableSpread() { - throw new TypeError( - 'Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.' - ) - } - - function _toConsumableArray(arr) { - return ( - _arrayWithoutHoles(arr) || - _iterableToArray(arr) || - _unsupportedIterableToArray(arr) || - _nonIterableSpread() - ) - } - - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - - function baseSlice$2(array, start, end) { - var index = -1, - length = array.length - - if (start < 0) { - start = -start > length ? 0 : length + start - } - end = end > length ? length : end - if (end < 0) { - end += length - } - length = start > end ? 0 : (end - start) >>> 0 - start >>>= 0 - - var result = Array(length) - while (++index < length) { - result[index] = array[index + start] - } - return result - } - - var _baseSlice = baseSlice$2 - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - - function eq$5(value, other) { - return value === other || (value !== value && other !== other) - } - - var eq_1 = eq$5 - - /** Detect free variable `global` from Node.js. */ - - var freeGlobal$1 = - typeof commonjsGlobal == 'object' && - commonjsGlobal && - commonjsGlobal.Object === Object && - commonjsGlobal - - var _freeGlobal = freeGlobal$1 - - var freeGlobal = _freeGlobal - - /** Detect free variable `self`. */ - var freeSelf = - typeof self == 'object' && self && self.Object === Object && self - - /** Used as a reference to the global object. */ - var root$8 = freeGlobal || freeSelf || Function('return this')() - - var _root = root$8 - - var root$7 = _root - - /** Built-in value references. */ - var Symbol$7 = root$7.Symbol - - var _Symbol = Symbol$7 - - var Symbol$6 = _Symbol - - /** Used for built-in method references. */ - var objectProto$g = Object.prototype - - /** Used to check objects for own properties. */ - var hasOwnProperty$d = objectProto$g.hasOwnProperty - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString$1 = objectProto$g.toString - - /** Built-in value references. */ - var symToStringTag$1 = Symbol$6 ? Symbol$6.toStringTag : undefined - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag$1(value) { - var isOwn = hasOwnProperty$d.call(value, symToStringTag$1), - tag = value[symToStringTag$1] - - try { - value[symToStringTag$1] = undefined - var unmasked = true - } catch (e) {} - - var result = nativeObjectToString$1.call(value) - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag - } else { - delete value[symToStringTag$1] - } - } - return result - } - - var _getRawTag = getRawTag$1 - - /** Used for built-in method references. */ - - var objectProto$f = Object.prototype - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto$f.toString - - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString$1(value) { - return nativeObjectToString.call(value) - } - - var _objectToString = objectToString$1 - - var Symbol$5 = _Symbol, - getRawTag = _getRawTag, - objectToString = _objectToString - - /** `Object#toString` result references. */ - var nullTag = '[object Null]', - undefinedTag = '[object Undefined]' - - /** Built-in value references. */ - var symToStringTag = Symbol$5 ? Symbol$5.toStringTag : undefined - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag$6(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag - } - return symToStringTag && symToStringTag in Object(value) - ? getRawTag(value) - : objectToString(value) - } - - var _baseGetTag = baseGetTag$6 - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - - function isObject$9(value) { - var type = typeof value - return value != null && (type == 'object' || type == 'function') - } - - var isObject_1 = isObject$9 - - var baseGetTag$5 = _baseGetTag, - isObject$8 = isObject_1 - - /** `Object#toString` result references. */ - var asyncTag = '[object AsyncFunction]', - funcTag$2 = '[object Function]', - genTag$1 = '[object GeneratorFunction]', - proxyTag = '[object Proxy]' - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction$4(value) { - if (!isObject$8(value)) { - return false - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag$5(value) - return ( - tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag - ) - } - - var isFunction_1 = isFunction$4 - - /** Used as references for various `Number` constants. */ - - var MAX_SAFE_INTEGER$1 = 9007199254740991 - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength$3(value) { - return ( - typeof value == 'number' && - value > -1 && - value % 1 == 0 && - value <= MAX_SAFE_INTEGER$1 - ) - } - - var isLength_1 = isLength$3 - - var isFunction$3 = isFunction_1, - isLength$2 = isLength_1 - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike$5(value) { - return value != null && isLength$2(value.length) && !isFunction$3(value) - } - - var isArrayLike_1 = isArrayLike$5 - - /** Used as references for various `Number` constants. */ - - var MAX_SAFE_INTEGER = 9007199254740991 - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/ - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex$3(value, length) { - var type = typeof value - length = length == null ? MAX_SAFE_INTEGER : length - - return ( - !!length && - (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && - value > -1 && - value % 1 == 0 && - value < length - ) - } - - var _isIndex = isIndex$3 - - var eq$4 = eq_1, - isArrayLike$4 = isArrayLike_1, - isIndex$2 = _isIndex, - isObject$7 = isObject_1 - - /** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ - function isIterateeCall$4(value, index, object) { - if (!isObject$7(object)) { - return false - } - var type = typeof index - if ( - type == 'number' - ? isArrayLike$4(object) && isIndex$2(index, object.length) - : type == 'string' && index in object - ) { - return eq$4(object[index], value) - } - return false - } - - var _isIterateeCall = isIterateeCall$4 - - /** Used to match a single whitespace character. */ - - var reWhitespace = /\s/ - - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ - function trimmedEndIndex$1(string) { - var index = string.length - - while (index-- && reWhitespace.test(string.charAt(index))) {} - return index - } - - var _trimmedEndIndex = trimmedEndIndex$1 - - var trimmedEndIndex = _trimmedEndIndex - - /** Used to match leading whitespace. */ - var reTrimStart = /^\s+/ - - /** - * The base implementation of `_.trim`. - * - * @private - * @param {string} string The string to trim. - * @returns {string} Returns the trimmed string. - */ - function baseTrim$1(string) { - return string - ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') - : string - } - - var _baseTrim = baseTrim$1 - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - - function isObjectLike$8(value) { - return value != null && typeof value == 'object' - } - - var isObjectLike_1 = isObjectLike$8 - - var baseGetTag$4 = _baseGetTag, - isObjectLike$7 = isObjectLike_1 - - /** `Object#toString` result references. */ - var symbolTag$3 = '[object Symbol]' - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol$5(value) { - return ( - typeof value == 'symbol' || - (isObjectLike$7(value) && baseGetTag$4(value) == symbolTag$3) - ) - } - - var isSymbol_1 = isSymbol$5 - - var baseTrim = _baseTrim, - isObject$6 = isObject_1, - isSymbol$4 = isSymbol_1 - - /** Used as references for various `Number` constants. */ - var NAN = 0 / 0 - - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i - - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i - - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i - - /** Built-in method references without a dependency on `root`. */ - var freeParseInt = parseInt - - /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ - function toNumber$1(value) { - if (typeof value == 'number') { - return value - } - if (isSymbol$4(value)) { - return NAN - } - if (isObject$6(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value - value = isObject$6(other) ? other + '' : other - } - if (typeof value != 'string') { - return value === 0 ? value : +value - } - value = baseTrim(value) - var isBinary = reIsBinary.test(value) - return isBinary || reIsOctal.test(value) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : reIsBadHex.test(value) - ? NAN - : +value - } - - var toNumber_1 = toNumber$1 - - var toNumber = toNumber_1 - - /** Used as references for various `Number` constants. */ - var INFINITY$2 = 1 / 0, - MAX_INTEGER = 1.7976931348623157e308 - - /** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ - function toFinite$2(value) { - if (!value) { - return value === 0 ? value : 0 - } - value = toNumber(value) - if (value === INFINITY$2 || value === -INFINITY$2) { - var sign = value < 0 ? -1 : 1 - return sign * MAX_INTEGER - } - return value === value ? value : 0 - } - - var toFinite_1 = toFinite$2 - - var toFinite$1 = toFinite_1 - - /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ - function toInteger$2(value) { - var result = toFinite$1(value), - remainder = result % 1 - - return result === result ? (remainder ? result - remainder : result) : 0 - } - - var toInteger_1 = toInteger$2 - - var baseSlice$1 = _baseSlice, - isIterateeCall$3 = _isIterateeCall, - toInteger$1 = toInteger_1 - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeCeil$1 = Math.ceil, - nativeMax$3 = Math.max - - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] - * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ - function chunk(array, size, guard) { - if (guard ? isIterateeCall$3(array, size, guard) : size === undefined) { - size = 1 - } else { - size = nativeMax$3(toInteger$1(size), 0) - } - var length = array == null ? 0 : array.length - if (!length || size < 1) { - return [] - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil$1(length / size)) - - while (index < length) { - result[resIndex++] = baseSlice$1(array, index, (index += size)) - } - return result - } - - var chunk_1 = chunk - - function _extends$1() { - _extends$1 = - Object.assign || - function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target - } - - return _extends$1.apply(this, arguments) - } - - /** - * Returns the owner document of a given element. - * - * @param node the element - */ - function ownerDocument$1(node) { - return (node && node.ownerDocument) || document - } - - /** - * Returns the owner window of a given element. - * - * @param node the element - */ - - function ownerWindow(node) { - var doc = ownerDocument$1(node) - return (doc && doc.defaultView) || window - } - - /** - * Returns one or all computed style properties of an element. - * - * @param node the element - * @param psuedoElement the style property - */ - - function getComputedStyle$1(node, psuedoElement) { - return ownerWindow(node).getComputedStyle(node, psuedoElement) - } - - var rUpper = /([A-Z])/g - function hyphenate(string) { - return string.replace(rUpper, '-$1').toLowerCase() - } - - /** - * Copyright 2013-2014, Facebook, Inc. - * All rights reserved. - * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js - */ - var msPattern = /^ms-/ - function hyphenateStyleName(string) { - return hyphenate(string).replace(msPattern, '-ms-') - } - - var supportedTransforms = - /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i - function isTransform(value) { - return !!(value && supportedTransforms.test(value)) - } - - function style(node, property) { - var css = '' - var transforms = '' - - if (typeof property === 'string') { - return ( - node.style.getPropertyValue(hyphenateStyleName(property)) || - getComputedStyle$1(node).getPropertyValue(hyphenateStyleName(property)) - ) - } - - Object.keys(property).forEach(function (key) { - var value = property[key] - - if (!value && value !== 0) { - node.style.removeProperty(hyphenateStyleName(key)) - } else if (isTransform(key)) { - transforms += key + '(' + value + ') ' - } else { - css += hyphenateStyleName(key) + ': ' + value + ';' - } - }) - - if (transforms) { - css += 'transform: ' + transforms + ';' - } - - node.style.cssText += ';' + css - } - - /* eslint-disable no-bitwise, no-cond-assign */ - - /** - * Checks if an element contains another given element. - * - * @param context the context element - * @param node the element to check - */ - function contains$1(context, node) { - // HTML DOM and SVG DOM may have different support levels, - // so we need to check on context instead of a document root element. - if (context.contains) return context.contains(node) - if (context.compareDocumentPosition) - return context === node || !!(context.compareDocumentPosition(node) & 16) - } - - function isDocument(element) { - return 'nodeType' in element && element.nodeType === document.DOCUMENT_NODE - } - - function isWindow(node) { - if ('window' in node && node.window === node) return node - if (isDocument(node)) return node.defaultView || false - return false - } - - function getscrollAccessor(offset) { - var prop = offset === 'pageXOffset' ? 'scrollLeft' : 'scrollTop' - - function scrollAccessor(node, val) { - var win = isWindow(node) - - if (val === undefined) { - return win ? win[offset] : node[prop] - } - - if (win) { - win.scrollTo(win[offset], val) - } else { - node[prop] = val - } - } - - return scrollAccessor - } - - /** - * Gets or sets the scroll left position of a given element. - * - * @param node the element - * @param val the position to set - */ - - var scrollLeft = getscrollAccessor('pageXOffset') - - /** - * Gets or sets the scroll top position of a given element. - * - * @param node the element - * @param val the position to set - */ - - var scrollTop = getscrollAccessor('pageYOffset') - - /** - * Returns the offset of a given element, including top and left positions, width and height. - * - * @param node the element - */ - - function offset$2(node) { - var doc = ownerDocument$1(node) - var box = { - top: 0, - left: 0, - height: 0, - width: 0, - } - var docElem = doc && doc.documentElement // Make sure it's not a disconnected DOM node - - if (!docElem || !contains$1(docElem, node)) return box - if (node.getBoundingClientRect !== undefined) - box = node.getBoundingClientRect() - box = { - top: box.top + scrollTop(docElem) - (docElem.clientTop || 0), - left: box.left + scrollLeft(docElem) - (docElem.clientLeft || 0), - width: box.width, - height: box.height, - } - return box - } - - var isHTMLElement$1 = function isHTMLElement(e) { - return !!e && 'offsetParent' in e - } - - function offsetParent(node) { - var doc = ownerDocument$1(node) - var parent = node && node.offsetParent - - while ( - isHTMLElement$1(parent) && - parent.nodeName !== 'HTML' && - style(parent, 'position') === 'static' - ) { - parent = parent.offsetParent - } - - return parent || doc.documentElement - } - - var nodeName = function nodeName(node) { - return node.nodeName && node.nodeName.toLowerCase() - } - /** - * Returns the relative position of a given element. - * - * @param node the element - * @param offsetParent the offset parent - */ - - function position(node, offsetParent$1) { - var parentOffset = { - top: 0, - left: 0, - } - var offset // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, - // because it is its only offset parent - - if (style(node, 'position') === 'fixed') { - offset = node.getBoundingClientRect() - } else { - var parent = offsetParent$1 || offsetParent(node) - offset = offset$2(node) - if (nodeName(parent) !== 'html') parentOffset = offset$2(parent) - var borderTop = String(style(parent, 'borderTopWidth') || 0) - parentOffset.top += parseInt(borderTop, 10) - scrollTop(parent) || 0 - var borderLeft = String(style(parent, 'borderLeftWidth') || 0) - parentOffset.left += parseInt(borderLeft, 10) - scrollLeft(parent) || 0 - } - - var marginTop = String(style(node, 'marginTop') || 0) - var marginLeft = String(style(node, 'marginLeft') || 0) // Subtract parent offsets and node margins - - return _extends$1({}, offset, { - top: offset.top - parentOffset.top - (parseInt(marginTop, 10) || 0), - left: offset.left - parentOffset.left - (parseInt(marginLeft, 10) || 0), - }) - } - - var canUseDOM = !!( - typeof window !== 'undefined' && - window.document && - window.document.createElement - ) - - /* https://github.com/component/raf */ - var prev = new Date().getTime() - - function fallback(fn) { - var curr = new Date().getTime() - var ms = Math.max(0, 16 - (curr - prev)) - var handle = setTimeout(fn, ms) - prev = curr - return handle - } - - var vendors = ['', 'webkit', 'moz', 'o', 'ms'] - var cancelMethod = 'clearTimeout' - var rafImpl = fallback // eslint-disable-next-line import/no-mutable-exports - - var getKey$1 = function getKey(vendor, k) { - return ( - vendor + - (!vendor ? k : k[0].toUpperCase() + k.substr(1)) + - 'AnimationFrame' - ) - } - - if (canUseDOM) { - vendors.some(function (vendor) { - var rafMethod = getKey$1(vendor, 'request') - - if (rafMethod in window) { - cancelMethod = getKey$1(vendor, 'cancel') // @ts-ignore - - rafImpl = function rafImpl(cb) { - return window[rafMethod](cb) - } - } - - return !!rafImpl - }) - } - - var cancel = function cancel(id) { - // @ts-ignore - if (typeof window[cancelMethod] === 'function') window[cancelMethod](id) - } - var request = rafImpl - - var matchesImpl - /** - * Checks if a given element matches a selector. - * - * @param node the element - * @param selector the selector - */ - - function matches(node, selector) { - if (!matchesImpl) { - var body = document.body - var nativeMatch = - body.matches || - body.matchesSelector || - body.webkitMatchesSelector || - body.mozMatchesSelector || - body.msMatchesSelector - - matchesImpl = function matchesImpl(n, s) { - return nativeMatch.call(n, s) - } - } - - return matchesImpl(node, selector) - } - - var toArray = Function.prototype.bind.call(Function.prototype.call, [].slice) - /** - * Runs `querySelectorAll` on a given element. - * - * @param element the element - * @param selector the selector - */ - - function qsa(element, selector) { - return toArray(element.querySelectorAll(selector)) - } - - /* eslint-disable no-return-assign */ - var optionsSupported = false - var onceSupported = false - - try { - var options = { - get passive() { - return (optionsSupported = true) - }, - - get once() { - // eslint-disable-next-line no-multi-assign - return (onceSupported = optionsSupported = true) - }, - } - - if (canUseDOM) { - window.addEventListener('test', options, options) - window.removeEventListener('test', options, true) - } - } catch (e) { - /* */ - } - - /** - * An `addEventListener` ponyfill, supports the `once` option - * - * @param node the element - * @param eventName the event name - * @param handle the handler - * @param options event options - */ - function addEventListener$1(node, eventName, handler, options) { - if (options && typeof options !== 'boolean' && !onceSupported) { - var once = options.once, - capture = options.capture - var wrappedHandler = handler - - if (!onceSupported && once) { - wrappedHandler = - handler.__once || - function onceHandler(event) { - this.removeEventListener(eventName, onceHandler, capture) - handler.call(this, event) - } - - handler.__once = wrappedHandler - } - - node.addEventListener( - eventName, - wrappedHandler, - optionsSupported ? options : capture - ) - } - - node.addEventListener(eventName, handler, options) - } - - /** - * Store the last of some value. Tracked via a `Ref` only updating it - * after the component renders. - * - * Helpful if you need to compare a prop value to it's previous value during render. - * - * ```ts - * function Component(props) { - * const lastProps = usePrevious(props) - * - * if (lastProps.foo !== props.foo) - * resetValueFromProps(props.foo) - * } - * ``` - * - * @param value the value to track - */ - - function usePrevious(value) { - var ref = react.exports.useRef(null) - react.exports.useEffect(function () { - ref.current = value - }) - return ref.current - } - - /** - * Creates a `Ref` whose value is updated in an effect, ensuring the most recent - * value is the one rendered with. Generally only required for Concurrent mode usage - * where previous work in `render()` may be discarded before being used. - * - * This is safe to access in an event handler. - * - * @param value The `Ref` value - */ - - function useCommittedRef(value) { - var ref = react.exports.useRef(value) - react.exports.useEffect( - function () { - ref.current = value - }, - [value] - ) - return ref - } - - function useEventCallback(fn) { - var ref = useCommittedRef(fn) - return react.exports.useCallback( - function () { - return ref.current && ref.current.apply(ref, arguments) - }, - [ref] - ) - } - - var DropdownContext = /*#__PURE__*/ React.createContext(null) - - function _extends() { - _extends = Object.assign - ? Object.assign.bind() - : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target - } - return _extends.apply(this, arguments) - } - - /** - * A convenience hook around `useState` designed to be paired with - * the component [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs) api. - * Callback refs are useful over `useRef()` when you need to respond to the ref being set - * instead of lazily accessing it in an effect. - * - * ```ts - * const [element, attachRef] = useCallbackRef() - * - * useEffect(() => { - * if (!element) return - * - * const calendar = new FullCalendar.Calendar(element) - * - * return () => { - * calendar.destroy() - * } - * }, [element]) - * - * return
- * ``` - * - * @category refs - */ - - function useCallbackRef() { - return react.exports.useState(null) - } - - /** - * Track whether a component is current mounted. Generally less preferable than - * properlly canceling effects so they don't run after a component is unmounted, - * but helpful in cases where that isn't feasible, such as a `Promise` resolution. - * - * @returns a function that returns the current isMounted state of the component - * - * ```ts - * const [data, setData] = useState(null) - * const isMounted = useMounted() - * - * useEffect(() => { - * fetchdata().then((newData) => { - * if (isMounted()) { - * setData(newData); - * } - * }) - * }) - * ``` - */ - - function useMounted() { - var mounted = react.exports.useRef(true) - var isMounted = react.exports.useRef(function () { - return mounted.current - }) - react.exports.useEffect(function () { - mounted.current = true - return function () { - mounted.current = false - } - }, []) - return isMounted.current - } - - function useSafeState(state) { - var isMounted = useMounted() - return [ - state[0], - react.exports.useCallback( - function (nextState) { - if (!isMounted()) return - return state[1](nextState) - }, - [isMounted, state[1]] - ), - ] - } - - var top = 'top' - var bottom = 'bottom' - var right = 'right' - var left = 'left' - var auto = 'auto' - var basePlacements = [top, bottom, right, left] - var start = 'start' - var end = 'end' - var clippingParents = 'clippingParents' - var viewport = 'viewport' - var popper = 'popper' - var reference = 'reference' - var variationPlacements = /*#__PURE__*/ basePlacements.reduce(function ( - acc, - placement - ) { - return acc.concat([placement + '-' + start, placement + '-' + end]) - }, - []) - var placements = /*#__PURE__*/ [] - .concat(basePlacements, [auto]) - .reduce(function (acc, placement) { - return acc.concat([ - placement, - placement + '-' + start, - placement + '-' + end, - ]) - }, []) // modifiers that need to read the DOM - - var beforeRead = 'beforeRead' - var read = 'read' - var afterRead = 'afterRead' // pure-logic modifiers - - var beforeMain = 'beforeMain' - var main = 'main' - var afterMain = 'afterMain' // modifier with the purpose to write to the DOM (or write into a framework state) - - var beforeWrite = 'beforeWrite' - var write = 'write' - var afterWrite = 'afterWrite' - var modifierPhases = [ - beforeRead, - read, - afterRead, - beforeMain, - main, - afterMain, - beforeWrite, - write, - afterWrite, - ] - - function getBasePlacement(placement) { - return placement.split('-')[0] - } - - function getWindow(node) { - if (node == null) { - return window - } - - if (node.toString() !== '[object Window]') { - var ownerDocument = node.ownerDocument - return ownerDocument ? ownerDocument.defaultView || window : window - } - - return node - } - - function isElement(node) { - var OwnElement = getWindow(node).Element - return node instanceof OwnElement || node instanceof Element - } - - function isHTMLElement(node) { - var OwnElement = getWindow(node).HTMLElement - return node instanceof OwnElement || node instanceof HTMLElement - } - - function isShadowRoot(node) { - // IE 11 has no ShadowRoot - if (typeof ShadowRoot === 'undefined') { - return false - } - - var OwnElement = getWindow(node).ShadowRoot - return node instanceof OwnElement || node instanceof ShadowRoot - } - - var max = Math.max - var min = Math.min - var round = Math.round - - function getBoundingClientRect(element, includeScale) { - if (includeScale === void 0) { - includeScale = false - } - - var rect = element.getBoundingClientRect() - var scaleX = 1 - var scaleY = 1 - - if (isHTMLElement(element) && includeScale) { - var offsetHeight = element.offsetHeight - var offsetWidth = element.offsetWidth // Do not attempt to divide by 0, otherwise we get `Infinity` as scale - // Fallback to 1 in case both values are `0` - - if (offsetWidth > 0) { - scaleX = round(rect.width) / offsetWidth || 1 - } - - if (offsetHeight > 0) { - scaleY = round(rect.height) / offsetHeight || 1 - } - } - - return { - width: rect.width / scaleX, - height: rect.height / scaleY, - top: rect.top / scaleY, - right: rect.right / scaleX, - bottom: rect.bottom / scaleY, - left: rect.left / scaleX, - x: rect.left / scaleX, - y: rect.top / scaleY, - } - } - - // means it doesn't take into account transforms. - - function getLayoutRect(element) { - var clientRect = getBoundingClientRect(element) // Use the clientRect sizes if it's not been transformed. - // Fixes https://github.com/popperjs/popper-core/issues/1223 - - var width = element.offsetWidth - var height = element.offsetHeight - - if (Math.abs(clientRect.width - width) <= 1) { - width = clientRect.width - } - - if (Math.abs(clientRect.height - height) <= 1) { - height = clientRect.height - } - - return { - x: element.offsetLeft, - y: element.offsetTop, - width: width, - height: height, - } - } - - function contains(parent, child) { - var rootNode = child.getRootNode && child.getRootNode() // First, attempt with faster native method - - if (parent.contains(child)) { - return true - } // then fallback to custom implementation with Shadow DOM support - else if (rootNode && isShadowRoot(rootNode)) { - var next = child - - do { - if (next && parent.isSameNode(next)) { - return true - } // $FlowFixMe[prop-missing]: need a better way to handle this... - - next = next.parentNode || next.host - } while (next) - } // Give up, the result is false - - return false - } - - function getNodeName(element) { - return element ? (element.nodeName || '').toLowerCase() : null - } - - function getComputedStyle(element) { - return getWindow(element).getComputedStyle(element) - } - - function isTableElement(element) { - return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0 - } - - function getDocumentElement(element) { - // $FlowFixMe[incompatible-return]: assume body is always available - return ( - (isElement(element) - ? element.ownerDocument // $FlowFixMe[prop-missing] - : element.document) || window.document - ).documentElement - } - - function getParentNode(element) { - if (getNodeName(element) === 'html') { - return element - } - - return ( - // this is a quicker (but less type safe) way to save quite some bytes from the bundle - // $FlowFixMe[incompatible-return] - // $FlowFixMe[prop-missing] - element.assignedSlot || // step into the shadow DOM of the parent of a slotted node - element.parentNode || // DOM Element detected - (isShadowRoot(element) ? element.host : null) || // ShadowRoot detected - // $FlowFixMe[incompatible-call]: HTMLElement is a Node - getDocumentElement(element) // fallback - ) - } - - function getTrueOffsetParent(element) { - if ( - !isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837 - getComputedStyle(element).position === 'fixed' - ) { - return null - } - - return element.offsetParent - } // `.offsetParent` reports `null` for fixed elements, while absolute elements - // return the containing block - - function getContainingBlock(element) { - var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 - var isIE = navigator.userAgent.indexOf('Trident') !== -1 - - if (isIE && isHTMLElement(element)) { - // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport - var elementCss = getComputedStyle(element) - - if (elementCss.position === 'fixed') { - return null - } - } - - var currentNode = getParentNode(element) - - if (isShadowRoot(currentNode)) { - currentNode = currentNode.host - } - - while ( - isHTMLElement(currentNode) && - ['html', 'body'].indexOf(getNodeName(currentNode)) < 0 - ) { - var css = getComputedStyle(currentNode) // This is non-exhaustive but covers the most common CSS properties that - // create a containing block. - // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - - if ( - css.transform !== 'none' || - css.perspective !== 'none' || - css.contain === 'paint' || - ['transform', 'perspective'].indexOf(css.willChange) !== -1 || - (isFirefox && css.willChange === 'filter') || - (isFirefox && css.filter && css.filter !== 'none') - ) { - return currentNode - } else { - currentNode = currentNode.parentNode - } - } - - return null - } // Gets the closest ancestor positioned element. Handles some edge cases, - // such as table ancestors and cross browser bugs. - - function getOffsetParent(element) { - var window = getWindow(element) - var offsetParent = getTrueOffsetParent(element) - - while ( - offsetParent && - isTableElement(offsetParent) && - getComputedStyle(offsetParent).position === 'static' - ) { - offsetParent = getTrueOffsetParent(offsetParent) - } - - if ( - offsetParent && - (getNodeName(offsetParent) === 'html' || - (getNodeName(offsetParent) === 'body' && - getComputedStyle(offsetParent).position === 'static')) - ) { - return window - } - - return offsetParent || getContainingBlock(element) || window - } - - function getMainAxisFromPlacement(placement) { - return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y' - } - - function within(min$1, value, max$1) { - return max(min$1, min(value, max$1)) - } - function withinMaxClamp(min, value, max) { - var v = within(min, value, max) - return v > max ? max : v - } - - function getFreshSideObject() { - return { - top: 0, - right: 0, - bottom: 0, - left: 0, - } - } - - function mergePaddingObject(paddingObject) { - return Object.assign({}, getFreshSideObject(), paddingObject) - } - - function expandToHashMap(value, keys) { - return keys.reduce(function (hashMap, key) { - hashMap[key] = value - return hashMap - }, {}) - } - - var toPaddingObject = function toPaddingObject(padding, state) { - padding = - typeof padding === 'function' - ? padding( - Object.assign({}, state.rects, { - placement: state.placement, - }) - ) - : padding - return mergePaddingObject( - typeof padding !== 'number' - ? padding - : expandToHashMap(padding, basePlacements) - ) - } - - function arrow(_ref) { - var _state$modifiersData$ - - var state = _ref.state, - name = _ref.name, - options = _ref.options - var arrowElement = state.elements.arrow - var popperOffsets = state.modifiersData.popperOffsets - var basePlacement = getBasePlacement(state.placement) - var axis = getMainAxisFromPlacement(basePlacement) - var isVertical = [left, right].indexOf(basePlacement) >= 0 - var len = isVertical ? 'height' : 'width' - - if (!arrowElement || !popperOffsets) { - return - } - - var paddingObject = toPaddingObject(options.padding, state) - var arrowRect = getLayoutRect(arrowElement) - var minProp = axis === 'y' ? top : left - var maxProp = axis === 'y' ? bottom : right - var endDiff = - state.rects.reference[len] + - state.rects.reference[axis] - - popperOffsets[axis] - - state.rects.popper[len] - var startDiff = popperOffsets[axis] - state.rects.reference[axis] - var arrowOffsetParent = getOffsetParent(arrowElement) - var clientSize = arrowOffsetParent - ? axis === 'y' - ? arrowOffsetParent.clientHeight || 0 - : arrowOffsetParent.clientWidth || 0 - : 0 - var centerToReference = endDiff / 2 - startDiff / 2 // Make sure the arrow doesn't overflow the popper if the center point is - // outside of the popper bounds - - var min = paddingObject[minProp] - var max = clientSize - arrowRect[len] - paddingObject[maxProp] - var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference - var offset = within(min, center, max) // Prevents breaking syntax highlighting... - - var axisProp = axis - state.modifiersData[name] = - ((_state$modifiersData$ = {}), - (_state$modifiersData$[axisProp] = offset), - (_state$modifiersData$.centerOffset = offset - center), - _state$modifiersData$) - } - - function effect$1(_ref2) { - var state = _ref2.state, - options = _ref2.options - var _options$element = options.element, - arrowElement = - _options$element === void 0 ? '[data-popper-arrow]' : _options$element - - if (arrowElement == null) { - return - } // CSS selector - - if (typeof arrowElement === 'string') { - arrowElement = state.elements.popper.querySelector(arrowElement) - - if (!arrowElement) { - return - } - } - - { - if (!isHTMLElement(arrowElement)) { - console.error( - [ - 'Popper: "arrow" element must be an HTMLElement (not an SVGElement).', - 'To use an SVG arrow, wrap it in an HTMLElement that will be used as', - 'the arrow.', - ].join(' ') - ) - } - } - - if (!contains(state.elements.popper, arrowElement)) { - { - console.error( - [ - 'Popper: "arrow" modifier\'s `element` must be a child of the popper', - 'element.', - ].join(' ') - ) - } - - return - } - - state.elements.arrow = arrowElement - } // eslint-disable-next-line import/no-unused-modules - - var arrow$1 = { - name: 'arrow', - enabled: true, - phase: 'main', - fn: arrow, - effect: effect$1, - requires: ['popperOffsets'], - requiresIfExists: ['preventOverflow'], - } - - function getVariation(placement) { - return placement.split('-')[1] - } - - var unsetSides = { - top: 'auto', - right: 'auto', - bottom: 'auto', - left: 'auto', - } // Round the offsets to the nearest suitable subpixel based on the DPR. - // Zooming can change the DPR, but it seems to report a value that will - // cleanly divide the values into the appropriate subpixels. - - function roundOffsetsByDPR(_ref) { - var x = _ref.x, - y = _ref.y - var win = window - var dpr = win.devicePixelRatio || 1 - return { - x: round(x * dpr) / dpr || 0, - y: round(y * dpr) / dpr || 0, - } - } - - function mapToStyles(_ref2) { - var _Object$assign2 - - var popper = _ref2.popper, - popperRect = _ref2.popperRect, - placement = _ref2.placement, - variation = _ref2.variation, - offsets = _ref2.offsets, - position = _ref2.position, - gpuAcceleration = _ref2.gpuAcceleration, - adaptive = _ref2.adaptive, - roundOffsets = _ref2.roundOffsets, - isFixed = _ref2.isFixed - var _offsets$x = offsets.x, - x = _offsets$x === void 0 ? 0 : _offsets$x, - _offsets$y = offsets.y, - y = _offsets$y === void 0 ? 0 : _offsets$y - - var _ref3 = - typeof roundOffsets === 'function' - ? roundOffsets({ - x: x, - y: y, - }) - : { - x: x, - y: y, - } - - x = _ref3.x - y = _ref3.y - var hasX = offsets.hasOwnProperty('x') - var hasY = offsets.hasOwnProperty('y') - var sideX = left - var sideY = top - var win = window - - if (adaptive) { - var offsetParent = getOffsetParent(popper) - var heightProp = 'clientHeight' - var widthProp = 'clientWidth' - - if (offsetParent === getWindow(popper)) { - offsetParent = getDocumentElement(popper) - - if ( - getComputedStyle(offsetParent).position !== 'static' && - position === 'absolute' - ) { - heightProp = 'scrollHeight' - widthProp = 'scrollWidth' - } - } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it - - offsetParent = offsetParent - - if ( - placement === top || - ((placement === left || placement === right) && variation === end) - ) { - sideY = bottom - var offsetY = - isFixed && offsetParent === win && win.visualViewport - ? win.visualViewport.height // $FlowFixMe[prop-missing] - : offsetParent[heightProp] - y -= offsetY - popperRect.height - y *= gpuAcceleration ? 1 : -1 - } - - if ( - placement === left || - ((placement === top || placement === bottom) && variation === end) - ) { - sideX = right - var offsetX = - isFixed && offsetParent === win && win.visualViewport - ? win.visualViewport.width // $FlowFixMe[prop-missing] - : offsetParent[widthProp] - x -= offsetX - popperRect.width - x *= gpuAcceleration ? 1 : -1 - } - } - - var commonStyles = Object.assign( - { - position: position, - }, - adaptive && unsetSides - ) - - var _ref4 = - roundOffsets === true - ? roundOffsetsByDPR({ - x: x, - y: y, - }) - : { - x: x, - y: y, - } - - x = _ref4.x - y = _ref4.y - - if (gpuAcceleration) { - var _Object$assign - - return Object.assign( - {}, - commonStyles, - ((_Object$assign = {}), - (_Object$assign[sideY] = hasY ? '0' : ''), - (_Object$assign[sideX] = hasX ? '0' : ''), - (_Object$assign.transform = - (win.devicePixelRatio || 1) <= 1 - ? 'translate(' + x + 'px, ' + y + 'px)' - : 'translate3d(' + x + 'px, ' + y + 'px, 0)'), - _Object$assign) - ) - } - - return Object.assign( - {}, - commonStyles, - ((_Object$assign2 = {}), - (_Object$assign2[sideY] = hasY ? y + 'px' : ''), - (_Object$assign2[sideX] = hasX ? x + 'px' : ''), - (_Object$assign2.transform = ''), - _Object$assign2) - ) - } - - function computeStyles(_ref5) { - var state = _ref5.state, - options = _ref5.options - var _options$gpuAccelerat = options.gpuAcceleration, - gpuAcceleration = - _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, - _options$adaptive = options.adaptive, - adaptive = _options$adaptive === void 0 ? true : _options$adaptive, - _options$roundOffsets = options.roundOffsets, - roundOffsets = - _options$roundOffsets === void 0 ? true : _options$roundOffsets - - { - var transitionProperty = - getComputedStyle(state.elements.popper).transitionProperty || '' - - if ( - adaptive && - ['transform', 'top', 'right', 'bottom', 'left'].some(function ( - property - ) { - return transitionProperty.indexOf(property) >= 0 - }) - ) { - console.warn( - [ - 'Popper: Detected CSS transitions on at least one of the following', - 'CSS properties: "transform", "top", "right", "bottom", "left".', - '\n\n', - 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', - 'for smooth transitions, or remove these properties from the CSS', - 'transition declaration on the popper element if only transitioning', - 'opacity or background-color for example.', - '\n\n', - 'We recommend using the popper element as a wrapper around an inner', - 'element that can have any CSS property transitioned for animations.', - ].join(' ') - ) - } - } - - var commonStyles = { - placement: getBasePlacement(state.placement), - variation: getVariation(state.placement), - popper: state.elements.popper, - popperRect: state.rects.popper, - gpuAcceleration: gpuAcceleration, - isFixed: state.options.strategy === 'fixed', - } - - if (state.modifiersData.popperOffsets != null) { - state.styles.popper = Object.assign( - {}, - state.styles.popper, - mapToStyles( - Object.assign({}, commonStyles, { - offsets: state.modifiersData.popperOffsets, - position: state.options.strategy, - adaptive: adaptive, - roundOffsets: roundOffsets, - }) - ) - ) - } - - if (state.modifiersData.arrow != null) { - state.styles.arrow = Object.assign( - {}, - state.styles.arrow, - mapToStyles( - Object.assign({}, commonStyles, { - offsets: state.modifiersData.arrow, - position: 'absolute', - adaptive: false, - roundOffsets: roundOffsets, - }) - ) - ) - } - - state.attributes.popper = Object.assign({}, state.attributes.popper, { - 'data-popper-placement': state.placement, - }) - } // eslint-disable-next-line import/no-unused-modules - - var computeStyles$1 = { - name: 'computeStyles', - enabled: true, - phase: 'beforeWrite', - fn: computeStyles, - data: {}, - } - - var passive = { - passive: true, - } - - function effect(_ref) { - var state = _ref.state, - instance = _ref.instance, - options = _ref.options - var _options$scroll = options.scroll, - scroll = _options$scroll === void 0 ? true : _options$scroll, - _options$resize = options.resize, - resize = _options$resize === void 0 ? true : _options$resize - var window = getWindow(state.elements.popper) - var scrollParents = [].concat( - state.scrollParents.reference, - state.scrollParents.popper - ) - - if (scroll) { - scrollParents.forEach(function (scrollParent) { - scrollParent.addEventListener('scroll', instance.update, passive) - }) - } - - if (resize) { - window.addEventListener('resize', instance.update, passive) - } - - return function () { - if (scroll) { - scrollParents.forEach(function (scrollParent) { - scrollParent.removeEventListener('scroll', instance.update, passive) - }) - } - - if (resize) { - window.removeEventListener('resize', instance.update, passive) - } - } - } // eslint-disable-next-line import/no-unused-modules - - var eventListeners = { - name: 'eventListeners', - enabled: true, - phase: 'write', - fn: function fn() {}, - effect: effect, - data: {}, - } - - var hash$1 = { - left: 'right', - right: 'left', - bottom: 'top', - top: 'bottom', - } - function getOppositePlacement(placement) { - return placement.replace(/left|right|bottom|top/g, function (matched) { - return hash$1[matched] - }) - } - - var hash = { - start: 'end', - end: 'start', - } - function getOppositeVariationPlacement(placement) { - return placement.replace(/start|end/g, function (matched) { - return hash[matched] - }) - } - - function getWindowScroll(node) { - var win = getWindow(node) - var scrollLeft = win.pageXOffset - var scrollTop = win.pageYOffset - return { - scrollLeft: scrollLeft, - scrollTop: scrollTop, - } - } - - function getWindowScrollBarX(element) { - // If has a CSS width greater than the viewport, then this will be - // incorrect for RTL. - // Popper 1 is broken in this case and never had a bug report so let's assume - // it's not an issue. I don't think anyone ever specifies width on - // anyway. - // Browsers where the left scrollbar doesn't cause an issue report `0` for - // this (e.g. Edge 2019, IE11, Safari) - return ( - getBoundingClientRect(getDocumentElement(element)).left + - getWindowScroll(element).scrollLeft - ) - } - - function getViewportRect(element) { - var win = getWindow(element) - var html = getDocumentElement(element) - var visualViewport = win.visualViewport - var width = html.clientWidth - var height = html.clientHeight - var x = 0 - var y = 0 // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper - // can be obscured underneath it. - // Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even - // if it isn't open, so if this isn't available, the popper will be detected - // to overflow the bottom of the screen too early. - - if (visualViewport) { - width = visualViewport.width - height = visualViewport.height // Uses Layout Viewport (like Chrome; Safari does not currently) - // In Chrome, it returns a value very close to 0 (+/-) but contains rounding - // errors due to floating point numbers, so we need to check precision. - // Safari returns a number <= 0, usually < -1 when pinch-zoomed - // Feature detection fails in mobile emulation mode in Chrome. - // Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) < - // 0.001 - // Fallback here: "Not Safari" userAgent - - if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { - x = visualViewport.offsetLeft - y = visualViewport.offsetTop - } - } - - return { - width: width, - height: height, - x: x + getWindowScrollBarX(element), - y: y, - } - } - - // of the `` and `` rect bounds if horizontally scrollable - - function getDocumentRect(element) { - var _element$ownerDocumen - - var html = getDocumentElement(element) - var winScroll = getWindowScroll(element) - var body = - (_element$ownerDocumen = element.ownerDocument) == null - ? void 0 - : _element$ownerDocumen.body - var width = max( - html.scrollWidth, - html.clientWidth, - body ? body.scrollWidth : 0, - body ? body.clientWidth : 0 - ) - var height = max( - html.scrollHeight, - html.clientHeight, - body ? body.scrollHeight : 0, - body ? body.clientHeight : 0 - ) - var x = -winScroll.scrollLeft + getWindowScrollBarX(element) - var y = -winScroll.scrollTop - - if (getComputedStyle(body || html).direction === 'rtl') { - x += max(html.clientWidth, body ? body.clientWidth : 0) - width - } - - return { - width: width, - height: height, - x: x, - y: y, - } - } - - function isScrollParent(element) { - // Firefox wants us to check `-x` and `-y` variations as well - var _getComputedStyle = getComputedStyle(element), - overflow = _getComputedStyle.overflow, - overflowX = _getComputedStyle.overflowX, - overflowY = _getComputedStyle.overflowY - - return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX) - } - - function getScrollParent(node) { - if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) { - // $FlowFixMe[incompatible-return]: assume body is always available - return node.ownerDocument.body - } - - if (isHTMLElement(node) && isScrollParent(node)) { - return node - } - - return getScrollParent(getParentNode(node)) - } - - /* - given a DOM element, return the list of all scroll parents, up the list of ancesors - until we get to the top window object. This list is what we attach scroll listeners - to, because if any of these parent elements scroll, we'll need to re-calculate the - reference element's position. - */ - - function listScrollParents(element, list) { - var _element$ownerDocumen - - if (list === void 0) { - list = [] - } - - var scrollParent = getScrollParent(element) - var isBody = - scrollParent === - ((_element$ownerDocumen = element.ownerDocument) == null - ? void 0 - : _element$ownerDocumen.body) - var win = getWindow(scrollParent) - var target = isBody - ? [win].concat( - win.visualViewport || [], - isScrollParent(scrollParent) ? scrollParent : [] - ) - : scrollParent - var updatedList = list.concat(target) - return isBody - ? updatedList // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here - : updatedList.concat(listScrollParents(getParentNode(target))) - } - - function rectToClientRect(rect) { - return Object.assign({}, rect, { - left: rect.x, - top: rect.y, - right: rect.x + rect.width, - bottom: rect.y + rect.height, - }) - } - - function getInnerBoundingClientRect(element) { - var rect = getBoundingClientRect(element) - rect.top = rect.top + element.clientTop - rect.left = rect.left + element.clientLeft - rect.bottom = rect.top + element.clientHeight - rect.right = rect.left + element.clientWidth - rect.width = element.clientWidth - rect.height = element.clientHeight - rect.x = rect.left - rect.y = rect.top - return rect - } - - function getClientRectFromMixedType(element, clippingParent) { - return clippingParent === viewport - ? rectToClientRect(getViewportRect(element)) - : isElement(clippingParent) - ? getInnerBoundingClientRect(clippingParent) - : rectToClientRect(getDocumentRect(getDocumentElement(element))) - } // A "clipping parent" is an overflowable container with the characteristic of - // clipping (or hiding) overflowing elements with a position different from - // `initial` - - function getClippingParents(element) { - var clippingParents = listScrollParents(getParentNode(element)) - var canEscapeClipping = - ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0 - var clipperElement = - canEscapeClipping && isHTMLElement(element) - ? getOffsetParent(element) - : element - - if (!isElement(clipperElement)) { - return [] - } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414 - - return clippingParents.filter(function (clippingParent) { - return ( - isElement(clippingParent) && - contains(clippingParent, clipperElement) && - getNodeName(clippingParent) !== 'body' - ) - }) - } // Gets the maximum area that the element is visible in due to any number of - // clipping parents - - function getClippingRect(element, boundary, rootBoundary) { - var mainClippingParents = - boundary === 'clippingParents' - ? getClippingParents(element) - : [].concat(boundary) - var clippingParents = [].concat(mainClippingParents, [rootBoundary]) - var firstClippingParent = clippingParents[0] - var clippingRect = clippingParents.reduce(function ( - accRect, - clippingParent - ) { - var rect = getClientRectFromMixedType(element, clippingParent) - accRect.top = max(rect.top, accRect.top) - accRect.right = min(rect.right, accRect.right) - accRect.bottom = min(rect.bottom, accRect.bottom) - accRect.left = max(rect.left, accRect.left) - return accRect - }, - getClientRectFromMixedType(element, firstClippingParent)) - clippingRect.width = clippingRect.right - clippingRect.left - clippingRect.height = clippingRect.bottom - clippingRect.top - clippingRect.x = clippingRect.left - clippingRect.y = clippingRect.top - return clippingRect - } - - function computeOffsets(_ref) { - var reference = _ref.reference, - element = _ref.element, - placement = _ref.placement - var basePlacement = placement ? getBasePlacement(placement) : null - var variation = placement ? getVariation(placement) : null - var commonX = reference.x + reference.width / 2 - element.width / 2 - var commonY = reference.y + reference.height / 2 - element.height / 2 - var offsets - - switch (basePlacement) { - case top: - offsets = { - x: commonX, - y: reference.y - element.height, - } - break - - case bottom: - offsets = { - x: commonX, - y: reference.y + reference.height, - } - break - - case right: - offsets = { - x: reference.x + reference.width, - y: commonY, - } - break - - case left: - offsets = { - x: reference.x - element.width, - y: commonY, - } - break - - default: - offsets = { - x: reference.x, - y: reference.y, - } - } - - var mainAxis = basePlacement - ? getMainAxisFromPlacement(basePlacement) - : null - - if (mainAxis != null) { - var len = mainAxis === 'y' ? 'height' : 'width' - - switch (variation) { - case start: - offsets[mainAxis] = - offsets[mainAxis] - (reference[len] / 2 - element[len] / 2) - break - - case end: - offsets[mainAxis] = - offsets[mainAxis] + (reference[len] / 2 - element[len] / 2) - break - } - } - - return offsets - } - - function detectOverflow(state, options) { - if (options === void 0) { - options = {} - } - - var _options = options, - _options$placement = _options.placement, - placement = - _options$placement === void 0 ? state.placement : _options$placement, - _options$boundary = _options.boundary, - boundary = - _options$boundary === void 0 ? clippingParents : _options$boundary, - _options$rootBoundary = _options.rootBoundary, - rootBoundary = - _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, - _options$elementConte = _options.elementContext, - elementContext = - _options$elementConte === void 0 ? popper : _options$elementConte, - _options$altBoundary = _options.altBoundary, - altBoundary = - _options$altBoundary === void 0 ? false : _options$altBoundary, - _options$padding = _options.padding, - padding = _options$padding === void 0 ? 0 : _options$padding - var paddingObject = mergePaddingObject( - typeof padding !== 'number' - ? padding - : expandToHashMap(padding, basePlacements) - ) - var altContext = elementContext === popper ? reference : popper - var popperRect = state.rects.popper - var element = state.elements[altBoundary ? altContext : elementContext] - var clippingClientRect = getClippingRect( - isElement(element) - ? element - : element.contextElement || getDocumentElement(state.elements.popper), - boundary, - rootBoundary - ) - var referenceClientRect = getBoundingClientRect(state.elements.reference) - var popperOffsets = computeOffsets({ - reference: referenceClientRect, - element: popperRect, - strategy: 'absolute', - placement: placement, - }) - var popperClientRect = rectToClientRect( - Object.assign({}, popperRect, popperOffsets) - ) - var elementClientRect = - elementContext === popper ? popperClientRect : referenceClientRect // positive = overflowing the clipping rect - // 0 or negative = within the clipping rect - - var overflowOffsets = { - top: clippingClientRect.top - elementClientRect.top + paddingObject.top, - bottom: - elementClientRect.bottom - - clippingClientRect.bottom + - paddingObject.bottom, - left: - clippingClientRect.left - elementClientRect.left + paddingObject.left, - right: - elementClientRect.right - - clippingClientRect.right + - paddingObject.right, - } - var offsetData = state.modifiersData.offset // Offsets can be applied only to the popper element - - if (elementContext === popper && offsetData) { - var offset = offsetData[placement] - Object.keys(overflowOffsets).forEach(function (key) { - var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1 - var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x' - overflowOffsets[key] += offset[axis] * multiply - }) - } - - return overflowOffsets - } - - function computeAutoPlacement(state, options) { - if (options === void 0) { - options = {} - } - - var _options = options, - placement = _options.placement, - boundary = _options.boundary, - rootBoundary = _options.rootBoundary, - padding = _options.padding, - flipVariations = _options.flipVariations, - _options$allowedAutoP = _options.allowedAutoPlacements, - allowedAutoPlacements = - _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP - var variation = getVariation(placement) - var placements$1 = variation - ? flipVariations - ? variationPlacements - : variationPlacements.filter(function (placement) { - return getVariation(placement) === variation - }) - : basePlacements - var allowedPlacements = placements$1.filter(function (placement) { - return allowedAutoPlacements.indexOf(placement) >= 0 - }) - - if (allowedPlacements.length === 0) { - allowedPlacements = placements$1 - - { - console.error( - [ - 'Popper: The `allowedAutoPlacements` option did not allow any', - 'placements. Ensure the `placement` option matches the variation', - 'of the allowed placements.', - 'For example, "auto" cannot be used to allow "bottom-start".', - 'Use "auto-start" instead.', - ].join(' ') - ) - } - } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions... - - var overflows = allowedPlacements.reduce(function (acc, placement) { - acc[placement] = detectOverflow(state, { - placement: placement, - boundary: boundary, - rootBoundary: rootBoundary, - padding: padding, - })[getBasePlacement(placement)] - return acc - }, {}) - return Object.keys(overflows).sort(function (a, b) { - return overflows[a] - overflows[b] - }) - } - - function getExpandedFallbackPlacements(placement) { - if (getBasePlacement(placement) === auto) { - return [] - } - - var oppositePlacement = getOppositePlacement(placement) - return [ - getOppositeVariationPlacement(placement), - oppositePlacement, - getOppositeVariationPlacement(oppositePlacement), - ] - } - - function flip(_ref) { - var state = _ref.state, - options = _ref.options, - name = _ref.name - - if (state.modifiersData[name]._skip) { - return - } - - var _options$mainAxis = options.mainAxis, - checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, - _options$altAxis = options.altAxis, - checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, - specifiedFallbackPlacements = options.fallbackPlacements, - padding = options.padding, - boundary = options.boundary, - rootBoundary = options.rootBoundary, - altBoundary = options.altBoundary, - _options$flipVariatio = options.flipVariations, - flipVariations = - _options$flipVariatio === void 0 ? true : _options$flipVariatio, - allowedAutoPlacements = options.allowedAutoPlacements - var preferredPlacement = state.options.placement - var basePlacement = getBasePlacement(preferredPlacement) - var isBasePlacement = basePlacement === preferredPlacement - var fallbackPlacements = - specifiedFallbackPlacements || - (isBasePlacement || !flipVariations - ? [getOppositePlacement(preferredPlacement)] - : getExpandedFallbackPlacements(preferredPlacement)) - var placements = [preferredPlacement] - .concat(fallbackPlacements) - .reduce(function (acc, placement) { - return acc.concat( - getBasePlacement(placement) === auto - ? computeAutoPlacement(state, { - placement: placement, - boundary: boundary, - rootBoundary: rootBoundary, - padding: padding, - flipVariations: flipVariations, - allowedAutoPlacements: allowedAutoPlacements, - }) - : placement - ) - }, []) - var referenceRect = state.rects.reference - var popperRect = state.rects.popper - var checksMap = new Map() - var makeFallbackChecks = true - var firstFittingPlacement = placements[0] - - for (var i = 0; i < placements.length; i++) { - var placement = placements[i] - - var _basePlacement = getBasePlacement(placement) - - var isStartVariation = getVariation(placement) === start - var isVertical = [top, bottom].indexOf(_basePlacement) >= 0 - var len = isVertical ? 'width' : 'height' - var overflow = detectOverflow(state, { - placement: placement, - boundary: boundary, - rootBoundary: rootBoundary, - altBoundary: altBoundary, - padding: padding, - }) - var mainVariationSide = isVertical - ? isStartVariation - ? right - : left - : isStartVariation - ? bottom - : top - - if (referenceRect[len] > popperRect[len]) { - mainVariationSide = getOppositePlacement(mainVariationSide) - } - - var altVariationSide = getOppositePlacement(mainVariationSide) - var checks = [] - - if (checkMainAxis) { - checks.push(overflow[_basePlacement] <= 0) - } - - if (checkAltAxis) { - checks.push( - overflow[mainVariationSide] <= 0, - overflow[altVariationSide] <= 0 - ) - } - - if ( - checks.every(function (check) { - return check - }) - ) { - firstFittingPlacement = placement - makeFallbackChecks = false - break - } - - checksMap.set(placement, checks) - } - - if (makeFallbackChecks) { - // `2` may be desired in some cases – research later - var numberOfChecks = flipVariations ? 3 : 1 - - var _loop = function _loop(_i) { - var fittingPlacement = placements.find(function (placement) { - var checks = checksMap.get(placement) - - if (checks) { - return checks.slice(0, _i).every(function (check) { - return check - }) - } - }) - - if (fittingPlacement) { - firstFittingPlacement = fittingPlacement - return 'break' - } - } - - for (var _i = numberOfChecks; _i > 0; _i--) { - var _ret = _loop(_i) - - if (_ret === 'break') break - } - } - - if (state.placement !== firstFittingPlacement) { - state.modifiersData[name]._skip = true - state.placement = firstFittingPlacement - state.reset = true - } - } // eslint-disable-next-line import/no-unused-modules - - var flip$1 = { - name: 'flip', - enabled: true, - phase: 'main', - fn: flip, - requiresIfExists: ['offset'], - data: { - _skip: false, - }, - } - - function getSideOffsets(overflow, rect, preventedOffsets) { - if (preventedOffsets === void 0) { - preventedOffsets = { - x: 0, - y: 0, - } - } - - return { - top: overflow.top - rect.height - preventedOffsets.y, - right: overflow.right - rect.width + preventedOffsets.x, - bottom: overflow.bottom - rect.height + preventedOffsets.y, - left: overflow.left - rect.width - preventedOffsets.x, - } - } - - function isAnySideFullyClipped(overflow) { - return [top, right, bottom, left].some(function (side) { - return overflow[side] >= 0 - }) - } - - function hide(_ref) { - var state = _ref.state, - name = _ref.name - var referenceRect = state.rects.reference - var popperRect = state.rects.popper - var preventedOffsets = state.modifiersData.preventOverflow - var referenceOverflow = detectOverflow(state, { - elementContext: 'reference', - }) - var popperAltOverflow = detectOverflow(state, { - altBoundary: true, - }) - var referenceClippingOffsets = getSideOffsets( - referenceOverflow, - referenceRect - ) - var popperEscapeOffsets = getSideOffsets( - popperAltOverflow, - popperRect, - preventedOffsets - ) - var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets) - var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets) - state.modifiersData[name] = { - referenceClippingOffsets: referenceClippingOffsets, - popperEscapeOffsets: popperEscapeOffsets, - isReferenceHidden: isReferenceHidden, - hasPopperEscaped: hasPopperEscaped, - } - state.attributes.popper = Object.assign({}, state.attributes.popper, { - 'data-popper-reference-hidden': isReferenceHidden, - 'data-popper-escaped': hasPopperEscaped, - }) - } // eslint-disable-next-line import/no-unused-modules - - var hide$1 = { - name: 'hide', - enabled: true, - phase: 'main', - requiresIfExists: ['preventOverflow'], - fn: hide, - } - - function distanceAndSkiddingToXY(placement, rects, offset) { - var basePlacement = getBasePlacement(placement) - var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1 - - var _ref = - typeof offset === 'function' - ? offset( - Object.assign({}, rects, { - placement: placement, - }) - ) - : offset, - skidding = _ref[0], - distance = _ref[1] - - skidding = skidding || 0 - distance = (distance || 0) * invertDistance - return [left, right].indexOf(basePlacement) >= 0 - ? { - x: distance, - y: skidding, - } - : { - x: skidding, - y: distance, - } - } - - function offset(_ref2) { - var state = _ref2.state, - options = _ref2.options, - name = _ref2.name - var _options$offset = options.offset, - offset = _options$offset === void 0 ? [0, 0] : _options$offset - var data = placements.reduce(function (acc, placement) { - acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset) - return acc - }, {}) - var _data$state$placement = data[state.placement], - x = _data$state$placement.x, - y = _data$state$placement.y - - if (state.modifiersData.popperOffsets != null) { - state.modifiersData.popperOffsets.x += x - state.modifiersData.popperOffsets.y += y - } - - state.modifiersData[name] = data - } // eslint-disable-next-line import/no-unused-modules - - var offset$1 = { - name: 'offset', - enabled: true, - phase: 'main', - requires: ['popperOffsets'], - fn: offset, - } - - function popperOffsets(_ref) { - var state = _ref.state, - name = _ref.name - // Offsets are the actual position the popper needs to have to be - // properly positioned near its reference element - // This is the most basic placement, and will be adjusted by - // the modifiers in the next step - state.modifiersData[name] = computeOffsets({ - reference: state.rects.reference, - element: state.rects.popper, - strategy: 'absolute', - placement: state.placement, - }) - } // eslint-disable-next-line import/no-unused-modules - - var popperOffsets$1 = { - name: 'popperOffsets', - enabled: true, - phase: 'read', - fn: popperOffsets, - data: {}, - } - - function getAltAxis(axis) { - return axis === 'x' ? 'y' : 'x' - } - - function preventOverflow(_ref) { - var state = _ref.state, - options = _ref.options, - name = _ref.name - var _options$mainAxis = options.mainAxis, - checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, - _options$altAxis = options.altAxis, - checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, - boundary = options.boundary, - rootBoundary = options.rootBoundary, - altBoundary = options.altBoundary, - padding = options.padding, - _options$tether = options.tether, - tether = _options$tether === void 0 ? true : _options$tether, - _options$tetherOffset = options.tetherOffset, - tetherOffset = - _options$tetherOffset === void 0 ? 0 : _options$tetherOffset - var overflow = detectOverflow(state, { - boundary: boundary, - rootBoundary: rootBoundary, - padding: padding, - altBoundary: altBoundary, - }) - var basePlacement = getBasePlacement(state.placement) - var variation = getVariation(state.placement) - var isBasePlacement = !variation - var mainAxis = getMainAxisFromPlacement(basePlacement) - var altAxis = getAltAxis(mainAxis) - var popperOffsets = state.modifiersData.popperOffsets - var referenceRect = state.rects.reference - var popperRect = state.rects.popper - var tetherOffsetValue = - typeof tetherOffset === 'function' - ? tetherOffset( - Object.assign({}, state.rects, { - placement: state.placement, - }) - ) - : tetherOffset - var normalizedTetherOffsetValue = - typeof tetherOffsetValue === 'number' - ? { - mainAxis: tetherOffsetValue, - altAxis: tetherOffsetValue, - } - : Object.assign( - { - mainAxis: 0, - altAxis: 0, - }, - tetherOffsetValue - ) - var offsetModifierState = state.modifiersData.offset - ? state.modifiersData.offset[state.placement] - : null - var data = { - x: 0, - y: 0, - } - - if (!popperOffsets) { - return - } - - if (checkMainAxis) { - var _offsetModifierState$ - - var mainSide = mainAxis === 'y' ? top : left - var altSide = mainAxis === 'y' ? bottom : right - var len = mainAxis === 'y' ? 'height' : 'width' - var offset = popperOffsets[mainAxis] - var min$1 = offset + overflow[mainSide] - var max$1 = offset - overflow[altSide] - var additive = tether ? -popperRect[len] / 2 : 0 - var minLen = variation === start ? referenceRect[len] : popperRect[len] - var maxLen = variation === start ? -popperRect[len] : -referenceRect[len] // We need to include the arrow in the calculation so the arrow doesn't go - // outside the reference bounds - - var arrowElement = state.elements.arrow - var arrowRect = - tether && arrowElement - ? getLayoutRect(arrowElement) - : { - width: 0, - height: 0, - } - var arrowPaddingObject = state.modifiersData['arrow#persistent'] - ? state.modifiersData['arrow#persistent'].padding - : getFreshSideObject() - var arrowPaddingMin = arrowPaddingObject[mainSide] - var arrowPaddingMax = arrowPaddingObject[altSide] // If the reference length is smaller than the arrow length, we don't want - // to include its full size in the calculation. If the reference is small - // and near the edge of a boundary, the popper can overflow even if the - // reference is not overflowing as well (e.g. virtual elements with no - // width or height) - - var arrowLen = within(0, referenceRect[len], arrowRect[len]) - var minOffset = isBasePlacement - ? referenceRect[len] / 2 - - additive - - arrowLen - - arrowPaddingMin - - normalizedTetherOffsetValue.mainAxis - : minLen - - arrowLen - - arrowPaddingMin - - normalizedTetherOffsetValue.mainAxis - var maxOffset = isBasePlacement - ? -referenceRect[len] / 2 + - additive + - arrowLen + - arrowPaddingMax + - normalizedTetherOffsetValue.mainAxis - : maxLen + - arrowLen + - arrowPaddingMax + - normalizedTetherOffsetValue.mainAxis - var arrowOffsetParent = - state.elements.arrow && getOffsetParent(state.elements.arrow) - var clientOffset = arrowOffsetParent - ? mainAxis === 'y' - ? arrowOffsetParent.clientTop || 0 - : arrowOffsetParent.clientLeft || 0 - : 0 - var offsetModifierValue = - (_offsetModifierState$ = - offsetModifierState == null - ? void 0 - : offsetModifierState[mainAxis]) != null - ? _offsetModifierState$ - : 0 - var tetherMin = offset + minOffset - offsetModifierValue - clientOffset - var tetherMax = offset + maxOffset - offsetModifierValue - var preventedOffset = within( - tether ? min(min$1, tetherMin) : min$1, - offset, - tether ? max(max$1, tetherMax) : max$1 - ) - popperOffsets[mainAxis] = preventedOffset - data[mainAxis] = preventedOffset - offset - } - - if (checkAltAxis) { - var _offsetModifierState$2 - - var _mainSide = mainAxis === 'x' ? top : left - - var _altSide = mainAxis === 'x' ? bottom : right - - var _offset = popperOffsets[altAxis] - - var _len = altAxis === 'y' ? 'height' : 'width' - - var _min = _offset + overflow[_mainSide] - - var _max = _offset - overflow[_altSide] - - var isOriginSide = [top, left].indexOf(basePlacement) !== -1 - - var _offsetModifierValue = - (_offsetModifierState$2 = - offsetModifierState == null - ? void 0 - : offsetModifierState[altAxis]) != null - ? _offsetModifierState$2 - : 0 - - var _tetherMin = isOriginSide - ? _min - : _offset - - referenceRect[_len] - - popperRect[_len] - - _offsetModifierValue + - normalizedTetherOffsetValue.altAxis - - var _tetherMax = isOriginSide - ? _offset + - referenceRect[_len] + - popperRect[_len] - - _offsetModifierValue - - normalizedTetherOffsetValue.altAxis - : _max - - var _preventedOffset = - tether && isOriginSide - ? withinMaxClamp(_tetherMin, _offset, _tetherMax) - : within( - tether ? _tetherMin : _min, - _offset, - tether ? _tetherMax : _max - ) - - popperOffsets[altAxis] = _preventedOffset - data[altAxis] = _preventedOffset - _offset - } - - state.modifiersData[name] = data - } // eslint-disable-next-line import/no-unused-modules - - var preventOverflow$1 = { - name: 'preventOverflow', - enabled: true, - phase: 'main', - fn: preventOverflow, - requiresIfExists: ['offset'], - } - - function getHTMLElementScroll(element) { - return { - scrollLeft: element.scrollLeft, - scrollTop: element.scrollTop, - } - } - - function getNodeScroll(node) { - if (node === getWindow(node) || !isHTMLElement(node)) { - return getWindowScroll(node) - } else { - return getHTMLElementScroll(node) - } - } - - function isElementScaled(element) { - var rect = element.getBoundingClientRect() - var scaleX = round(rect.width) / element.offsetWidth || 1 - var scaleY = round(rect.height) / element.offsetHeight || 1 - return scaleX !== 1 || scaleY !== 1 - } // Returns the composite rect of an element relative to its offsetParent. - // Composite means it takes into account transforms as well as layout. - - function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { - if (isFixed === void 0) { - isFixed = false - } - - var isOffsetParentAnElement = isHTMLElement(offsetParent) - var offsetParentIsScaled = - isHTMLElement(offsetParent) && isElementScaled(offsetParent) - var documentElement = getDocumentElement(offsetParent) - var rect = getBoundingClientRect( - elementOrVirtualElement, - offsetParentIsScaled - ) - var scroll = { - scrollLeft: 0, - scrollTop: 0, - } - var offsets = { - x: 0, - y: 0, - } - - if (isOffsetParentAnElement || (!isOffsetParentAnElement && !isFixed)) { - if ( - getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078 - isScrollParent(documentElement) - ) { - scroll = getNodeScroll(offsetParent) - } - - if (isHTMLElement(offsetParent)) { - offsets = getBoundingClientRect(offsetParent, true) - offsets.x += offsetParent.clientLeft - offsets.y += offsetParent.clientTop - } else if (documentElement) { - offsets.x = getWindowScrollBarX(documentElement) - } - } - - return { - x: rect.left + scroll.scrollLeft - offsets.x, - y: rect.top + scroll.scrollTop - offsets.y, - width: rect.width, - height: rect.height, - } - } - - function order(modifiers) { - var map = new Map() - var visited = new Set() - var result = [] - modifiers.forEach(function (modifier) { - map.set(modifier.name, modifier) - }) // On visiting object, check for its dependencies and visit them recursively - - function sort(modifier) { - visited.add(modifier.name) - var requires = [].concat( - modifier.requires || [], - modifier.requiresIfExists || [] - ) - requires.forEach(function (dep) { - if (!visited.has(dep)) { - var depModifier = map.get(dep) - - if (depModifier) { - sort(depModifier) - } - } - }) - result.push(modifier) - } - - modifiers.forEach(function (modifier) { - if (!visited.has(modifier.name)) { - // check for visited object - sort(modifier) - } - }) - return result - } - - function orderModifiers(modifiers) { - // order based on dependencies - var orderedModifiers = order(modifiers) // order based on phase - - return modifierPhases.reduce(function (acc, phase) { - return acc.concat( - orderedModifiers.filter(function (modifier) { - return modifier.phase === phase - }) - ) - }, []) - } - - function debounce(fn) { - var pending - return function () { - if (!pending) { - pending = new Promise(function (resolve) { - Promise.resolve().then(function () { - pending = undefined - resolve(fn()) - }) - }) - } - - return pending - } - } - - function format(str) { - for ( - var _len = arguments.length, - args = new Array(_len > 1 ? _len - 1 : 0), - _key = 1; - _key < _len; - _key++ - ) { - args[_key - 1] = arguments[_key] - } - - return [].concat(args).reduce(function (p, c) { - return p.replace(/%s/, c) - }, str) - } - - var INVALID_MODIFIER_ERROR = - 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s' - var MISSING_DEPENDENCY_ERROR = - 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available' - var VALID_PROPERTIES = [ - 'name', - 'enabled', - 'phase', - 'fn', - 'effect', - 'requires', - 'options', - ] - function validateModifiers(modifiers) { - modifiers.forEach(function (modifier) { - ;[] - .concat(Object.keys(modifier), VALID_PROPERTIES) // IE11-compatible replacement for `new Set(iterable)` - .filter(function (value, index, self) { - return self.indexOf(value) === index - }) - .forEach(function (key) { - switch (key) { - case 'name': - if (typeof modifier.name !== 'string') { - console.error( - format( - INVALID_MODIFIER_ERROR, - String(modifier.name), - '"name"', - '"string"', - '"' + String(modifier.name) + '"' - ) - ) - } - - break - - case 'enabled': - if (typeof modifier.enabled !== 'boolean') { - console.error( - format( - INVALID_MODIFIER_ERROR, - modifier.name, - '"enabled"', - '"boolean"', - '"' + String(modifier.enabled) + '"' - ) - ) - } - - break - - case 'phase': - if (modifierPhases.indexOf(modifier.phase) < 0) { - console.error( - format( - INVALID_MODIFIER_ERROR, - modifier.name, - '"phase"', - 'either ' + modifierPhases.join(', '), - '"' + String(modifier.phase) + '"' - ) - ) - } - - break - - case 'fn': - if (typeof modifier.fn !== 'function') { - console.error( - format( - INVALID_MODIFIER_ERROR, - modifier.name, - '"fn"', - '"function"', - '"' + String(modifier.fn) + '"' - ) - ) - } - - break - - case 'effect': - if ( - modifier.effect != null && - typeof modifier.effect !== 'function' - ) { - console.error( - format( - INVALID_MODIFIER_ERROR, - modifier.name, - '"effect"', - '"function"', - '"' + String(modifier.fn) + '"' - ) - ) - } - - break - - case 'requires': - if ( - modifier.requires != null && - !Array.isArray(modifier.requires) - ) { - console.error( - format( - INVALID_MODIFIER_ERROR, - modifier.name, - '"requires"', - '"array"', - '"' + String(modifier.requires) + '"' - ) - ) - } - - break - - case 'requiresIfExists': - if (!Array.isArray(modifier.requiresIfExists)) { - console.error( - format( - INVALID_MODIFIER_ERROR, - modifier.name, - '"requiresIfExists"', - '"array"', - '"' + String(modifier.requiresIfExists) + '"' - ) - ) - } - - break - - case 'options': - case 'data': - break - - default: - console.error( - 'PopperJS: an invalid property has been provided to the "' + - modifier.name + - '" modifier, valid properties are ' + - VALID_PROPERTIES.map(function (s) { - return '"' + s + '"' - }).join(', ') + - '; but "' + - key + - '" was provided.' - ) - } - - modifier.requires && - modifier.requires.forEach(function (requirement) { - if ( - modifiers.find(function (mod) { - return mod.name === requirement - }) == null - ) { - console.error( - format( - MISSING_DEPENDENCY_ERROR, - String(modifier.name), - requirement, - requirement - ) - ) - } - }) - }) - }) - } - - function uniqueBy(arr, fn) { - var identifiers = new Set() - return arr.filter(function (item) { - var identifier = fn(item) - - if (!identifiers.has(identifier)) { - identifiers.add(identifier) - return true - } - }) - } - - function mergeByName(modifiers) { - var merged = modifiers.reduce(function (merged, current) { - var existing = merged[current.name] - merged[current.name] = existing - ? Object.assign({}, existing, current, { - options: Object.assign({}, existing.options, current.options), - data: Object.assign({}, existing.data, current.data), - }) - : current - return merged - }, {}) // IE11 does not support Object.values - - return Object.keys(merged).map(function (key) { - return merged[key] - }) - } - - var INVALID_ELEMENT_ERROR = - 'Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.' - var INFINITE_LOOP_ERROR = - 'Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.' - var DEFAULT_OPTIONS = { - placement: 'bottom', - modifiers: [], - strategy: 'absolute', - } - - function areValidElements() { - for ( - var _len = arguments.length, args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key] - } - - return !args.some(function (element) { - return !(element && typeof element.getBoundingClientRect === 'function') - }) - } - - function popperGenerator(generatorOptions) { - if (generatorOptions === void 0) { - generatorOptions = {} - } - - var _generatorOptions = generatorOptions, - _generatorOptions$def = _generatorOptions.defaultModifiers, - defaultModifiers = - _generatorOptions$def === void 0 ? [] : _generatorOptions$def, - _generatorOptions$def2 = _generatorOptions.defaultOptions, - defaultOptions = - _generatorOptions$def2 === void 0 - ? DEFAULT_OPTIONS - : _generatorOptions$def2 - return function createPopper(reference, popper, options) { - if (options === void 0) { - options = defaultOptions - } - - var state = { - placement: 'bottom', - orderedModifiers: [], - options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), - modifiersData: {}, - elements: { - reference: reference, - popper: popper, - }, - attributes: {}, - styles: {}, - } - var effectCleanupFns = [] - var isDestroyed = false - var instance = { - state: state, - setOptions: function setOptions(setOptionsAction) { - var options = - typeof setOptionsAction === 'function' - ? setOptionsAction(state.options) - : setOptionsAction - cleanupModifierEffects() - state.options = Object.assign( - {}, - defaultOptions, - state.options, - options - ) - state.scrollParents = { - reference: isElement(reference) - ? listScrollParents(reference) - : reference.contextElement - ? listScrollParents(reference.contextElement) - : [], - popper: listScrollParents(popper), - } // Orders the modifiers based on their dependencies and `phase` - // properties - - var orderedModifiers = orderModifiers( - mergeByName([].concat(defaultModifiers, state.options.modifiers)) - ) // Strip out disabled modifiers - - state.orderedModifiers = orderedModifiers.filter(function (m) { - return m.enabled - }) // Validate the provided modifiers so that the consumer will get warned - // if one of the modifiers is invalid for any reason - - { - var modifiers = uniqueBy( - [].concat(orderedModifiers, state.options.modifiers), - function (_ref) { - var name = _ref.name - return name - } - ) - validateModifiers(modifiers) - - if (getBasePlacement(state.options.placement) === auto) { - var flipModifier = state.orderedModifiers.find(function (_ref2) { - var name = _ref2.name - return name === 'flip' - }) - - if (!flipModifier) { - console.error( - [ - 'Popper: "auto" placements require the "flip" modifier be', - 'present and enabled to work.', - ].join(' ') - ) - } - } - - var _getComputedStyle = getComputedStyle(popper), - marginTop = _getComputedStyle.marginTop, - marginRight = _getComputedStyle.marginRight, - marginBottom = _getComputedStyle.marginBottom, - marginLeft = _getComputedStyle.marginLeft // We no longer take into account `margins` on the popper, and it can - // cause bugs with positioning, so we'll warn the consumer - - if ( - [marginTop, marginRight, marginBottom, marginLeft].some(function ( - margin - ) { - return parseFloat(margin) - }) - ) { - console.warn( - [ - 'Popper: CSS "margin" styles cannot be used to apply padding', - 'between the popper and its reference element or boundary.', - 'To replicate margin, use the `offset` modifier, as well as', - 'the `padding` option in the `preventOverflow` and `flip`', - 'modifiers.', - ].join(' ') - ) - } - } - - runModifierEffects() - return instance.update() - }, - // Sync update – it will always be executed, even if not necessary. This - // is useful for low frequency updates where sync behavior simplifies the - // logic. - // For high frequency updates (e.g. `resize` and `scroll` events), always - // prefer the async Popper#update method - forceUpdate: function forceUpdate() { - if (isDestroyed) { - return - } - - var _state$elements = state.elements, - reference = _state$elements.reference, - popper = _state$elements.popper // Don't proceed if `reference` or `popper` are not valid elements - // anymore - - if (!areValidElements(reference, popper)) { - { - console.error(INVALID_ELEMENT_ERROR) - } - - return - } // Store the reference and popper rects to be read by modifiers - - state.rects = { - reference: getCompositeRect( - reference, - getOffsetParent(popper), - state.options.strategy === 'fixed' - ), - popper: getLayoutRect(popper), - } // Modifiers have the ability to reset the current update cycle. The - // most common use case for this is the `flip` modifier changing the - // placement, which then needs to re-run all the modifiers, because the - // logic was previously ran for the previous placement and is therefore - // stale/incorrect - - state.reset = false - state.placement = state.options.placement // On each update cycle, the `modifiersData` property for each modifier - // is filled with the initial data specified by the modifier. This means - // it doesn't persist and is fresh on each update. - // To ensure persistent data, use `${name}#persistent` - - state.orderedModifiers.forEach(function (modifier) { - return (state.modifiersData[modifier.name] = Object.assign( - {}, - modifier.data - )) - }) - var __debug_loops__ = 0 - - for (var index = 0; index < state.orderedModifiers.length; index++) { - { - __debug_loops__ += 1 - - if (__debug_loops__ > 100) { - console.error(INFINITE_LOOP_ERROR) - break - } - } - - if (state.reset === true) { - state.reset = false - index = -1 - continue - } - - var _state$orderedModifie = state.orderedModifiers[index], - fn = _state$orderedModifie.fn, - _state$orderedModifie2 = _state$orderedModifie.options, - _options = - _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, - name = _state$orderedModifie.name - - if (typeof fn === 'function') { - state = - fn({ - state: state, - options: _options, - name: name, - instance: instance, - }) || state - } - } - }, - // Async and optimistically optimized update – it will not be executed if - // not necessary (debounced to run at most once-per-tick) - update: debounce(function () { - return new Promise(function (resolve) { - instance.forceUpdate() - resolve(state) - }) - }), - destroy: function destroy() { - cleanupModifierEffects() - isDestroyed = true - }, - } - - if (!areValidElements(reference, popper)) { - { - console.error(INVALID_ELEMENT_ERROR) - } - - return instance - } - - instance.setOptions(options).then(function (state) { - if (!isDestroyed && options.onFirstUpdate) { - options.onFirstUpdate(state) - } - }) // Modifiers have the ability to execute arbitrary code before the first - // update cycle runs. They will be executed in the same order as the update - // cycle. This is useful when a modifier adds some persistent data that - // other modifiers need to use, but the modifier is run after the dependent - // one. - - function runModifierEffects() { - state.orderedModifiers.forEach(function (_ref3) { - var name = _ref3.name, - _ref3$options = _ref3.options, - options = _ref3$options === void 0 ? {} : _ref3$options, - effect = _ref3.effect - - if (typeof effect === 'function') { - var cleanupFn = effect({ - state: state, - name: name, - instance: instance, - options: options, - }) - - var noopFn = function noopFn() {} - - effectCleanupFns.push(cleanupFn || noopFn) - } - }) - } - - function cleanupModifierEffects() { - effectCleanupFns.forEach(function (fn) { - return fn() - }) - effectCleanupFns = [] - } - - return instance - } - } - - // This is b/c the Popper lib is all esm files, and would break in a common js only environment - - var createPopper = popperGenerator({ - defaultModifiers: [ - hide$1, - popperOffsets$1, - computeStyles$1, - eventListeners, - offset$1, - flip$1, - preventOverflow$1, - arrow$1, - ], - }) - - var initialPopperStyles = function initialPopperStyles(position) { - return { - position: position, - top: '0', - left: '0', - opacity: '0', - pointerEvents: 'none', - } - } - - var disabledApplyStylesModifier = { - name: 'applyStyles', - enabled: false, - } // until docjs supports type exports... - - var ariaDescribedByModifier = { - name: 'ariaDescribedBy', - enabled: true, - phase: 'afterWrite', - effect: function effect(_ref) { - var state = _ref.state - return function () { - var _state$elements = state.elements, - reference = _state$elements.reference, - popper = _state$elements.popper - - if ('removeAttribute' in reference) { - var ids = (reference.getAttribute('aria-describedby') || '') - .split(',') - .filter(function (id) { - return id.trim() !== popper.id - }) - if (!ids.length) reference.removeAttribute('aria-describedby') - else reference.setAttribute('aria-describedby', ids.join(',')) - } - } - }, - fn: function fn(_ref2) { - var _popper$getAttribute - - var state = _ref2.state - var _state$elements2 = state.elements, - popper = _state$elements2.popper, - reference = _state$elements2.reference - var role = - (_popper$getAttribute = popper.getAttribute('role')) == null - ? void 0 - : _popper$getAttribute.toLowerCase() - - if (popper.id && role === 'tooltip' && 'setAttribute' in reference) { - var ids = reference.getAttribute('aria-describedby') - - if (ids && ids.split(',').indexOf(popper.id) !== -1) { - return - } - - reference.setAttribute( - 'aria-describedby', - ids ? ids + ',' + popper.id : popper.id - ) - } - }, - } - var EMPTY_MODIFIERS = [] - /** - * Position an element relative some reference element using Popper.js - * - * @param referenceElement - * @param popperElement - * @param {object} options - * @param {object=} options.modifiers Popper.js modifiers - * @param {boolean=} options.enabled toggle the popper functionality on/off - * @param {string=} options.placement The popper element placement relative to the reference element - * @param {string=} options.strategy the positioning strategy - * @param {boolean=} options.eventsEnabled have Popper listen on window resize events to reposition the element - * @param {function=} options.onCreate called when the popper is created - * @param {function=} options.onUpdate called when the popper is updated - * - * @returns {UsePopperState} The popper state - */ - - function usePopper(referenceElement, popperElement, _temp) { - var _ref3 = _temp === void 0 ? {} : _temp, - _ref3$enabled = _ref3.enabled, - enabled = _ref3$enabled === void 0 ? true : _ref3$enabled, - _ref3$placement = _ref3.placement, - placement = _ref3$placement === void 0 ? 'bottom' : _ref3$placement, - _ref3$strategy = _ref3.strategy, - strategy = _ref3$strategy === void 0 ? 'absolute' : _ref3$strategy, - _ref3$modifiers = _ref3.modifiers, - modifiers = - _ref3$modifiers === void 0 ? EMPTY_MODIFIERS : _ref3$modifiers, - config = _objectWithoutPropertiesLoose$1(_ref3, [ - 'enabled', - 'placement', - 'strategy', - 'modifiers', - ]) - - var popperInstanceRef = react.exports.useRef() - var update = react.exports.useCallback(function () { - var _popperInstanceRef$cu - - ;(_popperInstanceRef$cu = popperInstanceRef.current) == null - ? void 0 - : _popperInstanceRef$cu.update() - }, []) - var forceUpdate = react.exports.useCallback(function () { - var _popperInstanceRef$cu2 - - ;(_popperInstanceRef$cu2 = popperInstanceRef.current) == null - ? void 0 - : _popperInstanceRef$cu2.forceUpdate() - }, []) - - var _useSafeState = useSafeState( - react.exports.useState({ - placement: placement, - update: update, - forceUpdate: forceUpdate, - attributes: {}, - styles: { - popper: initialPopperStyles(strategy), - arrow: {}, - }, - }) - ), - popperState = _useSafeState[0], - setState = _useSafeState[1] - - var updateModifier = react.exports.useMemo( - function () { - return { - name: 'updateStateModifier', - enabled: true, - phase: 'write', - requires: ['computeStyles'], - fn: function fn(_ref4) { - var state = _ref4.state - var styles = {} - var attributes = {} - Object.keys(state.elements).forEach(function (element) { - styles[element] = state.styles[element] - attributes[element] = state.attributes[element] - }) - setState({ - state: state, - styles: styles, - attributes: attributes, - update: update, - forceUpdate: forceUpdate, - placement: state.placement, - }) - }, - } - }, - [update, forceUpdate, setState] - ) - react.exports.useEffect( - function () { - if (!popperInstanceRef.current || !enabled) return - popperInstanceRef.current.setOptions({ - placement: placement, - strategy: strategy, - modifiers: [].concat(modifiers, [ - updateModifier, - disabledApplyStylesModifier, - ]), - }) // intentionally NOT re-running on new modifiers - // eslint-disable-next-line react-hooks/exhaustive-deps - }, - [strategy, placement, updateModifier, enabled] - ) - react.exports.useEffect( - function () { - if (!enabled || referenceElement == null || popperElement == null) { - return undefined - } - - popperInstanceRef.current = createPopper( - referenceElement, - popperElement, - _extends({}, config, { - placement: placement, - strategy: strategy, - modifiers: [].concat(modifiers, [ - ariaDescribedByModifier, - updateModifier, - ]), - }) - ) - return function () { - if (popperInstanceRef.current != null) { - popperInstanceRef.current.destroy() - popperInstanceRef.current = undefined - setState(function (s) { - return _extends({}, s, { - attributes: {}, - styles: { - popper: initialPopperStyles(strategy), - }, - }) - }) - } - } // This is only run once to _create_ the popper - // eslint-disable-next-line react-hooks/exhaustive-deps - }, - [enabled, referenceElement, popperElement] - ) - return popperState - } - - /** - * A `removeEventListener` ponyfill - * - * @param node the element - * @param eventName the event name - * @param handle the handler - * @param options event options - */ - function removeEventListener(node, eventName, handler, options) { - var capture = - options && typeof options !== 'boolean' ? options.capture : options - node.removeEventListener(eventName, handler, capture) - - if (handler.__once) { - node.removeEventListener(eventName, handler.__once, capture) - } - } - - function listen(node, eventName, handler, options) { - addEventListener$1(node, eventName, handler, options) - return function () { - removeEventListener(node, eventName, handler, options) - } - } - - /** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - var warning = function () {} - - { - var printWarning = function printWarning(format, args) { - var len = arguments.length - args = new Array(len > 1 ? len - 1 : 0) - for (var key = 1; key < len; key++) { - args[key - 1] = arguments[key] - } - var argIndex = 0 - var message = - 'Warning: ' + - format.replace(/%s/g, function () { - return args[argIndex++] - }) - if (typeof console !== 'undefined') { - console.error(message) - } - try { - // --- Welcome to debugging React --- - // This error was thrown as a convenience so that you can use this stack - // to find the callsite that caused this warning to fire. - throw new Error(message) - } catch (x) {} - } - - warning = function (condition, format, args) { - var len = arguments.length - args = new Array(len > 2 ? len - 2 : 0) - for (var key = 2; key < len; key++) { - args[key - 2] = arguments[key] - } - if (format === undefined) { - throw new Error( - '`warning(condition, format, ...args)` requires a warning ' + - 'message argument' - ) - } - if (!condition) { - printWarning.apply(null, [format].concat(args)) - } - } - } - - var warning_1 = warning - - var reactDom = { exports: {} } - - var reactDom_development = {} - - var scheduler = { exports: {} } - - var scheduler_development = {} - - /** @license React v0.20.2 - * scheduler.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - ;(function (exports) { - { - ;(function () { - var enableSchedulerDebugging = false - var enableProfiling = false - - var requestHostCallback - var requestHostTimeout - var cancelHostTimeout - var requestPaint - var hasPerformanceNow = - typeof performance === 'object' && - typeof performance.now === 'function' - - if (hasPerformanceNow) { - var localPerformance = performance - - exports.unstable_now = function () { - return localPerformance.now() - } - } else { - var localDate = Date - var initialTime = localDate.now() - - exports.unstable_now = function () { - return localDate.now() - initialTime - } - } - - if ( - // If Scheduler runs in a non-DOM environment, it falls back to a naive - // implementation using setTimeout. - typeof window === 'undefined' || // Check if MessageChannel is supported, too. - typeof MessageChannel !== 'function' - ) { - // If this accidentally gets imported in a non-browser environment, e.g. JavaScriptCore, - // fallback to a naive implementation. - var _callback = null - var _timeoutID = null - - var _flushCallback = function () { - if (_callback !== null) { - try { - var currentTime = exports.unstable_now() - var hasRemainingTime = true - - _callback(hasRemainingTime, currentTime) - - _callback = null - } catch (e) { - setTimeout(_flushCallback, 0) - throw e - } - } - } - - requestHostCallback = function (cb) { - if (_callback !== null) { - // Protect against re-entrancy. - setTimeout(requestHostCallback, 0, cb) - } else { - _callback = cb - setTimeout(_flushCallback, 0) - } - } - - requestHostTimeout = function (cb, ms) { - _timeoutID = setTimeout(cb, ms) - } - - cancelHostTimeout = function () { - clearTimeout(_timeoutID) - } - - exports.unstable_shouldYield = function () { - return false - } - - requestPaint = exports.unstable_forceFrameRate = function () {} - } else { - // Capture local references to native APIs, in case a polyfill overrides them. - var _setTimeout = window.setTimeout - var _clearTimeout = window.clearTimeout - - if (typeof console !== 'undefined') { - // TODO: Scheduler no longer requires these methods to be polyfilled. But - // maybe we want to continue warning if they don't exist, to preserve the - // option to rely on it in the future? - var requestAnimationFrame = window.requestAnimationFrame - var cancelAnimationFrame = window.cancelAnimationFrame - - if (typeof requestAnimationFrame !== 'function') { - // Using console['error'] to evade Babel and ESLint - console['error']( - "This browser doesn't support requestAnimationFrame. " + - 'Make sure that you load a ' + - 'polyfill in older browsers. https://reactjs.org/link/react-polyfills' - ) - } - - if (typeof cancelAnimationFrame !== 'function') { - // Using console['error'] to evade Babel and ESLint - console['error']( - "This browser doesn't support cancelAnimationFrame. " + - 'Make sure that you load a ' + - 'polyfill in older browsers. https://reactjs.org/link/react-polyfills' - ) - } - } - - var isMessageLoopRunning = false - var scheduledHostCallback = null - var taskTimeoutID = -1 // Scheduler periodically yields in case there is other work on the main - // thread, like user events. By default, it yields multiple times per frame. - // It does not attempt to align with frame boundaries, since most tasks don't - // need to be frame aligned; for those that do, use requestAnimationFrame. - - var yieldInterval = 5 - var deadline = 0 // TODO: Make this configurable - - { - // `isInputPending` is not available. Since we have no way of knowing if - // there's pending input, always yield at the end of the frame. - exports.unstable_shouldYield = function () { - return exports.unstable_now() >= deadline - } // Since we yield every frame regardless, `requestPaint` has no effect. - - requestPaint = function () {} - } - - exports.unstable_forceFrameRate = function (fps) { - if (fps < 0 || fps > 125) { - // Using console['error'] to evade Babel and ESLint - console['error']( - 'forceFrameRate takes a positive int between 0 and 125, ' + - 'forcing frame rates higher than 125 fps is not supported' - ) - return - } - - if (fps > 0) { - yieldInterval = Math.floor(1000 / fps) - } else { - // reset the framerate - yieldInterval = 5 - } - } - - var performWorkUntilDeadline = function () { - if (scheduledHostCallback !== null) { - var currentTime = exports.unstable_now() // Yield after `yieldInterval` ms, regardless of where we are in the vsync - // cycle. This means there's always time remaining at the beginning of - // the message event. - - deadline = currentTime + yieldInterval - var hasTimeRemaining = true - - try { - var hasMoreWork = scheduledHostCallback( - hasTimeRemaining, - currentTime - ) - - if (!hasMoreWork) { - isMessageLoopRunning = false - scheduledHostCallback = null - } else { - // If there's more work, schedule the next message event at the end - // of the preceding one. - port.postMessage(null) - } - } catch (error) { - // If a scheduler task throws, exit the current browser task so the - // error can be observed. - port.postMessage(null) - throw error - } - } else { - isMessageLoopRunning = false - } // Yielding to the browser will give it a chance to paint, so we can - } - - var channel = new MessageChannel() - var port = channel.port2 - channel.port1.onmessage = performWorkUntilDeadline - - requestHostCallback = function (callback) { - scheduledHostCallback = callback - - if (!isMessageLoopRunning) { - isMessageLoopRunning = true - port.postMessage(null) - } - } - - requestHostTimeout = function (callback, ms) { - taskTimeoutID = _setTimeout(function () { - callback(exports.unstable_now()) - }, ms) - } - - cancelHostTimeout = function () { - _clearTimeout(taskTimeoutID) - - taskTimeoutID = -1 - } - } - - function push(heap, node) { - var index = heap.length - heap.push(node) - siftUp(heap, node, index) - } - function peek(heap) { - var first = heap[0] - return first === undefined ? null : first - } - function pop(heap) { - var first = heap[0] - - if (first !== undefined) { - var last = heap.pop() - - if (last !== first) { - heap[0] = last - siftDown(heap, last, 0) - } - - return first - } else { - return null - } - } - - function siftUp(heap, node, i) { - var index = i - - while (true) { - var parentIndex = (index - 1) >>> 1 - var parent = heap[parentIndex] - - if (parent !== undefined && compare(parent, node) > 0) { - // The parent is larger. Swap positions. - heap[parentIndex] = node - heap[index] = parent - index = parentIndex - } else { - // The parent is smaller. Exit. - return - } - } - } - - function siftDown(heap, node, i) { - var index = i - var length = heap.length - - while (index < length) { - var leftIndex = (index + 1) * 2 - 1 - var left = heap[leftIndex] - var rightIndex = leftIndex + 1 - var right = heap[rightIndex] // If the left or right node is smaller, swap with the smaller of those. - - if (left !== undefined && compare(left, node) < 0) { - if (right !== undefined && compare(right, left) < 0) { - heap[index] = right - heap[rightIndex] = node - index = rightIndex - } else { - heap[index] = left - heap[leftIndex] = node - index = leftIndex - } - } else if (right !== undefined && compare(right, node) < 0) { - heap[index] = right - heap[rightIndex] = node - index = rightIndex - } else { - // Neither child is smaller. Exit. - return - } - } - } - - function compare(a, b) { - // Compare sort index first, then task id. - var diff = a.sortIndex - b.sortIndex - return diff !== 0 ? diff : a.id - b.id - } - - // TODO: Use symbols? - var ImmediatePriority = 1 - var UserBlockingPriority = 2 - var NormalPriority = 3 - var LowPriority = 4 - var IdlePriority = 5 - - function markTaskErrored(task, ms) {} - - /* eslint-disable no-var */ - // Math.pow(2, 30) - 1 - // 0b111111111111111111111111111111 - - var maxSigned31BitInt = 1073741823 // Times out immediately - - var IMMEDIATE_PRIORITY_TIMEOUT = -1 // Eventually times out - - var USER_BLOCKING_PRIORITY_TIMEOUT = 250 - var NORMAL_PRIORITY_TIMEOUT = 5000 - var LOW_PRIORITY_TIMEOUT = 10000 // Never times out - - var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt // Tasks are stored on a min heap - - var taskQueue = [] - var timerQueue = [] // Incrementing id counter. Used to maintain insertion order. - - var taskIdCounter = 1 // Pausing the scheduler is useful for debugging. - var currentTask = null - var currentPriorityLevel = NormalPriority // This is set while performing work, to prevent re-entrancy. - - var isPerformingWork = false - var isHostCallbackScheduled = false - var isHostTimeoutScheduled = false - - function advanceTimers(currentTime) { - // Check for tasks that are no longer delayed and add them to the queue. - var timer = peek(timerQueue) - - while (timer !== null) { - if (timer.callback === null) { - // Timer was cancelled. - pop(timerQueue) - } else if (timer.startTime <= currentTime) { - // Timer fired. Transfer to the task queue. - pop(timerQueue) - timer.sortIndex = timer.expirationTime - push(taskQueue, timer) - } else { - // Remaining timers are pending. - return - } - - timer = peek(timerQueue) - } - } - - function handleTimeout(currentTime) { - isHostTimeoutScheduled = false - advanceTimers(currentTime) - - if (!isHostCallbackScheduled) { - if (peek(taskQueue) !== null) { - isHostCallbackScheduled = true - requestHostCallback(flushWork) - } else { - var firstTimer = peek(timerQueue) - - if (firstTimer !== null) { - requestHostTimeout( - handleTimeout, - firstTimer.startTime - currentTime - ) - } - } - } - } - - function flushWork(hasTimeRemaining, initialTime) { - isHostCallbackScheduled = false - - if (isHostTimeoutScheduled) { - // We scheduled a timeout but it's no longer needed. Cancel it. - isHostTimeoutScheduled = false - cancelHostTimeout() - } - - isPerformingWork = true - var previousPriorityLevel = currentPriorityLevel - - try { - var currentTime - if (enableProfiling); - else { - // No catch in prod code path. - return workLoop(hasTimeRemaining, initialTime) - } - } finally { - currentTask = null - currentPriorityLevel = previousPriorityLevel - isPerformingWork = false - } - } - - function workLoop(hasTimeRemaining, initialTime) { - var currentTime = initialTime - advanceTimers(currentTime) - currentTask = peek(taskQueue) - - while (currentTask !== null && !enableSchedulerDebugging) { - if ( - currentTask.expirationTime > currentTime && - (!hasTimeRemaining || exports.unstable_shouldYield()) - ) { - // This currentTask hasn't expired, and we've reached the deadline. - break - } - - var callback = currentTask.callback - - if (typeof callback === 'function') { - currentTask.callback = null - currentPriorityLevel = currentTask.priorityLevel - var didUserCallbackTimeout = - currentTask.expirationTime <= currentTime - - var continuationCallback = callback(didUserCallbackTimeout) - currentTime = exports.unstable_now() - - if (typeof continuationCallback === 'function') { - currentTask.callback = continuationCallback - } else { - if (currentTask === peek(taskQueue)) { - pop(taskQueue) - } - } - - advanceTimers(currentTime) - } else { - pop(taskQueue) - } - - currentTask = peek(taskQueue) - } // Return whether there's additional work - - if (currentTask !== null) { - return true - } else { - var firstTimer = peek(timerQueue) - - if (firstTimer !== null) { - requestHostTimeout( - handleTimeout, - firstTimer.startTime - currentTime - ) - } - - return false - } - } - - function unstable_runWithPriority(priorityLevel, eventHandler) { - switch (priorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - case LowPriority: - case IdlePriority: - break - - default: - priorityLevel = NormalPriority - } - - var previousPriorityLevel = currentPriorityLevel - currentPriorityLevel = priorityLevel - - try { - return eventHandler() - } finally { - currentPriorityLevel = previousPriorityLevel - } - } - - function unstable_next(eventHandler) { - var priorityLevel - - switch (currentPriorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - // Shift down to normal priority - priorityLevel = NormalPriority - break - - default: - // Anything lower than normal priority should remain at the current level. - priorityLevel = currentPriorityLevel - break - } - - var previousPriorityLevel = currentPriorityLevel - currentPriorityLevel = priorityLevel - - try { - return eventHandler() - } finally { - currentPriorityLevel = previousPriorityLevel - } - } - - function unstable_wrapCallback(callback) { - var parentPriorityLevel = currentPriorityLevel - return function () { - // This is a fork of runWithPriority, inlined for performance. - var previousPriorityLevel = currentPriorityLevel - currentPriorityLevel = parentPriorityLevel - - try { - return callback.apply(this, arguments) - } finally { - currentPriorityLevel = previousPriorityLevel - } - } - } - - function unstable_scheduleCallback(priorityLevel, callback, options) { - var currentTime = exports.unstable_now() - var startTime - - if (typeof options === 'object' && options !== null) { - var delay = options.delay - - if (typeof delay === 'number' && delay > 0) { - startTime = currentTime + delay - } else { - startTime = currentTime - } - } else { - startTime = currentTime - } - - var timeout - - switch (priorityLevel) { - case ImmediatePriority: - timeout = IMMEDIATE_PRIORITY_TIMEOUT - break - - case UserBlockingPriority: - timeout = USER_BLOCKING_PRIORITY_TIMEOUT - break - - case IdlePriority: - timeout = IDLE_PRIORITY_TIMEOUT - break - - case LowPriority: - timeout = LOW_PRIORITY_TIMEOUT - break - - case NormalPriority: - default: - timeout = NORMAL_PRIORITY_TIMEOUT - break - } - - var expirationTime = startTime + timeout - var newTask = { - id: taskIdCounter++, - callback: callback, - priorityLevel: priorityLevel, - startTime: startTime, - expirationTime: expirationTime, - sortIndex: -1, - } - - if (startTime > currentTime) { - // This is a delayed task. - newTask.sortIndex = startTime - push(timerQueue, newTask) - - if (peek(taskQueue) === null && newTask === peek(timerQueue)) { - // All tasks are delayed, and this is the task with the earliest delay. - if (isHostTimeoutScheduled) { - // Cancel an existing timeout. - cancelHostTimeout() - } else { - isHostTimeoutScheduled = true - } // Schedule a timeout. - - requestHostTimeout(handleTimeout, startTime - currentTime) - } - } else { - newTask.sortIndex = expirationTime - push(taskQueue, newTask) - // wait until the next time we yield. - - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true - requestHostCallback(flushWork) - } - } - - return newTask - } - - function unstable_pauseExecution() {} - - function unstable_continueExecution() { - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true - requestHostCallback(flushWork) - } - } - - function unstable_getFirstCallbackNode() { - return peek(taskQueue) - } - - function unstable_cancelCallback(task) { - // remove from the queue because you can't remove arbitrary nodes from an - // array based heap, only the first one.) - - task.callback = null - } - - function unstable_getCurrentPriorityLevel() { - return currentPriorityLevel - } - - var unstable_requestPaint = requestPaint - var unstable_Profiling = null - - exports.unstable_IdlePriority = IdlePriority - exports.unstable_ImmediatePriority = ImmediatePriority - exports.unstable_LowPriority = LowPriority - exports.unstable_NormalPriority = NormalPriority - exports.unstable_Profiling = unstable_Profiling - exports.unstable_UserBlockingPriority = UserBlockingPriority - exports.unstable_cancelCallback = unstable_cancelCallback - exports.unstable_continueExecution = unstable_continueExecution - exports.unstable_getCurrentPriorityLevel = - unstable_getCurrentPriorityLevel - exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode - exports.unstable_next = unstable_next - exports.unstable_pauseExecution = unstable_pauseExecution - exports.unstable_requestPaint = unstable_requestPaint - exports.unstable_runWithPriority = unstable_runWithPriority - exports.unstable_scheduleCallback = unstable_scheduleCallback - exports.unstable_wrapCallback = unstable_wrapCallback - })() - } - })(scheduler_development) - - ;(function (module) { - { - module.exports = scheduler_development - } - })(scheduler) - - var tracing = { exports: {} } - - var schedulerTracing_development = {} - - /** @license React v0.20.2 - * scheduler-tracing.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - ;(function (exports) { - { - ;(function () { - var DEFAULT_THREAD_ID = 0 // Counters used to generate unique IDs. - - var interactionIDCounter = 0 - var threadIDCounter = 0 // Set of currently traced interactions. - // Interactions "stack"– - // Meaning that newly traced interactions are appended to the previously active set. - // When an interaction goes out of scope, the previous set (if any) is restored. - - exports.__interactionsRef = null // Listener(s) to notify when interactions begin and end. - - exports.__subscriberRef = null - - { - exports.__interactionsRef = { - current: new Set(), - } - exports.__subscriberRef = { - current: null, - } - } - function unstable_clear(callback) { - var prevInteractions = exports.__interactionsRef.current - exports.__interactionsRef.current = new Set() - - try { - return callback() - } finally { - exports.__interactionsRef.current = prevInteractions - } - } - function unstable_getCurrent() { - { - return exports.__interactionsRef.current - } - } - function unstable_getThreadID() { - return ++threadIDCounter - } - function unstable_trace(name, timestamp, callback) { - var threadID = - arguments.length > 3 && arguments[3] !== undefined - ? arguments[3] - : DEFAULT_THREAD_ID - - var interaction = { - __count: 1, - id: interactionIDCounter++, - name: name, - timestamp: timestamp, - } - var prevInteractions = exports.__interactionsRef.current // Traced interactions should stack/accumulate. - // To do that, clone the current interactions. - // The previous set will be restored upon completion. - - var interactions = new Set(prevInteractions) - interactions.add(interaction) - exports.__interactionsRef.current = interactions - var subscriber = exports.__subscriberRef.current - var returnValue - - try { - if (subscriber !== null) { - subscriber.onInteractionTraced(interaction) - } - } finally { - try { - if (subscriber !== null) { - subscriber.onWorkStarted(interactions, threadID) - } - } finally { - try { - returnValue = callback() - } finally { - exports.__interactionsRef.current = prevInteractions - - try { - if (subscriber !== null) { - subscriber.onWorkStopped(interactions, threadID) - } - } finally { - interaction.__count-- // If no async work was scheduled for this interaction, - // Notify subscribers that it's completed. - - if (subscriber !== null && interaction.__count === 0) { - subscriber.onInteractionScheduledWorkCompleted(interaction) - } - } - } - } - } - - return returnValue - } - function unstable_wrap(callback) { - var threadID = - arguments.length > 1 && arguments[1] !== undefined - ? arguments[1] - : DEFAULT_THREAD_ID - - var wrappedInteractions = exports.__interactionsRef.current - var subscriber = exports.__subscriberRef.current - - if (subscriber !== null) { - subscriber.onWorkScheduled(wrappedInteractions, threadID) - } // Update the pending async work count for the current interactions. - // Update after calling subscribers in case of error. - - wrappedInteractions.forEach(function (interaction) { - interaction.__count++ - }) - var hasRun = false - - function wrapped() { - var prevInteractions = exports.__interactionsRef.current - exports.__interactionsRef.current = wrappedInteractions - subscriber = exports.__subscriberRef.current - - try { - var returnValue - - try { - if (subscriber !== null) { - subscriber.onWorkStarted(wrappedInteractions, threadID) - } - } finally { - try { - returnValue = callback.apply(undefined, arguments) - } finally { - exports.__interactionsRef.current = prevInteractions - - if (subscriber !== null) { - subscriber.onWorkStopped(wrappedInteractions, threadID) - } - } - } - - return returnValue - } finally { - if (!hasRun) { - // We only expect a wrapped function to be executed once, - // But in the event that it's executed more than once– - // Only decrement the outstanding interaction counts once. - hasRun = true // Update pending async counts for all wrapped interactions. - // If this was the last scheduled async work for any of them, - // Mark them as completed. - - wrappedInteractions.forEach(function (interaction) { - interaction.__count-- - - if (subscriber !== null && interaction.__count === 0) { - subscriber.onInteractionScheduledWorkCompleted(interaction) - } - }) - } - } - } - - wrapped.cancel = function cancel() { - subscriber = exports.__subscriberRef.current - - try { - if (subscriber !== null) { - subscriber.onWorkCanceled(wrappedInteractions, threadID) - } - } finally { - // Update pending async counts for all wrapped interactions. - // If this was the last scheduled async work for any of them, - // Mark them as completed. - wrappedInteractions.forEach(function (interaction) { - interaction.__count-- - - if (subscriber && interaction.__count === 0) { - subscriber.onInteractionScheduledWorkCompleted(interaction) - } - }) - } - } - - return wrapped - } - - var subscribers = null - - { - subscribers = new Set() - } - - function unstable_subscribe(subscriber) { - { - subscribers.add(subscriber) - - if (subscribers.size === 1) { - exports.__subscriberRef.current = { - onInteractionScheduledWorkCompleted: - onInteractionScheduledWorkCompleted, - onInteractionTraced: onInteractionTraced, - onWorkCanceled: onWorkCanceled, - onWorkScheduled: onWorkScheduled, - onWorkStarted: onWorkStarted, - onWorkStopped: onWorkStopped, - } - } - } - } - function unstable_unsubscribe(subscriber) { - { - subscribers.delete(subscriber) - - if (subscribers.size === 0) { - exports.__subscriberRef.current = null - } - } - } - - function onInteractionTraced(interaction) { - var didCatchError = false - var caughtError = null - subscribers.forEach(function (subscriber) { - try { - subscriber.onInteractionTraced(interaction) - } catch (error) { - if (!didCatchError) { - didCatchError = true - caughtError = error - } - } - }) - - if (didCatchError) { - throw caughtError - } - } - - function onInteractionScheduledWorkCompleted(interaction) { - var didCatchError = false - var caughtError = null - subscribers.forEach(function (subscriber) { - try { - subscriber.onInteractionScheduledWorkCompleted(interaction) - } catch (error) { - if (!didCatchError) { - didCatchError = true - caughtError = error - } - } - }) - - if (didCatchError) { - throw caughtError - } - } - - function onWorkScheduled(interactions, threadID) { - var didCatchError = false - var caughtError = null - subscribers.forEach(function (subscriber) { - try { - subscriber.onWorkScheduled(interactions, threadID) - } catch (error) { - if (!didCatchError) { - didCatchError = true - caughtError = error - } - } - }) - - if (didCatchError) { - throw caughtError - } - } - - function onWorkStarted(interactions, threadID) { - var didCatchError = false - var caughtError = null - subscribers.forEach(function (subscriber) { - try { - subscriber.onWorkStarted(interactions, threadID) - } catch (error) { - if (!didCatchError) { - didCatchError = true - caughtError = error - } - } - }) - - if (didCatchError) { - throw caughtError - } - } - - function onWorkStopped(interactions, threadID) { - var didCatchError = false - var caughtError = null - subscribers.forEach(function (subscriber) { - try { - subscriber.onWorkStopped(interactions, threadID) - } catch (error) { - if (!didCatchError) { - didCatchError = true - caughtError = error - } - } - }) - - if (didCatchError) { - throw caughtError - } - } - - function onWorkCanceled(interactions, threadID) { - var didCatchError = false - var caughtError = null - subscribers.forEach(function (subscriber) { - try { - subscriber.onWorkCanceled(interactions, threadID) - } catch (error) { - if (!didCatchError) { - didCatchError = true - caughtError = error - } - } - }) - - if (didCatchError) { - throw caughtError - } - } - - exports.unstable_clear = unstable_clear - exports.unstable_getCurrent = unstable_getCurrent - exports.unstable_getThreadID = unstable_getThreadID - exports.unstable_subscribe = unstable_subscribe - exports.unstable_trace = unstable_trace - exports.unstable_unsubscribe = unstable_unsubscribe - exports.unstable_wrap = unstable_wrap - })() - } - })(schedulerTracing_development) - - ;(function (module) { - { - module.exports = schedulerTracing_development - } - })(tracing) - - /** @license React v17.0.2 - * react-dom.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - { - ;(function () { - var React = react.exports - var _assign = objectAssign - var Scheduler = scheduler.exports - var tracing$1 = tracing.exports - - var ReactSharedInternals = - React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED - - // by calls to these methods by a Babel plugin. - // - // In PROD (or in packages without access to React internals), - // they are left as they are instead. - - function warn(format) { - { - for ( - var _len = arguments.length, - args = new Array(_len > 1 ? _len - 1 : 0), - _key = 1; - _key < _len; - _key++ - ) { - args[_key - 1] = arguments[_key] - } - - printWarning('warn', format, args) - } - } - function error(format) { - { - for ( - var _len2 = arguments.length, - args = new Array(_len2 > 1 ? _len2 - 1 : 0), - _key2 = 1; - _key2 < _len2; - _key2++ - ) { - args[_key2 - 1] = arguments[_key2] - } - - printWarning('error', format, args) - } - } - - function printWarning(level, format, args) { - // When changing this logic, you might want to also - // update consoleWithStackDev.www.js as well. - { - var ReactDebugCurrentFrame = - ReactSharedInternals.ReactDebugCurrentFrame - var stack = ReactDebugCurrentFrame.getStackAddendum() - - if (stack !== '') { - format += '%s' - args = args.concat([stack]) - } - - var argsWithFormat = args.map(function (item) { - return '' + item - }) // Careful: RN currently depends on this prefix - - argsWithFormat.unshift('Warning: ' + format) // We intentionally don't use spread (or .apply) directly because it - // breaks IE9: https://github.com/facebook/react/issues/13610 - // eslint-disable-next-line react-internal/no-production-logging - - Function.prototype.apply.call(console[level], console, argsWithFormat) - } - } - - if (!React) { - { - throw Error( - 'ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.' - ) - } - } - - var FunctionComponent = 0 - var ClassComponent = 1 - var IndeterminateComponent = 2 // Before we know whether it is function or class - - var HostRoot = 3 // Root of a host tree. Could be nested inside another node. - - var HostPortal = 4 // A subtree. Could be an entry point to a different renderer. - - var HostComponent = 5 - var HostText = 6 - var Fragment = 7 - var Mode = 8 - var ContextConsumer = 9 - var ContextProvider = 10 - var ForwardRef = 11 - var Profiler = 12 - var SuspenseComponent = 13 - var MemoComponent = 14 - var SimpleMemoComponent = 15 - var LazyComponent = 16 - var IncompleteClassComponent = 17 - var DehydratedFragment = 18 - var SuspenseListComponent = 19 - var FundamentalComponent = 20 - var ScopeComponent = 21 - var Block = 22 - var OffscreenComponent = 23 - var LegacyHiddenComponent = 24 - - // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. - - var enableProfilerTimer = true // Record durations for commit and passive effects phases. - - var enableFundamentalAPI = false // Experimental Scope support. - var enableNewReconciler = false // Errors that are thrown while unmounting (or after in the case of passive effects) - var warnAboutStringRefs = false - - var allNativeEvents = new Set() - /** - * Mapping from registration name to event name - */ - - var registrationNameDependencies = {} - /** - * Mapping from lowercase registration names to the properly cased version, - * used to warn in the case of missing event handlers. Available - * only in true. - * @type {Object} - */ - - var possibleRegistrationNames = {} // Trust the developer to only use possibleRegistrationNames in true - - function registerTwoPhaseEvent(registrationName, dependencies) { - registerDirectEvent(registrationName, dependencies) - registerDirectEvent(registrationName + 'Capture', dependencies) - } - function registerDirectEvent(registrationName, dependencies) { - { - if (registrationNameDependencies[registrationName]) { - error( - 'EventRegistry: More than one plugin attempted to publish the same ' + - 'registration name, `%s`.', - registrationName - ) - } - } - - registrationNameDependencies[registrationName] = dependencies - - { - var lowerCasedName = registrationName.toLowerCase() - possibleRegistrationNames[lowerCasedName] = registrationName - - if (registrationName === 'onDoubleClick') { - possibleRegistrationNames.ondblclick = registrationName - } - } - - for (var i = 0; i < dependencies.length; i++) { - allNativeEvents.add(dependencies[i]) - } - } - - var canUseDOM = !!( - typeof window !== 'undefined' && - typeof window.document !== 'undefined' && - typeof window.document.createElement !== 'undefined' - ) - - // A reserved attribute. - // It is handled by React separately and shouldn't be written to the DOM. - var RESERVED = 0 // A simple string attribute. - // Attributes that aren't in the filter are presumed to have this type. - - var STRING = 1 // A string attribute that accepts booleans in React. In HTML, these are called - // "enumerated" attributes with "true" and "false" as possible values. - // When true, it should be set to a "true" string. - // When false, it should be set to a "false" string. - - var BOOLEANISH_STRING = 2 // A real boolean attribute. - // When true, it should be present (set either to an empty string or its name). - // When false, it should be omitted. - - var BOOLEAN = 3 // An attribute that can be used as a flag as well as with a value. - // When true, it should be present (set either to an empty string or its name). - // When false, it should be omitted. - // For any other value, should be present with that value. - - var OVERLOADED_BOOLEAN = 4 // An attribute that must be numeric or parse as a numeric. - // When falsy, it should be removed. - - var NUMERIC = 5 // An attribute that must be positive numeric or parse as a positive numeric. - // When falsy, it should be removed. - - var POSITIVE_NUMERIC = 6 - - /* eslint-disable max-len */ - var ATTRIBUTE_NAME_START_CHAR = - ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD' - /* eslint-enable max-len */ - - var ATTRIBUTE_NAME_CHAR = - ATTRIBUTE_NAME_START_CHAR + - '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040' - var ROOT_ATTRIBUTE_NAME = 'data-reactroot' - var VALID_ATTRIBUTE_NAME_REGEX = new RegExp( - '^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$' - ) - var hasOwnProperty = Object.prototype.hasOwnProperty - var illegalAttributeNameCache = {} - var validatedAttributeNameCache = {} - function isAttributeNameSafe(attributeName) { - if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { - return true - } - - if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { - return false - } - - if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { - validatedAttributeNameCache[attributeName] = true - return true - } - - illegalAttributeNameCache[attributeName] = true - - { - error('Invalid attribute name: `%s`', attributeName) - } - - return false - } - function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null) { - return propertyInfo.type === RESERVED - } - - if (isCustomComponentTag) { - return false - } - - if ( - name.length > 2 && - (name[0] === 'o' || name[0] === 'O') && - (name[1] === 'n' || name[1] === 'N') - ) { - return true - } - - return false - } - function shouldRemoveAttributeWithWarning( - name, - value, - propertyInfo, - isCustomComponentTag - ) { - if (propertyInfo !== null && propertyInfo.type === RESERVED) { - return false - } - - switch (typeof value) { - case 'function': // $FlowIssue symbol is perfectly valid here - - case 'symbol': - // eslint-disable-line - return true - - case 'boolean': { - if (isCustomComponentTag) { - return false - } - - if (propertyInfo !== null) { - return !propertyInfo.acceptsBooleans - } else { - var prefix = name.toLowerCase().slice(0, 5) - return prefix !== 'data-' && prefix !== 'aria-' - } - } - - default: - return false - } - } - function shouldRemoveAttribute( - name, - value, - propertyInfo, - isCustomComponentTag - ) { - if (value === null || typeof value === 'undefined') { - return true - } - - if ( - shouldRemoveAttributeWithWarning( - name, - value, - propertyInfo, - isCustomComponentTag - ) - ) { - return true - } - - if (isCustomComponentTag) { - return false - } - - if (propertyInfo !== null) { - switch (propertyInfo.type) { - case BOOLEAN: - return !value - - case OVERLOADED_BOOLEAN: - return value === false - - case NUMERIC: - return isNaN(value) - - case POSITIVE_NUMERIC: - return isNaN(value) || value < 1 - } - } - - return false - } - function getPropertyInfo(name) { - return properties.hasOwnProperty(name) ? properties[name] : null - } - - function PropertyInfoRecord( - name, - type, - mustUseProperty, - attributeName, - attributeNamespace, - sanitizeURL, - removeEmptyString - ) { - this.acceptsBooleans = - type === BOOLEANISH_STRING || - type === BOOLEAN || - type === OVERLOADED_BOOLEAN - this.attributeName = attributeName - this.attributeNamespace = attributeNamespace - this.mustUseProperty = mustUseProperty - this.propertyName = name - this.type = type - this.sanitizeURL = sanitizeURL - this.removeEmptyString = removeEmptyString - } // When adding attributes to this list, be sure to also add them to - // the `possibleStandardNames` module to ensure casing and incorrect - // name warnings. - - var properties = {} // These props are reserved by React. They shouldn't be written to the DOM. - - var reservedProps = [ - 'children', - 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular - // elements (not just inputs). Now that ReactDOMInput assigns to the - // defaultValue property -- do we need this? - 'defaultValue', - 'defaultChecked', - 'innerHTML', - 'suppressContentEditableWarning', - 'suppressHydrationWarning', - 'style', - ] - reservedProps.forEach(function (name) { - properties[name] = new PropertyInfoRecord( - name, - RESERVED, - false, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) // A few React string attributes have a different name. - // This is a mapping from React prop names to the attribute names. - - ;[ - ['acceptCharset', 'accept-charset'], - ['className', 'class'], - ['htmlFor', 'for'], - ['httpEquiv', 'http-equiv'], - ].forEach(function (_ref) { - var name = _ref[0], - attributeName = _ref[1] - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, // mustUseProperty - attributeName, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) // These are "enumerated" HTML attributes that accept "true" and "false". - // In React, we let users pass `true` and `false` even though technically - // these aren't boolean attributes (they are coerced to strings). - - ;['contentEditable', 'draggable', 'spellCheck', 'value'].forEach( - function (name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEANISH_STRING, - false, // mustUseProperty - name.toLowerCase(), // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - } - ) // These are "enumerated" SVG attributes that accept "true" and "false". - // In React, we let users pass `true` and `false` even though technically - // these aren't boolean attributes (they are coerced to strings). - // Since these are SVG attributes, their attribute names are case-sensitive. - - ;[ - 'autoReverse', - 'externalResourcesRequired', - 'focusable', - 'preserveAlpha', - ].forEach(function (name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEANISH_STRING, - false, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) // These are HTML boolean attributes. - - ;[ - 'allowFullScreen', - 'async', // Note: there is a special case that prevents it from being written to the DOM - // on the client side because the browsers are inconsistent. Instead we call focus(). - 'autoFocus', - 'autoPlay', - 'controls', - 'default', - 'defer', - 'disabled', - 'disablePictureInPicture', - 'disableRemotePlayback', - 'formNoValidate', - 'hidden', - 'loop', - 'noModule', - 'noValidate', - 'open', - 'playsInline', - 'readOnly', - 'required', - 'reversed', - 'scoped', - 'seamless', // Microdata - 'itemScope', - ].forEach(function (name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEAN, - false, // mustUseProperty - name.toLowerCase(), // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) // These are the few React props that we set as DOM properties - // rather than attributes. These are all booleans. - - ;[ - 'checked', // Note: `option.selected` is not updated if `select.multiple` is - // disabled with `removeAttribute`. We have special logic for handling this. - 'multiple', - 'muted', - 'selected', // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function (name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEAN, - true, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) // These are HTML attributes that are "overloaded booleans": they behave like - // booleans, but can also accept a string value. - - ;[ - 'capture', - 'download', // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function (name) { - properties[name] = new PropertyInfoRecord( - name, - OVERLOADED_BOOLEAN, - false, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) // These are HTML attributes that must be positive numbers. - - ;[ - 'cols', - 'rows', - 'size', - 'span', // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function (name) { - properties[name] = new PropertyInfoRecord( - name, - POSITIVE_NUMERIC, - false, // mustUseProperty - name, // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) // These are HTML attributes that must be numbers. - - ;['rowSpan', 'start'].forEach(function (name) { - properties[name] = new PropertyInfoRecord( - name, - NUMERIC, - false, // mustUseProperty - name.toLowerCase(), // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) - var CAMELIZE = /[\-\:]([a-z])/g - - var capitalize = function (token) { - return token[1].toUpperCase() - } // This is a list of all SVG attributes that need special casing, namespacing, - // or boolean value assignment. Regular attributes that just accept strings - // and have the same names are omitted, just like in the HTML attribute filter. - // Some of these attributes can be hard to find. This list was created by - // scraping the MDN documentation. - - ;[ - 'accent-height', - 'alignment-baseline', - 'arabic-form', - 'baseline-shift', - 'cap-height', - 'clip-path', - 'clip-rule', - 'color-interpolation', - 'color-interpolation-filters', - 'color-profile', - 'color-rendering', - 'dominant-baseline', - 'enable-background', - 'fill-opacity', - 'fill-rule', - 'flood-color', - 'flood-opacity', - 'font-family', - 'font-size', - 'font-size-adjust', - 'font-stretch', - 'font-style', - 'font-variant', - 'font-weight', - 'glyph-name', - 'glyph-orientation-horizontal', - 'glyph-orientation-vertical', - 'horiz-adv-x', - 'horiz-origin-x', - 'image-rendering', - 'letter-spacing', - 'lighting-color', - 'marker-end', - 'marker-mid', - 'marker-start', - 'overline-position', - 'overline-thickness', - 'paint-order', - 'panose-1', - 'pointer-events', - 'rendering-intent', - 'shape-rendering', - 'stop-color', - 'stop-opacity', - 'strikethrough-position', - 'strikethrough-thickness', - 'stroke-dasharray', - 'stroke-dashoffset', - 'stroke-linecap', - 'stroke-linejoin', - 'stroke-miterlimit', - 'stroke-opacity', - 'stroke-width', - 'text-anchor', - 'text-decoration', - 'text-rendering', - 'underline-position', - 'underline-thickness', - 'unicode-bidi', - 'unicode-range', - 'units-per-em', - 'v-alphabetic', - 'v-hanging', - 'v-ideographic', - 'v-mathematical', - 'vector-effect', - 'vert-adv-y', - 'vert-origin-x', - 'vert-origin-y', - 'word-spacing', - 'writing-mode', - 'xmlns:xlink', - 'x-height', // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize) - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, // mustUseProperty - attributeName, - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) // String SVG attributes with the xlink namespace. - - ;[ - 'xlink:actuate', - 'xlink:arcrole', - 'xlink:role', - 'xlink:show', - 'xlink:title', - 'xlink:type', // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize) - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, // mustUseProperty - attributeName, - 'http://www.w3.org/1999/xlink', - false, // sanitizeURL - false - ) - }) // String SVG attributes with the xml namespace. - - ;[ - 'xml:base', - 'xml:lang', - 'xml:space', // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize) - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, // mustUseProperty - attributeName, - 'http://www.w3.org/XML/1998/namespace', - false, // sanitizeURL - false - ) - }) // These attribute exists both in HTML and SVG. - // The attribute name is case-sensitive in SVG so we can't just use - // the React name like we do for attributes that exist only in HTML. - - ;['tabIndex', 'crossOrigin'].forEach(function (attributeName) { - properties[attributeName] = new PropertyInfoRecord( - attributeName, - STRING, - false, // mustUseProperty - attributeName.toLowerCase(), // attributeName - null, // attributeNamespace - false, // sanitizeURL - false - ) - }) // These attributes accept URLs. These must not allow javascript: URLS. - // These will also need to accept Trusted Types object in the future. - - var xlinkHref = 'xlinkHref' - properties[xlinkHref] = new PropertyInfoRecord( - 'xlinkHref', - STRING, - false, // mustUseProperty - 'xlink:href', - 'http://www.w3.org/1999/xlink', - true, // sanitizeURL - false - ) - ;['src', 'href', 'action', 'formAction'].forEach(function ( - attributeName - ) { - properties[attributeName] = new PropertyInfoRecord( - attributeName, - STRING, - false, // mustUseProperty - attributeName.toLowerCase(), // attributeName - null, // attributeNamespace - true, // sanitizeURL - true - ) - }) - - // and any newline or tab are filtered out as if they're not part of the URL. - // https://url.spec.whatwg.org/#url-parsing - // Tab or newline are defined as \r\n\t: - // https://infra.spec.whatwg.org/#ascii-tab-or-newline - // A C0 control is a code point in the range \u0000 NULL to \u001F - // INFORMATION SEPARATOR ONE, inclusive: - // https://infra.spec.whatwg.org/#c0-control-or-space - - /* eslint-disable max-len */ - - var isJavaScriptProtocol = - /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i - var didWarn = false - - function sanitizeURL(url) { - { - if (!didWarn && isJavaScriptProtocol.test(url)) { - didWarn = true - - error( - 'A future version of React will block javascript: URLs as a security precaution. ' + - 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + - 'using dangerouslySetInnerHTML instead. React was passed %s.', - JSON.stringify(url) - ) - } - } - } - - /** - * Get the value for a property on a node. Only used in DEV for SSR validation. - * The "expected" argument is used as a hint of what the expected value is. - * Some properties have multiple equivalent values. - */ - function getValueForProperty(node, name, expected, propertyInfo) { - { - if (propertyInfo.mustUseProperty) { - var propertyName = propertyInfo.propertyName - return node[propertyName] - } else { - if (propertyInfo.sanitizeURL) { - // If we haven't fully disabled javascript: URLs, and if - // the hydration is successful of a javascript: URL, we - // still want to warn on the client. - sanitizeURL('' + expected) - } - - var attributeName = propertyInfo.attributeName - var stringValue = null - - if (propertyInfo.type === OVERLOADED_BOOLEAN) { - if (node.hasAttribute(attributeName)) { - var value = node.getAttribute(attributeName) - - if (value === '') { - return true - } - - if ( - shouldRemoveAttribute(name, expected, propertyInfo, false) - ) { - return value - } - - if (value === '' + expected) { - return expected - } - - return value - } - } else if (node.hasAttribute(attributeName)) { - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - // We had an attribute but shouldn't have had one, so read it - // for the error message. - return node.getAttribute(attributeName) - } - - if (propertyInfo.type === BOOLEAN) { - // If this was a boolean, it doesn't matter what the value is - // the fact that we have it is the same as the expected. - return expected - } // Even if this property uses a namespace we use getAttribute - // because we assume its namespaced name is the same as our config. - // To use getAttributeNS we need the local name which we don't have - // in our config atm. - - stringValue = node.getAttribute(attributeName) - } - - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return stringValue === null ? expected : stringValue - } else if (stringValue === '' + expected) { - return expected - } else { - return stringValue - } - } - } - } - /** - * Get the value for a attribute on a node. Only used in DEV for SSR validation. - * The third argument is used as a hint of what the expected value is. Some - * attributes have multiple equivalent values. - */ - - function getValueForAttribute(node, name, expected) { - { - if (!isAttributeNameSafe(name)) { - return - } // If the object is an opaque reference ID, it's expected that - // the next prop is different than the server value, so just return - // expected - - if (isOpaqueHydratingObject(expected)) { - return expected - } - - if (!node.hasAttribute(name)) { - return expected === undefined ? undefined : null - } - - var value = node.getAttribute(name) - - if (value === '' + expected) { - return expected - } - - return value - } - } - /** - * Sets the value for a property on a node. - * - * @param {DOMElement} node - * @param {string} name - * @param {*} value - */ - - function setValueForProperty(node, name, value, isCustomComponentTag) { - var propertyInfo = getPropertyInfo(name) - - if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { - return - } - - if ( - shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) - ) { - value = null - } // If the prop isn't in the special list, treat it as a simple attribute. - - if (isCustomComponentTag || propertyInfo === null) { - if (isAttributeNameSafe(name)) { - var _attributeName = name - - if (value === null) { - node.removeAttribute(_attributeName) - } else { - node.setAttribute(_attributeName, '' + value) - } - } - - return - } - - var mustUseProperty = propertyInfo.mustUseProperty - - if (mustUseProperty) { - var propertyName = propertyInfo.propertyName - - if (value === null) { - var type = propertyInfo.type - node[propertyName] = type === BOOLEAN ? false : '' - } else { - // Contrary to `setAttribute`, object properties are properly - // `toString`ed by IE8/9. - node[propertyName] = value - } - - return - } // The rest are treated as attributes with special cases. - - var attributeName = propertyInfo.attributeName, - attributeNamespace = propertyInfo.attributeNamespace - - if (value === null) { - node.removeAttribute(attributeName) - } else { - var _type = propertyInfo.type - var attributeValue - - if ( - _type === BOOLEAN || - (_type === OVERLOADED_BOOLEAN && value === true) - ) { - // If attribute type is boolean, we know for sure it won't be an execution sink - // and we won't require Trusted Type here. - attributeValue = '' - } else { - // `setAttribute` with objects becomes only `[object]` in IE8/9, - // ('' + value) makes it output the correct toString()-value. - { - attributeValue = '' + value - } - - if (propertyInfo.sanitizeURL) { - sanitizeURL(attributeValue.toString()) - } - } - - if (attributeNamespace) { - node.setAttributeNS( - attributeNamespace, - attributeName, - attributeValue - ) - } else { - node.setAttribute(attributeName, attributeValue) - } - } - } - - // ATTENTION - // When adding new symbols to this file, - // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' - // The Symbol used to tag the ReactElement-like types. If there is no native Symbol - // nor polyfill, then a plain number is used for performance. - var REACT_ELEMENT_TYPE = 0xeac7 - var REACT_PORTAL_TYPE = 0xeaca - var REACT_FRAGMENT_TYPE = 0xeacb - var REACT_STRICT_MODE_TYPE = 0xeacc - var REACT_PROFILER_TYPE = 0xead2 - var REACT_PROVIDER_TYPE = 0xeacd - var REACT_CONTEXT_TYPE = 0xeace - var REACT_FORWARD_REF_TYPE = 0xead0 - var REACT_SUSPENSE_TYPE = 0xead1 - var REACT_SUSPENSE_LIST_TYPE = 0xead8 - var REACT_MEMO_TYPE = 0xead3 - var REACT_LAZY_TYPE = 0xead4 - var REACT_BLOCK_TYPE = 0xead9 - var REACT_SCOPE_TYPE = 0xead7 - var REACT_OPAQUE_ID_TYPE = 0xeae0 - var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1 - var REACT_OFFSCREEN_TYPE = 0xeae2 - var REACT_LEGACY_HIDDEN_TYPE = 0xeae3 - - if (typeof Symbol === 'function' && Symbol.for) { - var symbolFor = Symbol.for - REACT_ELEMENT_TYPE = symbolFor('react.element') - REACT_PORTAL_TYPE = symbolFor('react.portal') - REACT_FRAGMENT_TYPE = symbolFor('react.fragment') - REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode') - REACT_PROFILER_TYPE = symbolFor('react.profiler') - REACT_PROVIDER_TYPE = symbolFor('react.provider') - REACT_CONTEXT_TYPE = symbolFor('react.context') - REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref') - REACT_SUSPENSE_TYPE = symbolFor('react.suspense') - REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list') - REACT_MEMO_TYPE = symbolFor('react.memo') - REACT_LAZY_TYPE = symbolFor('react.lazy') - REACT_BLOCK_TYPE = symbolFor('react.block') - symbolFor('react.server.block') - symbolFor('react.fundamental') - REACT_SCOPE_TYPE = symbolFor('react.scope') - REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id') - REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode') - REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen') - REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden') - } - - var MAYBE_ITERATOR_SYMBOL = - typeof Symbol === 'function' && Symbol.iterator - var FAUX_ITERATOR_SYMBOL = '@@iterator' - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== 'object') { - return null - } - - var maybeIterator = - (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || - maybeIterable[FAUX_ITERATOR_SYMBOL] - - if (typeof maybeIterator === 'function') { - return maybeIterator - } - - return null - } - - // Helpers to patch console.logs to avoid logging during side-effect free - // replaying on render function. This currently only patches the object - // lazily which won't cover if the log function was extracted eagerly. - // We could also eagerly patch the method. - var disabledDepth = 0 - var prevLog - var prevInfo - var prevWarn - var prevError - var prevGroup - var prevGroupCollapsed - var prevGroupEnd - - function disabledLog() {} - - disabledLog.__reactDisabledLog = true - function disableLogs() { - { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log - prevInfo = console.info - prevWarn = console.warn - prevError = console.error - prevGroup = console.group - prevGroupCollapsed = console.groupCollapsed - prevGroupEnd = console.groupEnd // https://github.com/facebook/react/issues/19099 - - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true, - } // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props, - }) - /* eslint-enable react-internal/no-production-logging */ - } - - disabledDepth++ - } - } - function reenableLogs() { - { - disabledDepth-- - - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true, - } // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - log: _assign({}, props, { - value: prevLog, - }), - info: _assign({}, props, { - value: prevInfo, - }), - warn: _assign({}, props, { - value: prevWarn, - }), - error: _assign({}, props, { - value: prevError, - }), - group: _assign({}, props, { - value: prevGroup, - }), - groupCollapsed: _assign({}, props, { - value: prevGroupCollapsed, - }), - groupEnd: _assign({}, props, { - value: prevGroupEnd, - }), - }) - /* eslint-enable react-internal/no-production-logging */ - } - - if (disabledDepth < 0) { - error( - 'disabledDepth fell below zero. ' + - 'This is a bug in React. Please file an issue.' - ) - } - } - } - - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher - var prefix - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error() - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/) - prefix = (match && match[1]) || '' - } - } // We use the prefix to ensure our stacks line up with native stack frames. - - return '\n' + prefix + name - } - } - var reentry = false - var componentFrameCache - - { - var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map - componentFrameCache = new PossiblyWeakMap() - } - - function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if (!fn || reentry) { - return '' - } - - { - var frame = componentFrameCache.get(fn) - - if (frame !== undefined) { - return frame - } - } - - var control - reentry = true - var previousPrepareStackTrace = Error.prepareStackTrace // $FlowFixMe It does accept undefined. - - Error.prepareStackTrace = undefined - var previousDispatcher - - { - previousDispatcher = ReactCurrentDispatcher.current // Set the dispatcher in DEV because this might be call in the render function - // for warnings. - - ReactCurrentDispatcher.current = null - disableLogs() - } - - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error() - } // $FlowFixMe - - Object.defineProperty(Fake.prototype, 'props', { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error() - }, - }) - - if (typeof Reflect === 'object' && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []) - } catch (x) { - control = x - } - - Reflect.construct(fn, [], Fake) - } else { - try { - Fake.call() - } catch (x) { - control = x - } - - fn.call(Fake.prototype) - } - } else { - try { - throw Error() - } catch (x) { - control = x - } - - fn() - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === 'string') { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sample.stack.split('\n') - var controlLines = control.stack.split('\n') - var s = sampleLines.length - 1 - var c = controlLines.length - 1 - - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c-- - } - - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s-- - c-- // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. - - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = - '\n' + sampleLines[s].replace(' at new ', ' at ') - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, _frame) - } - } // Return the line we found. - - return _frame - } - } while (s >= 1 && c >= 0) - } - - break - } - } - } - } finally { - reentry = false - - { - ReactCurrentDispatcher.current = previousDispatcher - reenableLogs() - } - - Error.prepareStackTrace = previousPrepareStackTrace - } // Fallback to just using the name if we couldn't make it throw. - - var name = fn ? fn.displayName || fn.name : '' - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '' - - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, syntheticFrame) - } - } - - return syntheticFrame - } - - function describeClassComponentFrame(ctor, source, ownerFn) { - { - return describeNativeComponentFrame(ctor, true) - } - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false) - } - } - - function shouldConstruct(Component) { - var prototype = Component.prototype - return !!(prototype && prototype.isReactComponent) - } - - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return '' - } - - if (typeof type === 'function') { - { - return describeNativeComponentFrame(type, shouldConstruct(type)) - } - } - - if (typeof type === 'string') { - return describeBuiltInComponentFrame(type) - } - - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame('Suspense') - - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame('SuspenseList') - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render) - - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - type.type, - source, - ownerFn - ) - - case REACT_BLOCK_TYPE: - return describeFunctionComponentFrame(type._render) - - case REACT_LAZY_TYPE: { - var lazyComponent = type - var payload = lazyComponent._payload - var init = lazyComponent._init - - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV( - init(payload), - source, - ownerFn - ) - } catch (x) {} - } - } - } - - return '' - } - - function describeFiber(fiber) { - fiber._debugOwner ? fiber._debugOwner.type : null - fiber._debugSource - - switch (fiber.tag) { - case HostComponent: - return describeBuiltInComponentFrame(fiber.type) - - case LazyComponent: - return describeBuiltInComponentFrame('Lazy') - - case SuspenseComponent: - return describeBuiltInComponentFrame('Suspense') - - case SuspenseListComponent: - return describeBuiltInComponentFrame('SuspenseList') - - case FunctionComponent: - case IndeterminateComponent: - case SimpleMemoComponent: - return describeFunctionComponentFrame(fiber.type) - - case ForwardRef: - return describeFunctionComponentFrame(fiber.type.render) - - case Block: - return describeFunctionComponentFrame(fiber.type._render) - - case ClassComponent: - return describeClassComponentFrame(fiber.type) - - default: - return '' - } - } - - function getStackByFiberInDevAndProd(workInProgress) { - try { - var info = '' - var node = workInProgress - - do { - info += describeFiber(node) - node = node.return - } while (node) - - return info - } catch (x) { - return '\nError generating stack: ' + x.message + '\n' + x.stack - } - } - - function getWrappedName(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || '' - return ( - outerType.displayName || - (functionName !== '' - ? wrapperName + '(' + functionName + ')' - : wrapperName) - ) - } - - function getContextName(type) { - return type.displayName || 'Context' - } - - function getComponentName(type) { - if (type == null) { - // Host root, text node or just invalid type. - return null - } - - { - if (typeof type.tag === 'number') { - error( - 'Received an unexpected object in getComponentName(). ' + - 'This is likely a bug in React. Please file an issue.' - ) - } - } - - if (typeof type === 'function') { - return type.displayName || type.name || null - } - - if (typeof type === 'string') { - return type - } - - switch (type) { - case REACT_FRAGMENT_TYPE: - return 'Fragment' - - case REACT_PORTAL_TYPE: - return 'Portal' - - case REACT_PROFILER_TYPE: - return 'Profiler' - - case REACT_STRICT_MODE_TYPE: - return 'StrictMode' - - case REACT_SUSPENSE_TYPE: - return 'Suspense' - - case REACT_SUSPENSE_LIST_TYPE: - return 'SuspenseList' - } - - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type - return getContextName(context) + '.Consumer' - - case REACT_PROVIDER_TYPE: - var provider = type - return getContextName(provider._context) + '.Provider' - - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, 'ForwardRef') - - case REACT_MEMO_TYPE: - return getComponentName(type.type) - - case REACT_BLOCK_TYPE: - return getComponentName(type._render) - - case REACT_LAZY_TYPE: { - var lazyComponent = type - var payload = lazyComponent._payload - var init = lazyComponent._init - - try { - return getComponentName(init(payload)) - } catch (x) { - return null - } - } - } - } - - return null - } - - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame - var current = null - var isRendering = false - function getCurrentFiberOwnerNameInDevOrNull() { - { - if (current === null) { - return null - } - - var owner = current._debugOwner - - if (owner !== null && typeof owner !== 'undefined') { - return getComponentName(owner.type) - } - } - - return null - } - - function getCurrentFiberStackInDev() { - { - if (current === null) { - return '' - } // Safe because if current fiber exists, we are reconciling, - // and it is guaranteed to be the work-in-progress version. - - return getStackByFiberInDevAndProd(current) - } - } - - function resetCurrentFiber() { - { - ReactDebugCurrentFrame.getCurrentStack = null - current = null - isRendering = false - } - } - function setCurrentFiber(fiber) { - { - ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev - current = fiber - isRendering = false - } - } - function setIsRendering(rendering) { - { - isRendering = rendering - } - } - function getIsRendering() { - { - return isRendering - } - } - - // Flow does not allow string concatenation of most non-string types. To work - // around this limitation, we use an opaque type that can only be obtained by - // passing the value through getToStringValue first. - function toString(value) { - return '' + value - } - function getToStringValue(value) { - switch (typeof value) { - case 'boolean': - case 'number': - case 'object': - case 'string': - case 'undefined': - return value - - default: - // function, symbol are assigned as empty strings - return '' - } - } - - var hasReadOnlyValue = { - button: true, - checkbox: true, - image: true, - hidden: true, - radio: true, - reset: true, - submit: true, - } - function checkControlledValueProps(tagName, props) { - { - if ( - !( - hasReadOnlyValue[props.type] || - props.onChange || - props.onInput || - props.readOnly || - props.disabled || - props.value == null - ) - ) { - error( - 'You provided a `value` prop to a form field without an ' + - '`onChange` handler. This will render a read-only field. If ' + - 'the field should be mutable use `defaultValue`. Otherwise, ' + - 'set either `onChange` or `readOnly`.' - ) - } - - if ( - !( - props.onChange || - props.readOnly || - props.disabled || - props.checked == null - ) - ) { - error( - 'You provided a `checked` prop to a form field without an ' + - '`onChange` handler. This will render a read-only field. If ' + - 'the field should be mutable use `defaultChecked`. Otherwise, ' + - 'set either `onChange` or `readOnly`.' - ) - } - } - } - - function isCheckable(elem) { - var type = elem.type - var nodeName = elem.nodeName - return ( - nodeName && - nodeName.toLowerCase() === 'input' && - (type === 'checkbox' || type === 'radio') - ) - } - - function getTracker(node) { - return node._valueTracker - } - - function detachTracker(node) { - node._valueTracker = null - } - - function getValueFromNode(node) { - var value = '' - - if (!node) { - return value - } - - if (isCheckable(node)) { - value = node.checked ? 'true' : 'false' - } else { - value = node.value - } - - return value - } - - function trackValueOnNode(node) { - var valueField = isCheckable(node) ? 'checked' : 'value' - var descriptor = Object.getOwnPropertyDescriptor( - node.constructor.prototype, - valueField - ) - var currentValue = '' + node[valueField] // if someone has already defined a value or Safari, then bail - // and don't track value will cause over reporting of changes, - // but it's better then a hard failure - // (needed for certain tests that spyOn input values and Safari) - - if ( - node.hasOwnProperty(valueField) || - typeof descriptor === 'undefined' || - typeof descriptor.get !== 'function' || - typeof descriptor.set !== 'function' - ) { - return - } - - var get = descriptor.get, - set = descriptor.set - Object.defineProperty(node, valueField, { - configurable: true, - get: function () { - return get.call(this) - }, - set: function (value) { - currentValue = '' + value - set.call(this, value) - }, - }) // We could've passed this the first time - // but it triggers a bug in IE11 and Edge 14/15. - // Calling defineProperty() again should be equivalent. - // https://github.com/facebook/react/issues/11768 - - Object.defineProperty(node, valueField, { - enumerable: descriptor.enumerable, - }) - var tracker = { - getValue: function () { - return currentValue - }, - setValue: function (value) { - currentValue = '' + value - }, - stopTracking: function () { - detachTracker(node) - delete node[valueField] - }, - } - return tracker - } - - function track(node) { - if (getTracker(node)) { - return - } // TODO: Once it's just Fiber we can move this to node._wrapperState - - node._valueTracker = trackValueOnNode(node) - } - function updateValueIfChanged(node) { - if (!node) { - return false - } - - var tracker = getTracker(node) // if there is no tracker at this point it's unlikely - // that trying again will succeed - - if (!tracker) { - return true - } - - var lastValue = tracker.getValue() - var nextValue = getValueFromNode(node) - - if (nextValue !== lastValue) { - tracker.setValue(nextValue) - return true - } - - return false - } - - function getActiveElement(doc) { - doc = doc || (typeof document !== 'undefined' ? document : undefined) - - if (typeof doc === 'undefined') { - return null - } - - try { - return doc.activeElement || doc.body - } catch (e) { - return doc.body - } - } - - var didWarnValueDefaultValue = false - var didWarnCheckedDefaultChecked = false - var didWarnControlledToUncontrolled = false - var didWarnUncontrolledToControlled = false - - function isControlled(props) { - var usesChecked = props.type === 'checkbox' || props.type === 'radio' - return usesChecked ? props.checked != null : props.value != null - } - /** - * Implements an host component that allows setting these optional - * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. - * - * If `checked` or `value` are not supplied (or null/undefined), user actions - * that affect the checked state or value will trigger updates to the element. - * - * If they are supplied (and not null/undefined), the rendered element will not - * trigger updates to the element. Instead, the props must change in order for - * the rendered element to be updated. - * - * The rendered element will be initialized as unchecked (or `defaultChecked`) - * with an empty value (or `defaultValue`). - * - * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html - */ - - function getHostProps(element, props) { - var node = element - var checked = props.checked - - var hostProps = _assign({}, props, { - defaultChecked: undefined, - defaultValue: undefined, - value: undefined, - checked: - checked != null ? checked : node._wrapperState.initialChecked, - }) - - return hostProps - } - function initWrapperState(element, props) { - { - checkControlledValueProps('input', props) - - if ( - props.checked !== undefined && - props.defaultChecked !== undefined && - !didWarnCheckedDefaultChecked - ) { - error( - '%s contains an input of type %s with both checked and defaultChecked props. ' + - 'Input elements must be either controlled or uncontrolled ' + - '(specify either the checked prop, or the defaultChecked prop, but not ' + - 'both). Decide between using a controlled or uncontrolled input ' + - 'element and remove one of these props. More info: ' + - 'https://reactjs.org/link/controlled-components', - getCurrentFiberOwnerNameInDevOrNull() || 'A component', - props.type - ) - - didWarnCheckedDefaultChecked = true - } - - if ( - props.value !== undefined && - props.defaultValue !== undefined && - !didWarnValueDefaultValue - ) { - error( - '%s contains an input of type %s with both value and defaultValue props. ' + - 'Input elements must be either controlled or uncontrolled ' + - '(specify either the value prop, or the defaultValue prop, but not ' + - 'both). Decide between using a controlled or uncontrolled input ' + - 'element and remove one of these props. More info: ' + - 'https://reactjs.org/link/controlled-components', - getCurrentFiberOwnerNameInDevOrNull() || 'A component', - props.type - ) - - didWarnValueDefaultValue = true - } - } - - var node = element - var defaultValue = props.defaultValue == null ? '' : props.defaultValue - node._wrapperState = { - initialChecked: - props.checked != null ? props.checked : props.defaultChecked, - initialValue: getToStringValue( - props.value != null ? props.value : defaultValue - ), - controlled: isControlled(props), - } - } - function updateChecked(element, props) { - var node = element - var checked = props.checked - - if (checked != null) { - setValueForProperty(node, 'checked', checked, false) - } - } - function updateWrapper(element, props) { - var node = element - - { - var controlled = isControlled(props) - - if ( - !node._wrapperState.controlled && - controlled && - !didWarnUncontrolledToControlled - ) { - error( - 'A component is changing an uncontrolled input to be controlled. ' + - 'This is likely caused by the value changing from undefined to ' + - 'a defined value, which should not happen. ' + - 'Decide between using a controlled or uncontrolled input ' + - 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components' - ) - - didWarnUncontrolledToControlled = true - } - - if ( - node._wrapperState.controlled && - !controlled && - !didWarnControlledToUncontrolled - ) { - error( - 'A component is changing a controlled input to be uncontrolled. ' + - 'This is likely caused by the value changing from a defined to ' + - 'undefined, which should not happen. ' + - 'Decide between using a controlled or uncontrolled input ' + - 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components' - ) - - didWarnControlledToUncontrolled = true - } - } - - updateChecked(element, props) - var value = getToStringValue(props.value) - var type = props.type - - if (value != null) { - if (type === 'number') { - if ( - (value === 0 && node.value === '') || // We explicitly want to coerce to number here if possible. - // eslint-disable-next-line - node.value != value - ) { - node.value = toString(value) - } - } else if (node.value !== toString(value)) { - node.value = toString(value) - } - } else if (type === 'submit' || type === 'reset') { - // Submit/reset inputs need the attribute removed completely to avoid - // blank-text buttons. - node.removeAttribute('value') - return - } - - { - // When syncing the value attribute, the value comes from a cascade of - // properties: - // 1. The value React property - // 2. The defaultValue React property - // 3. Otherwise there should be no change - if (props.hasOwnProperty('value')) { - setDefaultValue(node, props.type, value) - } else if (props.hasOwnProperty('defaultValue')) { - setDefaultValue( - node, - props.type, - getToStringValue(props.defaultValue) - ) - } - } - - { - // When syncing the checked attribute, it only changes when it needs - // to be removed, such as transitioning from a checkbox into a text input - if (props.checked == null && props.defaultChecked != null) { - node.defaultChecked = !!props.defaultChecked - } - } - } - function postMountWrapper(element, props, isHydrating) { - var node = element // Do not assign value if it is already set. This prevents user text input - // from being lost during SSR hydration. - - if ( - props.hasOwnProperty('value') || - props.hasOwnProperty('defaultValue') - ) { - var type = props.type - var isButton = type === 'submit' || type === 'reset' // Avoid setting value attribute on submit/reset inputs as it overrides the - // default value provided by the browser. See: #12872 - - if (isButton && (props.value === undefined || props.value === null)) { - return - } - - var initialValue = toString(node._wrapperState.initialValue) // Do not assign value if it is already set. This prevents user text input - // from being lost during SSR hydration. - - if (!isHydrating) { - { - // When syncing the value attribute, the value property should use - // the wrapperState._initialValue property. This uses: - // - // 1. The value React property when present - // 2. The defaultValue React property when present - // 3. An empty string - if (initialValue !== node.value) { - node.value = initialValue - } - } - } - - { - // Otherwise, the value attribute is synchronized to the property, - // so we assign defaultValue to the same thing as the value property - // assignment step above. - node.defaultValue = initialValue - } - } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug - // this is needed to work around a chrome bug where setting defaultChecked - // will sometimes influence the value of checked (even after detachment). - // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 - // We need to temporarily unset name to avoid disrupting radio button groups. - - var name = node.name - - if (name !== '') { - node.name = '' - } - - { - // When syncing the checked attribute, both the checked property and - // attribute are assigned at the same time using defaultChecked. This uses: - // - // 1. The checked React property when present - // 2. The defaultChecked React property when present - // 3. Otherwise, false - node.defaultChecked = !node.defaultChecked - node.defaultChecked = !!node._wrapperState.initialChecked - } - - if (name !== '') { - node.name = name - } - } - function restoreControlledState(element, props) { - var node = element - updateWrapper(node, props) - updateNamedCousins(node, props) - } - - function updateNamedCousins(rootNode, props) { - var name = props.name - - if (props.type === 'radio' && name != null) { - var queryRoot = rootNode - - while (queryRoot.parentNode) { - queryRoot = queryRoot.parentNode - } // If `rootNode.form` was non-null, then we could try `form.elements`, - // but that sometimes behaves strangely in IE8. We could also try using - // `form.getElementsByName`, but that will only return direct children - // and won't include inputs that use the HTML5 `form=` attribute. Since - // the input might not even be in a form. It might not even be in the - // document. Let's just use the local `querySelectorAll` to ensure we don't - // miss anything. - - var group = queryRoot.querySelectorAll( - 'input[name=' + JSON.stringify('' + name) + '][type="radio"]' - ) - - for (var i = 0; i < group.length; i++) { - var otherNode = group[i] - - if (otherNode === rootNode || otherNode.form !== rootNode.form) { - continue - } // This will throw if radio buttons rendered by different copies of React - // and the same name are rendered into the same form (same as #1939). - // That's probably okay; we don't support it just as we don't support - // mixing React radio buttons with non-React ones. - - var otherProps = getFiberCurrentPropsFromNode(otherNode) - - if (!otherProps) { - { - throw Error( - 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.' - ) - } - } // We need update the tracked value on the named cousin since the value - // was changed but the input saw no event or value set - - updateValueIfChanged(otherNode) // If this is a controlled radio button group, forcing the input that - // was previously checked to update will cause it to be come re-checked - // as appropriate. - - updateWrapper(otherNode, otherProps) - } - } - } // In Chrome, assigning defaultValue to certain input types triggers input validation. - // For number inputs, the display value loses trailing decimal points. For email inputs, - // Chrome raises "The specified value is not a valid email address". - // - // Here we check to see if the defaultValue has actually changed, avoiding these problems - // when the user is inputting text - // - // https://github.com/facebook/react/issues/7253 - - function setDefaultValue(node, type, value) { - if ( - // Focused number inputs synchronize on blur. See ChangeEventPlugin.js - type !== 'number' || - getActiveElement(node.ownerDocument) !== node - ) { - if (value == null) { - node.defaultValue = toString(node._wrapperState.initialValue) - } else if (node.defaultValue !== toString(value)) { - node.defaultValue = toString(value) - } - } - } - - var didWarnSelectedSetOnOption = false - var didWarnInvalidChild = false - - function flattenChildren(children) { - var content = '' // Flatten children. We'll warn if they are invalid - // during validateProps() which runs for hydration too. - // Note that this would throw on non-element objects. - // Elements are stringified (which is normally irrelevant - // but matters for ). - - React.Children.forEach(children, function (child) { - if (child == null) { - return - } - - content += child // Note: we don't warn about invalid children here. - // Instead, this is done separately below so that - // it happens during the hydration code path too. - }) - return content - } - /** - * Implements an