tlvince-react-timeago
Version:
A simple Time-Ago component for ReactJs
170 lines (133 loc) • 7.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = 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; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _defaultFormatter = require('./defaultFormatter');
var _defaultFormatter2 = _interopRequireDefault(_defaultFormatter);
var _dateParser = require('./dateParser');
var _dateParser2 = _interopRequireDefault(_dateParser);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MINUTE = 60;
var HOUR = MINUTE * 60;
var DAY = HOUR * 24;
var WEEK = DAY * 7;
var MONTH = DAY * 30;
var YEAR = DAY * 365;
var TimeAgo = function (_Component) {
_inherits(TimeAgo, _Component);
function TimeAgo() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, TimeAgo);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = TimeAgo.__proto__ || Object.getPrototypeOf(TimeAgo)).call.apply(_ref, [this].concat(args))), _this), _this.isStillMounted = false, _this.tick = function (refresh) {
if (!_this.isStillMounted || !_this.props.live) {
return;
}
var then = (0, _dateParser2.default)(_this.props.date).valueOf();
if (!then) {
console.warn('[react-timeago] Invalid Date provided');
return;
}
var now = _this.props.now();
var seconds = Math.round(Math.abs(now - then) / 1000);
var unboundPeriod = seconds < MINUTE ? 1000 : seconds < HOUR ? 1000 * MINUTE : seconds < DAY ? 1000 * HOUR : 0;
var period = Math.min(Math.max(unboundPeriod, _this.props.minPeriod * 1000), _this.props.maxPeriod * 1000);
if (period) {
_this.timeoutId = setTimeout(_this.tick, period);
}
if (!refresh) {
_this.forceUpdate();
}
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(TimeAgo, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.isStillMounted = true;
if (this.props.live) {
this.tick(true);
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(lastProps) {
if (this.props.live !== lastProps.live || this.props.date !== lastProps.date) {
if (!this.props.live && this.timeoutId) {
clearTimeout(this.timeoutId);
}
this.tick();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.isStillMounted = false;
if (this.timeoutId) {
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
}
}, {
key: 'render',
value: function render() {
/* eslint-disable no-unused-vars */
var _props = this.props,
date = _props.date,
formatter = _props.formatter,
Komponent = _props.component,
live = _props.live,
minPeriod = _props.minPeriod,
maxPeriod = _props.maxPeriod,
title = _props.title,
passDownProps = _objectWithoutProperties(_props, ['date', 'formatter', 'component', 'live', 'minPeriod', 'maxPeriod', 'title']);
/* eslint-enable no-unused-vars */
var then = (0, _dateParser2.default)(date).valueOf();
if (!then) {
return null;
}
var now = this.props.now();
var seconds = Math.round(Math.abs(now - then) / 1000);
var suffix = then < now ? 'ago' : 'from now';
var _ref2 = seconds < MINUTE ? [Math.round(seconds), 'second'] : seconds < HOUR ? [Math.round(seconds / MINUTE), 'minute'] : seconds < DAY ? [Math.round(seconds / HOUR), 'hour'] : seconds < WEEK ? [Math.round(seconds / DAY), 'day'] : seconds < MONTH ? [Math.round(seconds / WEEK), 'week'] : seconds < YEAR ? [Math.round(seconds / MONTH), 'month'] : [Math.round(seconds / YEAR), 'year'],
_ref3 = _slicedToArray(_ref2, 2),
value = _ref3[0],
unit = _ref3[1];
var passDownTitle = typeof title === 'undefined' ? typeof date === 'string' ? date : (0, _dateParser2.default)(date).toISOString().substr(0, 16).replace('T', ' ') : title;
if (Komponent === 'time') {
passDownProps.dateTime = (0, _dateParser2.default)(date).toISOString();
delete passDownProps.now;
}
var nextFormatter = _defaultFormatter2.default.bind(null, value, unit, suffix, then);
return _react2.default.createElement(
Komponent,
_extends({}, passDownProps, { title: passDownTitle }),
this.props.formatter(value, unit, suffix, then, nextFormatter)
);
}
}]);
return TimeAgo;
}(_react.Component);
TimeAgo.displayName = 'TimeAgo';
TimeAgo.defaultProps = {
live: true,
component: 'time',
minPeriod: 0,
maxPeriod: Infinity,
formatter: _defaultFormatter2.default,
now: function now() {
return Date.now();
}
};
exports.default = TimeAgo;