@shopgate/engage
Version:
Shopgate's ENGAGE library.
91 lines (88 loc) • 2.42 kB
JavaScript
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _isEqual from "lodash/isEqual";
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { isBefore, isAfter, isBetween } from '@shopgate/pwa-common/helpers/date';
import { second$ } from '@shopgate/pwa-common/streams/interval';
/**
* The TimeBoundary component.
* @example
* <TimeBoundary
* start={new Date('2019-04-10T11:01:00.000Z')}
* end={new Date('2019-04-10T12:01:00.000Z')}
* >
* {({ before, between, after }) => (
{between && <div>Content is inside time boundary</div>}
)}
* </TimeBoundary>
*/
import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
let TimeBoundary = /*#__PURE__*/function (_Component) {
/**
* @inheritDoc
*/
function TimeBoundary(props) {
var _this;
_this = _Component.call(this, props) || this;
/** Clear interval if valid */
_this.clear = () => {
if (_this.intervalSubscription) {
_this.intervalSubscription.unsubscribe();
}
};
/**
* Check time boundary.
*/
_this.checkBoundary = () => {
const now = new Date(Date.now());
const newState = {
before: isBefore(now, _this.props.start),
between: isBetween(now, _this.props.start, _this.props.end),
after: isAfter(now, _this.props.end)
};
if (_isEqual(newState, _this.state)) {
return;
}
_this.setState(newState);
if (newState.after) {
// already after, stop timer
_this.clear();
}
};
_this.state = {
before: false,
between: false,
after: false
};
return _this;
}
/**
* @inheritDoc
*/
_inheritsLoose(TimeBoundary, _Component);
var _proto = TimeBoundary.prototype;
_proto.componentDidMount = function componentDidMount() {
this.intervalSubscription = second$.subscribe(this.checkBoundary);
this.checkBoundary();
}
/**
* @inheritDoc
*/;
_proto.componentWillUnmount = function componentWillUnmount() {
this.clear();
};
/**
* @returns {JSX}
*/
_proto.render = function render() {
return /*#__PURE__*/_jsx(_Fragment, {
children: this.props.children(this.state)
});
};
return TimeBoundary;
}(Component);
TimeBoundary.defaultProps = {
end: null,
start: null
};
export default TimeBoundary;