@dh-react-hooks/use-timeago
Advanced tools
Comparing version 0.4.1 to 0.4.4
@@ -7,6 +7,3 @@ module.exports = { | ||
}, | ||
extends: [ | ||
'plugin:@typescript-eslint/recommended', | ||
'prettier/@typescript-eslint' | ||
], | ||
extends: ['plugin:@typescript-eslint/recommended', 'prettier'], | ||
plugins: ['@typescript-eslint', 'react', 'react-hooks'], | ||
@@ -13,0 +10,0 @@ parserOptions: { |
@@ -6,2 +6,30 @@ # Change Log | ||
## 0.4.4 (2023-06-18) | ||
**Note:** Version bump only for package @dh-react-hooks/use-timeago | ||
## 0.4.3 (2023-06-18) | ||
**Note:** Version bump only for package @dh-react-hooks/use-timeago | ||
## [0.4.2](https://github.com/danhuang1202/DrHooks/compare/@dh-react-hooks/use-timeago@0.4.1...@dh-react-hooks/use-timeago@0.4.2) (2023-06-18) | ||
### Bug Fixes | ||
* add react@18 to peerDependencies ([9ce2140](https://github.com/danhuang1202/DrHooks/commit/9ce2140e2e7f8d3f63c8d51dc018ce472fe8f20e)) | ||
* update package.json and package-lock.json ([2d14baa](https://github.com/danhuang1202/DrHooks/commit/2d14baa41b5aad1f55a2e47b5f5850a5cc35d599)) | ||
## [0.4.1](https://github.com/danhuang1202/DrHooks/compare/@dh-react-hooks/use-timeago@0.4.0...@dh-react-hooks/use-timeago@0.4.1) (2021-02-21) | ||
@@ -8,0 +36,0 @@ |
650
es/index.js
import { useState, useEffect } from 'react'; | ||
function _defineProperty(obj, key, value) { | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
function _iterableToArrayLimit(arr, i) { | ||
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; | ||
if (null != _i) { | ||
var _s, | ||
_e, | ||
_x, | ||
_r, | ||
_arr = [], | ||
_n = !0, | ||
_d = !1; | ||
try { | ||
if (_x = (_i = _i.call(arr)).next, 0 === i) { | ||
if (Object(_i) !== _i) return; | ||
_n = !1; | ||
} else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); | ||
} catch (err) { | ||
_d = !0, _e = err; | ||
} finally { | ||
try { | ||
if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; | ||
} finally { | ||
if (_d) throw _e; | ||
} | ||
} | ||
return _arr; | ||
} | ||
return obj; | ||
} | ||
function ownKeys(object, enumerableOnly) { | ||
var keys = Object.keys(object); | ||
if (Object.getOwnPropertySymbols) { | ||
var symbols = Object.getOwnPropertySymbols(object); | ||
if (enumerableOnly) symbols = symbols.filter(function (sym) { | ||
enumerableOnly && (symbols = symbols.filter(function (sym) { | ||
return Object.getOwnPropertyDescriptor(object, sym).enumerable; | ||
}); | ||
keys.push.apply(keys, symbols); | ||
})), keys.push.apply(keys, symbols); | ||
} | ||
return keys; | ||
} | ||
function _objectSpread2(target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i] != null ? arguments[i] : {}; | ||
if (i % 2) { | ||
ownKeys(source, true).forEach(function (key) { | ||
_defineProperty(target, key, source[key]); | ||
}); | ||
} else if (Object.getOwnPropertyDescriptors) { | ||
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); | ||
} else { | ||
ownKeys(source).forEach(function (key) { | ||
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | ||
}); | ||
} | ||
var source = null != arguments[i] ? arguments[i] : {}; | ||
i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { | ||
_defineProperty(target, key, source[key]); | ||
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { | ||
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | ||
}); | ||
} | ||
return target; | ||
} | ||
function _defineProperty(obj, key, value) { | ||
key = _toPropertyKey(key); | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
} | ||
return obj; | ||
} | ||
function _slicedToArray(arr, i) { | ||
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); | ||
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); | ||
} | ||
function _arrayWithHoles(arr) { | ||
if (Array.isArray(arr)) return arr; | ||
} | ||
function _iterableToArrayLimit(arr, i) { | ||
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { | ||
return; | ||
} | ||
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"] != null) _i["return"](); | ||
} finally { | ||
if (_d) throw _e; | ||
} | ||
} | ||
return _arr; | ||
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 _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 _nonIterableRest() { | ||
throw new TypeError("Invalid attempt to destructure non-iterable instance"); | ||
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
function _toPrimitive(input, hint) { | ||
if (typeof input !== "object" || input === null) return input; | ||
var prim = input[Symbol.toPrimitive]; | ||
if (prim !== undefined) { | ||
var res = prim.call(input, hint || "default"); | ||
if (typeof res !== "object") return res; | ||
throw new TypeError("@@toPrimitive must return a primitive value."); | ||
} | ||
return (hint === "string" ? String : Number)(input); | ||
} | ||
function _toPropertyKey(arg) { | ||
var key = _toPrimitive(arg, "string"); | ||
return typeof key === "symbol" ? key : String(key); | ||
} | ||
function unwrapExports (x) { | ||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; | ||
var EN_US = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year']; | ||
function en_US (diff, idx) { | ||
if (idx === 0) | ||
return ['just now', 'right now']; | ||
var unit = EN_US[Math.floor(idx / 2)]; | ||
if (diff > 1) | ||
unit += 's'; | ||
return [diff + " " + unit + " ago", "in " + diff + " " + unit]; | ||
} | ||
function createCommonjsModule(fn, module) { | ||
return module = { exports: {} }, fn(module, module.exports), module.exports; | ||
var ZH_CN = ['秒', '分钟', '小时', '天', '周', '个月', '年']; | ||
function zh_CN (diff, idx) { | ||
if (idx === 0) | ||
return ['刚刚', '片刻后']; | ||
var unit = ZH_CN[~~(idx / 2)]; | ||
return [diff + " " + unit + "\u524D", diff + " " + unit + "\u540E"]; | ||
} | ||
var date = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.nextInterval = exports.diffSec = exports.formatDiff = exports.toDate = exports.toInt = void 0; | ||
/** | ||
@@ -113,365 +124,131 @@ * Created by hustcc on 18/5/20. | ||
*/ | ||
var SEC_ARRAY = [60, 60, 24, 7, 365 / 7 / 12, 12]; | ||
/** | ||
* change f into int, remove decimal. Just for code compression | ||
* @param f | ||
* @returns {number} | ||
* All supported locales | ||
*/ | ||
var toInt = function toInt(f) { | ||
return parseInt(f); | ||
}; | ||
var Locales = {}; | ||
/** | ||
* format Date / string / timestamp to Date instance. | ||
* @param input | ||
* @returns {*} | ||
* register a locale | ||
* @param locale | ||
* @param func | ||
*/ | ||
exports.toInt = toInt; | ||
var toDate = function toDate(input) { | ||
if (input instanceof Date) return input; | ||
if (!isNaN(input) || /^\d+$/.test(input)) return new Date(toInt(input)); | ||
input = (input || '').trim().replace(/\.\d+/, '') // remove milliseconds | ||
.replace(/-/, '/').replace(/-/, '/').replace(/(\d)T(\d)/, '$1 $2').replace(/Z/, ' UTC') // 2017-2-5T3:57:52Z -> 2017-2-5 3:57:52UTC | ||
.replace(/([\+\-]\d\d)\:?(\d\d)/, ' $1$2'); // -04:00 -> -0400 | ||
return new Date(input); | ||
var register = function (locale, func) { | ||
Locales[locale] = func; | ||
}; | ||
/** | ||
* format the diff second to *** time ago, with setting locale | ||
* @param diff | ||
* @param localeFunc | ||
* @returns {string | void | *} | ||
* get a locale, default is en_US | ||
* @param locale | ||
* @returns {*} | ||
*/ | ||
exports.toDate = toDate; | ||
var formatDiff = function formatDiff(diff, localeFunc) { | ||
// if locale is not exist, use defaultLocale. | ||
// if defaultLocale is not exist, use build-in `en`. | ||
// be sure of no error when locale is not exist. | ||
var i = 0, | ||
agoin = diff < 0 ? 1 : 0, | ||
// timein or timeago | ||
total_sec = diff = Math.abs(diff); | ||
for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY.length; i++) { | ||
diff /= SEC_ARRAY[i]; | ||
} | ||
diff = toInt(diff); | ||
i *= 2; | ||
if (diff > (i === 0 ? 9 : 1)) i += 1; | ||
return localeFunc(diff, i, total_sec)[agoin].replace('%s', diff); | ||
var getLocale = function (locale) { | ||
return Locales[locale] || Locales['en_US']; | ||
}; | ||
/** | ||
* calculate the diff second between date to be formatted an now date. | ||
* @param date | ||
* @param nowDate | ||
* @returns {number} | ||
*/ | ||
exports.formatDiff = formatDiff; | ||
var diffSec = function diffSec(date, nowDate) { | ||
nowDate = nowDate ? toDate(nowDate) : new Date(); | ||
return (nowDate - toDate(date)) / 1000; | ||
}; | ||
/** | ||
* nextInterval: calculate the next interval time. | ||
* - diff: the diff sec between now and date to be formatted. | ||
* | ||
* What's the meaning? | ||
* diff = 61 then return 59 | ||
* diff = 3601 (an hour + 1 second), then return 3599 | ||
* make the interval with high performance. | ||
**/ | ||
exports.diffSec = diffSec; | ||
var nextInterval = function nextInterval(diff) { | ||
var rst = 1, | ||
i = 0, | ||
d = Math.abs(diff); | ||
for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY.length; i++) { | ||
diff /= SEC_ARRAY[i]; | ||
rst *= SEC_ARRAY[i]; | ||
} | ||
d = d % rst; | ||
d = d ? rst - d : rst; | ||
return Math.ceil(d); | ||
}; | ||
exports.nextInterval = nextInterval; | ||
}); | ||
unwrapExports(date); | ||
var date_1 = date.nextInterval; | ||
var date_2 = date.diffSec; | ||
var date_3 = date.formatDiff; | ||
var date_4 = date.toDate; | ||
var date_5 = date.toInt; | ||
var locales = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.getLocale = exports.register = void 0; | ||
/** | ||
* Created by hustcc on 18/5/20. | ||
* Contract: i@hust.cc | ||
*/ | ||
var EN = 'second_minute_hour_day_week_month_year'.split('_'); | ||
var ZH = '秒_分钟_小时_天_周_个月_年'.split('_'); | ||
var zh_CN = function zh_CN(number, index) { | ||
if (index === 0) return ['刚刚', '片刻后']; | ||
var unit = ZH[parseInt(index / 2)]; | ||
return ["".concat(number, " ").concat(unit, "\u524D"), "".concat(number, " ").concat(unit, "\u540E")]; | ||
}; | ||
var en_US = function en_US(number, index) { | ||
if (index === 0) return ['just now', 'right now']; | ||
var unit = EN[parseInt(index / 2)]; | ||
if (number > 1) unit += 's'; | ||
return ["".concat(number, " ").concat(unit, " ago"), "in ".concat(number, " ").concat(unit)]; | ||
}; | ||
var SEC_ARRAY = [ | ||
60, | ||
60, | ||
24, | ||
7, | ||
365 / 7 / 12, | ||
12, | ||
]; | ||
/** | ||
* 所有的语言 | ||
* @type {{en: function(*, *), zh_CN: function(*, *)}} | ||
*/ | ||
var Locales = { | ||
en_US: en_US, | ||
zh_CN: zh_CN | ||
}; | ||
/** | ||
* 注册语言 | ||
* @param locale | ||
* @param func | ||
*/ | ||
var register = function register(locale, func) { | ||
Locales[locale] = func; | ||
}; | ||
/** | ||
* 获取语言函数 | ||
* @param locale | ||
* format Date / string / timestamp to timestamp | ||
* @param input | ||
* @returns {*} | ||
*/ | ||
exports.register = register; | ||
var getLocale = function getLocale(locale) { | ||
return Locales[locale] || en_US; | ||
}; | ||
exports.getLocale = getLocale; | ||
}); | ||
unwrapExports(locales); | ||
var locales_1 = locales.getLocale; | ||
var locales_2 = locales.register; | ||
var format_1 = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.format = void 0; | ||
var format = function format(date$1, locale, nowDate) { | ||
// diff seconds | ||
var sec = (0, date.diffSec)(date$1, nowDate); // format it with locale | ||
return (0, date.formatDiff)(sec, (0, locales.getLocale)(locale)); | ||
}; | ||
exports.format = format; | ||
}); | ||
unwrapExports(format_1); | ||
var format_2 = format_1.format; | ||
var dom = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.getTimerId = exports.saveTimerId = exports.getDateAttribute = void 0; | ||
var ATTR_TIMEAGO_TID = 'timeago-tid'; | ||
var ATTR_DATETIME = 'datetime'; | ||
function toDate(input) { | ||
if (input instanceof Date) | ||
return input; | ||
// @ts-ignore | ||
if (!isNaN(input) || /^\d+$/.test(input)) | ||
return new Date(parseInt(input)); | ||
input = (input || '') | ||
// @ts-ignore | ||
.trim() | ||
.replace(/\.\d+/, '') // remove milliseconds | ||
.replace(/-/, '/') | ||
.replace(/-/, '/') | ||
.replace(/(\d)T(\d)/, '$1 $2') | ||
.replace(/Z/, ' UTC') // 2017-2-5T3:57:52Z -> 2017-2-5 3:57:52UTC | ||
.replace(/([+-]\d\d):?(\d\d)/, ' $1$2'); // -04:00 -> -0400 | ||
return new Date(input); | ||
} | ||
/** | ||
* get the node attribute, native DOM and jquery supported. | ||
* @param node | ||
* @param name | ||
* @returns {*} | ||
* format the diff second to *** time ago, with setting locale | ||
* @param diff | ||
* @param localeFunc | ||
* @returns | ||
*/ | ||
var getAttribute = function getAttribute(node, name) { | ||
if (node.getAttribute) return node.getAttribute(name); // native dom | ||
if (node.attr) return node.attr(name); // jquery dom | ||
}; | ||
function formatDiff(diff, localeFunc) { | ||
/** | ||
* if locale is not exist, use defaultLocale. | ||
* if defaultLocale is not exist, use build-in `en`. | ||
* be sure of no error when locale is not exist. | ||
* | ||
* If `time in`, then 1 | ||
* If `time ago`, then 0 | ||
*/ | ||
var agoIn = diff < 0 ? 1 : 0; | ||
/** | ||
* Get absolute value of number (|diff| is non-negative) value of x | ||
* |diff| = diff if diff is positive | ||
* |diff| = -diff if diff is negative | ||
* |0| = 0 | ||
*/ | ||
diff = Math.abs(diff); | ||
/** | ||
* Time in seconds | ||
*/ | ||
var totalSec = diff; | ||
/** | ||
* Unit of time | ||
*/ | ||
var idx = 0; | ||
for (; diff >= SEC_ARRAY[idx] && idx < SEC_ARRAY.length; idx++) { | ||
diff /= SEC_ARRAY[idx]; | ||
} | ||
/** | ||
* Math.floor() is alternative of ~~ | ||
* | ||
* The differences and bugs: | ||
* Math.floor(3.7) -> 4 but ~~3.7 -> 3 | ||
* Math.floor(1559125440000.6) -> 1559125440000 but ~~1559125440000.6 -> 52311552 | ||
* | ||
* More information about the performance of algebraic: | ||
* https://www.youtube.com/watch?v=65-RbBwZQdU | ||
*/ | ||
diff = Math.floor(diff); | ||
idx *= 2; | ||
if (diff > (idx === 0 ? 9 : 1)) | ||
idx += 1; | ||
return localeFunc(diff, idx, totalSec)[agoIn].replace('%s', diff.toString()); | ||
} | ||
/** | ||
* get the datetime attribute, `data-timeagp` / `datetime` are supported. | ||
* @param node | ||
* @returns {*} | ||
* calculate the diff second between date to be formatted an now date. | ||
* @param date | ||
* @param relativeDate | ||
* @returns {number} | ||
*/ | ||
function diffSec(date, relativeDate) { | ||
var relDate = relativeDate ? toDate(relativeDate) : new Date(); | ||
return (+relDate - +toDate(date)) / 1000; | ||
} | ||
var getDateAttribute = function getDateAttribute(node) { | ||
return getAttribute(node, ATTR_DATETIME); | ||
}; | ||
/** | ||
* set the node attribute, native DOM and jquery supported. | ||
* @param node | ||
* @param timerId | ||
* @returns {*} | ||
* format a TDate into string | ||
* @param date | ||
* @param locale | ||
* @param opts | ||
*/ | ||
exports.getDateAttribute = getDateAttribute; | ||
var saveTimerId = function saveTimerId(node, timerId) { | ||
if (node.setAttribute) return node.setAttribute(ATTR_TIMEAGO_TID, timerId); | ||
if (node.attr) return node.attr(ATTR_TIMEAGO_TID, timerId); | ||
var format = function (date, locale, opts) { | ||
// diff seconds | ||
var sec = diffSec(date, opts && opts.relativeDate); | ||
// format it with locale | ||
return formatDiff(sec, getLocale(locale)); | ||
}; | ||
exports.saveTimerId = saveTimerId; | ||
var getTimerId = function getTimerId(node) { | ||
return getAttribute(node, ATTR_TIMEAGO_TID); | ||
}; | ||
exports.getTimerId = getTimerId; | ||
}); | ||
unwrapExports(dom); | ||
var dom_1 = dom.getTimerId; | ||
var dom_2 = dom.saveTimerId; | ||
var dom_3 = dom.getDateAttribute; | ||
var realtime = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.render = exports.cancel = void 0; | ||
// 所有的 timer | ||
var TimerPool = {}; | ||
var clear = function clear(tid) { | ||
clearTimeout(tid); | ||
delete TimerPool[tid]; | ||
}; // 定时运行 | ||
var run = function run(node, date$1, localeFunc, nowDate) { | ||
// 先清理掉之前的 | ||
clear((0, dom.getTimerId)(node)); // get diff seconds | ||
var diff = (0, date.diffSec)(date$1, nowDate); // render | ||
node.innerHTML = (0, date.formatDiff)(diff, localeFunc); | ||
var tid = setTimeout(function () { | ||
run(node, date$1, localeFunc, nowDate); | ||
}, (0, date.nextInterval)(diff) * 1000, 0x7FFFFFFF); // there is no need to save node in object. Just save the key | ||
TimerPool[tid] = 0; | ||
(0, dom.saveTimerId)(node, tid); | ||
}; // 取消一个 node 的实时渲染 | ||
var cancel = function cancel(node) { | ||
if (node) clear((0, dom.getTimerId)(node)); // get the timer of DOM node(native / jq). | ||
else for (var tid in TimerPool) { | ||
clear(tid); | ||
} | ||
}; // 实时渲染一系列节点 | ||
exports.cancel = cancel; | ||
var render = function render(nodes, locale, nowDate) { | ||
// by .length | ||
if (nodes.length === undefined) nodes = [nodes]; | ||
var node; | ||
for (var i = 0; i < nodes.length; i++) { | ||
node = nodes[i]; | ||
var date = (0, dom.getDateAttribute)(node); | ||
var localeFunc = (0, locales.getLocale)(locale); | ||
run(node, date, localeFunc, nowDate); | ||
} | ||
return nodes; | ||
}; | ||
exports.render = render; | ||
}); | ||
unwrapExports(realtime); | ||
var realtime_1 = realtime.render; | ||
var realtime_2 = realtime.cancel; | ||
var lib = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
Object.defineProperty(exports, "format", { | ||
enumerable: true, | ||
get: function get() { | ||
return format_1.format; | ||
} | ||
}); | ||
Object.defineProperty(exports, "render", { | ||
enumerable: true, | ||
get: function get() { | ||
return realtime.render; | ||
} | ||
}); | ||
Object.defineProperty(exports, "cancel", { | ||
enumerable: true, | ||
get: function get() { | ||
return realtime.cancel; | ||
} | ||
}); | ||
Object.defineProperty(exports, "register", { | ||
enumerable: true, | ||
get: function get() { | ||
return locales.register; | ||
} | ||
}); | ||
exports.version = void 0; | ||
/** | ||
@@ -481,13 +258,9 @@ * Created by hustcc on 18/5/20. | ||
*/ | ||
var version = "4.0.0-beta.2"; | ||
exports.version = version; | ||
}); | ||
register('en_US', en_US); | ||
register('zh_CN', zh_CN); | ||
unwrapExports(lib); | ||
var lib_1 = lib.format; | ||
var lib_2 = lib.register; | ||
var lib_3 = lib.version; | ||
/** start date, could be Date instance, timestamp or date string */ | ||
/** timeago string */ | ||
var defaultOptions = { | ||
@@ -497,24 +270,21 @@ locale: 'en_US', | ||
}; | ||
var useTimeAgo = function useTimeAgo(dateTime, options) { | ||
var _useState = useState(null), | ||
_useState2 = _slicedToArray(_useState, 2), | ||
timeago = _useState2[0], | ||
setTimeago = _useState2[1]; | ||
var _defaultOptions$optio = _objectSpread2({}, defaultOptions, {}, options), | ||
locale = _defaultOptions$optio.locale, | ||
localeRegister = _defaultOptions$optio.localeRegister, | ||
interval = _defaultOptions$optio.interval; | ||
_useState2 = _slicedToArray(_useState, 2), | ||
timeago = _useState2[0], | ||
setTimeago = _useState2[1]; | ||
var _defaultOptions$optio = _objectSpread2(_objectSpread2({}, defaultOptions), options), | ||
locale = _defaultOptions$optio.locale, | ||
localeRegister = _defaultOptions$optio.localeRegister, | ||
interval = _defaultOptions$optio.interval; | ||
var updateTimeAge = function updateTimeAge() { | ||
setTimeago(lib_1(dateTime, locale)); | ||
setTimeago(format(dateTime, locale)); | ||
}; | ||
useEffect(function () { | ||
if (localeRegister) { | ||
lib_2(locale, localeRegister); | ||
register(locale, localeRegister); | ||
} | ||
updateTimeAge(); | ||
updateTimeAge(); // eslint-disable-next-line react-hooks/exhaustive-deps | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, []); | ||
@@ -525,3 +295,5 @@ useEffect(function () { | ||
clearInterval(intervalId); | ||
}; // eslint-disable-next-line react-hooks/exhaustive-deps | ||
}; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [dateTime, interval]); | ||
@@ -528,0 +300,0 @@ return timeago; |
650
lib/index.js
@@ -5,108 +5,119 @@ 'use strict'; | ||
function _defineProperty(obj, key, value) { | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
function _iterableToArrayLimit(arr, i) { | ||
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; | ||
if (null != _i) { | ||
var _s, | ||
_e, | ||
_x, | ||
_r, | ||
_arr = [], | ||
_n = !0, | ||
_d = !1; | ||
try { | ||
if (_x = (_i = _i.call(arr)).next, 0 === i) { | ||
if (Object(_i) !== _i) return; | ||
_n = !1; | ||
} else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); | ||
} catch (err) { | ||
_d = !0, _e = err; | ||
} finally { | ||
try { | ||
if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; | ||
} finally { | ||
if (_d) throw _e; | ||
} | ||
} | ||
return _arr; | ||
} | ||
return obj; | ||
} | ||
function ownKeys(object, enumerableOnly) { | ||
var keys = Object.keys(object); | ||
if (Object.getOwnPropertySymbols) { | ||
var symbols = Object.getOwnPropertySymbols(object); | ||
if (enumerableOnly) symbols = symbols.filter(function (sym) { | ||
enumerableOnly && (symbols = symbols.filter(function (sym) { | ||
return Object.getOwnPropertyDescriptor(object, sym).enumerable; | ||
}); | ||
keys.push.apply(keys, symbols); | ||
})), keys.push.apply(keys, symbols); | ||
} | ||
return keys; | ||
} | ||
function _objectSpread2(target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i] != null ? arguments[i] : {}; | ||
if (i % 2) { | ||
ownKeys(source, true).forEach(function (key) { | ||
_defineProperty(target, key, source[key]); | ||
}); | ||
} else if (Object.getOwnPropertyDescriptors) { | ||
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); | ||
} else { | ||
ownKeys(source).forEach(function (key) { | ||
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | ||
}); | ||
} | ||
var source = null != arguments[i] ? arguments[i] : {}; | ||
i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { | ||
_defineProperty(target, key, source[key]); | ||
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { | ||
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | ||
}); | ||
} | ||
return target; | ||
} | ||
function _defineProperty(obj, key, value) { | ||
key = _toPropertyKey(key); | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
} | ||
return obj; | ||
} | ||
function _slicedToArray(arr, i) { | ||
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); | ||
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); | ||
} | ||
function _arrayWithHoles(arr) { | ||
if (Array.isArray(arr)) return arr; | ||
} | ||
function _iterableToArrayLimit(arr, i) { | ||
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { | ||
return; | ||
} | ||
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"] != null) _i["return"](); | ||
} finally { | ||
if (_d) throw _e; | ||
} | ||
} | ||
return _arr; | ||
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 _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 _nonIterableRest() { | ||
throw new TypeError("Invalid attempt to destructure non-iterable instance"); | ||
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
function _toPrimitive(input, hint) { | ||
if (typeof input !== "object" || input === null) return input; | ||
var prim = input[Symbol.toPrimitive]; | ||
if (prim !== undefined) { | ||
var res = prim.call(input, hint || "default"); | ||
if (typeof res !== "object") return res; | ||
throw new TypeError("@@toPrimitive must return a primitive value."); | ||
} | ||
return (hint === "string" ? String : Number)(input); | ||
} | ||
function _toPropertyKey(arg) { | ||
var key = _toPrimitive(arg, "string"); | ||
return typeof key === "symbol" ? key : String(key); | ||
} | ||
function unwrapExports (x) { | ||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; | ||
var EN_US = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year']; | ||
function en_US (diff, idx) { | ||
if (idx === 0) | ||
return ['just now', 'right now']; | ||
var unit = EN_US[Math.floor(idx / 2)]; | ||
if (diff > 1) | ||
unit += 's'; | ||
return [diff + " " + unit + " ago", "in " + diff + " " + unit]; | ||
} | ||
function createCommonjsModule(fn, module) { | ||
return module = { exports: {} }, fn(module, module.exports), module.exports; | ||
var ZH_CN = ['秒', '分钟', '小时', '天', '周', '个月', '年']; | ||
function zh_CN (diff, idx) { | ||
if (idx === 0) | ||
return ['刚刚', '片刻后']; | ||
var unit = ZH_CN[~~(idx / 2)]; | ||
return [diff + " " + unit + "\u524D", diff + " " + unit + "\u540E"]; | ||
} | ||
var date = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.nextInterval = exports.diffSec = exports.formatDiff = exports.toDate = exports.toInt = void 0; | ||
/** | ||
@@ -116,365 +127,131 @@ * Created by hustcc on 18/5/20. | ||
*/ | ||
var SEC_ARRAY = [60, 60, 24, 7, 365 / 7 / 12, 12]; | ||
/** | ||
* change f into int, remove decimal. Just for code compression | ||
* @param f | ||
* @returns {number} | ||
* All supported locales | ||
*/ | ||
var toInt = function toInt(f) { | ||
return parseInt(f); | ||
}; | ||
var Locales = {}; | ||
/** | ||
* format Date / string / timestamp to Date instance. | ||
* @param input | ||
* @returns {*} | ||
* register a locale | ||
* @param locale | ||
* @param func | ||
*/ | ||
exports.toInt = toInt; | ||
var toDate = function toDate(input) { | ||
if (input instanceof Date) return input; | ||
if (!isNaN(input) || /^\d+$/.test(input)) return new Date(toInt(input)); | ||
input = (input || '').trim().replace(/\.\d+/, '') // remove milliseconds | ||
.replace(/-/, '/').replace(/-/, '/').replace(/(\d)T(\d)/, '$1 $2').replace(/Z/, ' UTC') // 2017-2-5T3:57:52Z -> 2017-2-5 3:57:52UTC | ||
.replace(/([\+\-]\d\d)\:?(\d\d)/, ' $1$2'); // -04:00 -> -0400 | ||
return new Date(input); | ||
var register = function (locale, func) { | ||
Locales[locale] = func; | ||
}; | ||
/** | ||
* format the diff second to *** time ago, with setting locale | ||
* @param diff | ||
* @param localeFunc | ||
* @returns {string | void | *} | ||
* get a locale, default is en_US | ||
* @param locale | ||
* @returns {*} | ||
*/ | ||
exports.toDate = toDate; | ||
var formatDiff = function formatDiff(diff, localeFunc) { | ||
// if locale is not exist, use defaultLocale. | ||
// if defaultLocale is not exist, use build-in `en`. | ||
// be sure of no error when locale is not exist. | ||
var i = 0, | ||
agoin = diff < 0 ? 1 : 0, | ||
// timein or timeago | ||
total_sec = diff = Math.abs(diff); | ||
for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY.length; i++) { | ||
diff /= SEC_ARRAY[i]; | ||
} | ||
diff = toInt(diff); | ||
i *= 2; | ||
if (diff > (i === 0 ? 9 : 1)) i += 1; | ||
return localeFunc(diff, i, total_sec)[agoin].replace('%s', diff); | ||
var getLocale = function (locale) { | ||
return Locales[locale] || Locales['en_US']; | ||
}; | ||
/** | ||
* calculate the diff second between date to be formatted an now date. | ||
* @param date | ||
* @param nowDate | ||
* @returns {number} | ||
*/ | ||
exports.formatDiff = formatDiff; | ||
var diffSec = function diffSec(date, nowDate) { | ||
nowDate = nowDate ? toDate(nowDate) : new Date(); | ||
return (nowDate - toDate(date)) / 1000; | ||
}; | ||
/** | ||
* nextInterval: calculate the next interval time. | ||
* - diff: the diff sec between now and date to be formatted. | ||
* | ||
* What's the meaning? | ||
* diff = 61 then return 59 | ||
* diff = 3601 (an hour + 1 second), then return 3599 | ||
* make the interval with high performance. | ||
**/ | ||
exports.diffSec = diffSec; | ||
var nextInterval = function nextInterval(diff) { | ||
var rst = 1, | ||
i = 0, | ||
d = Math.abs(diff); | ||
for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY.length; i++) { | ||
diff /= SEC_ARRAY[i]; | ||
rst *= SEC_ARRAY[i]; | ||
} | ||
d = d % rst; | ||
d = d ? rst - d : rst; | ||
return Math.ceil(d); | ||
}; | ||
exports.nextInterval = nextInterval; | ||
}); | ||
unwrapExports(date); | ||
var date_1 = date.nextInterval; | ||
var date_2 = date.diffSec; | ||
var date_3 = date.formatDiff; | ||
var date_4 = date.toDate; | ||
var date_5 = date.toInt; | ||
var locales = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.getLocale = exports.register = void 0; | ||
/** | ||
* Created by hustcc on 18/5/20. | ||
* Contract: i@hust.cc | ||
*/ | ||
var EN = 'second_minute_hour_day_week_month_year'.split('_'); | ||
var ZH = '秒_分钟_小时_天_周_个月_年'.split('_'); | ||
var zh_CN = function zh_CN(number, index) { | ||
if (index === 0) return ['刚刚', '片刻后']; | ||
var unit = ZH[parseInt(index / 2)]; | ||
return ["".concat(number, " ").concat(unit, "\u524D"), "".concat(number, " ").concat(unit, "\u540E")]; | ||
}; | ||
var en_US = function en_US(number, index) { | ||
if (index === 0) return ['just now', 'right now']; | ||
var unit = EN[parseInt(index / 2)]; | ||
if (number > 1) unit += 's'; | ||
return ["".concat(number, " ").concat(unit, " ago"), "in ".concat(number, " ").concat(unit)]; | ||
}; | ||
var SEC_ARRAY = [ | ||
60, | ||
60, | ||
24, | ||
7, | ||
365 / 7 / 12, | ||
12, | ||
]; | ||
/** | ||
* 所有的语言 | ||
* @type {{en: function(*, *), zh_CN: function(*, *)}} | ||
*/ | ||
var Locales = { | ||
en_US: en_US, | ||
zh_CN: zh_CN | ||
}; | ||
/** | ||
* 注册语言 | ||
* @param locale | ||
* @param func | ||
*/ | ||
var register = function register(locale, func) { | ||
Locales[locale] = func; | ||
}; | ||
/** | ||
* 获取语言函数 | ||
* @param locale | ||
* format Date / string / timestamp to timestamp | ||
* @param input | ||
* @returns {*} | ||
*/ | ||
exports.register = register; | ||
var getLocale = function getLocale(locale) { | ||
return Locales[locale] || en_US; | ||
}; | ||
exports.getLocale = getLocale; | ||
}); | ||
unwrapExports(locales); | ||
var locales_1 = locales.getLocale; | ||
var locales_2 = locales.register; | ||
var format_1 = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.format = void 0; | ||
var format = function format(date$1, locale, nowDate) { | ||
// diff seconds | ||
var sec = (0, date.diffSec)(date$1, nowDate); // format it with locale | ||
return (0, date.formatDiff)(sec, (0, locales.getLocale)(locale)); | ||
}; | ||
exports.format = format; | ||
}); | ||
unwrapExports(format_1); | ||
var format_2 = format_1.format; | ||
var dom = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.getTimerId = exports.saveTimerId = exports.getDateAttribute = void 0; | ||
var ATTR_TIMEAGO_TID = 'timeago-tid'; | ||
var ATTR_DATETIME = 'datetime'; | ||
function toDate(input) { | ||
if (input instanceof Date) | ||
return input; | ||
// @ts-ignore | ||
if (!isNaN(input) || /^\d+$/.test(input)) | ||
return new Date(parseInt(input)); | ||
input = (input || '') | ||
// @ts-ignore | ||
.trim() | ||
.replace(/\.\d+/, '') // remove milliseconds | ||
.replace(/-/, '/') | ||
.replace(/-/, '/') | ||
.replace(/(\d)T(\d)/, '$1 $2') | ||
.replace(/Z/, ' UTC') // 2017-2-5T3:57:52Z -> 2017-2-5 3:57:52UTC | ||
.replace(/([+-]\d\d):?(\d\d)/, ' $1$2'); // -04:00 -> -0400 | ||
return new Date(input); | ||
} | ||
/** | ||
* get the node attribute, native DOM and jquery supported. | ||
* @param node | ||
* @param name | ||
* @returns {*} | ||
* format the diff second to *** time ago, with setting locale | ||
* @param diff | ||
* @param localeFunc | ||
* @returns | ||
*/ | ||
var getAttribute = function getAttribute(node, name) { | ||
if (node.getAttribute) return node.getAttribute(name); // native dom | ||
if (node.attr) return node.attr(name); // jquery dom | ||
}; | ||
function formatDiff(diff, localeFunc) { | ||
/** | ||
* if locale is not exist, use defaultLocale. | ||
* if defaultLocale is not exist, use build-in `en`. | ||
* be sure of no error when locale is not exist. | ||
* | ||
* If `time in`, then 1 | ||
* If `time ago`, then 0 | ||
*/ | ||
var agoIn = diff < 0 ? 1 : 0; | ||
/** | ||
* Get absolute value of number (|diff| is non-negative) value of x | ||
* |diff| = diff if diff is positive | ||
* |diff| = -diff if diff is negative | ||
* |0| = 0 | ||
*/ | ||
diff = Math.abs(diff); | ||
/** | ||
* Time in seconds | ||
*/ | ||
var totalSec = diff; | ||
/** | ||
* Unit of time | ||
*/ | ||
var idx = 0; | ||
for (; diff >= SEC_ARRAY[idx] && idx < SEC_ARRAY.length; idx++) { | ||
diff /= SEC_ARRAY[idx]; | ||
} | ||
/** | ||
* Math.floor() is alternative of ~~ | ||
* | ||
* The differences and bugs: | ||
* Math.floor(3.7) -> 4 but ~~3.7 -> 3 | ||
* Math.floor(1559125440000.6) -> 1559125440000 but ~~1559125440000.6 -> 52311552 | ||
* | ||
* More information about the performance of algebraic: | ||
* https://www.youtube.com/watch?v=65-RbBwZQdU | ||
*/ | ||
diff = Math.floor(diff); | ||
idx *= 2; | ||
if (diff > (idx === 0 ? 9 : 1)) | ||
idx += 1; | ||
return localeFunc(diff, idx, totalSec)[agoIn].replace('%s', diff.toString()); | ||
} | ||
/** | ||
* get the datetime attribute, `data-timeagp` / `datetime` are supported. | ||
* @param node | ||
* @returns {*} | ||
* calculate the diff second between date to be formatted an now date. | ||
* @param date | ||
* @param relativeDate | ||
* @returns {number} | ||
*/ | ||
function diffSec(date, relativeDate) { | ||
var relDate = relativeDate ? toDate(relativeDate) : new Date(); | ||
return (+relDate - +toDate(date)) / 1000; | ||
} | ||
var getDateAttribute = function getDateAttribute(node) { | ||
return getAttribute(node, ATTR_DATETIME); | ||
}; | ||
/** | ||
* set the node attribute, native DOM and jquery supported. | ||
* @param node | ||
* @param timerId | ||
* @returns {*} | ||
* format a TDate into string | ||
* @param date | ||
* @param locale | ||
* @param opts | ||
*/ | ||
exports.getDateAttribute = getDateAttribute; | ||
var saveTimerId = function saveTimerId(node, timerId) { | ||
if (node.setAttribute) return node.setAttribute(ATTR_TIMEAGO_TID, timerId); | ||
if (node.attr) return node.attr(ATTR_TIMEAGO_TID, timerId); | ||
var format = function (date, locale, opts) { | ||
// diff seconds | ||
var sec = diffSec(date, opts && opts.relativeDate); | ||
// format it with locale | ||
return formatDiff(sec, getLocale(locale)); | ||
}; | ||
exports.saveTimerId = saveTimerId; | ||
var getTimerId = function getTimerId(node) { | ||
return getAttribute(node, ATTR_TIMEAGO_TID); | ||
}; | ||
exports.getTimerId = getTimerId; | ||
}); | ||
unwrapExports(dom); | ||
var dom_1 = dom.getTimerId; | ||
var dom_2 = dom.saveTimerId; | ||
var dom_3 = dom.getDateAttribute; | ||
var realtime = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.render = exports.cancel = void 0; | ||
// 所有的 timer | ||
var TimerPool = {}; | ||
var clear = function clear(tid) { | ||
clearTimeout(tid); | ||
delete TimerPool[tid]; | ||
}; // 定时运行 | ||
var run = function run(node, date$1, localeFunc, nowDate) { | ||
// 先清理掉之前的 | ||
clear((0, dom.getTimerId)(node)); // get diff seconds | ||
var diff = (0, date.diffSec)(date$1, nowDate); // render | ||
node.innerHTML = (0, date.formatDiff)(diff, localeFunc); | ||
var tid = setTimeout(function () { | ||
run(node, date$1, localeFunc, nowDate); | ||
}, (0, date.nextInterval)(diff) * 1000, 0x7FFFFFFF); // there is no need to save node in object. Just save the key | ||
TimerPool[tid] = 0; | ||
(0, dom.saveTimerId)(node, tid); | ||
}; // 取消一个 node 的实时渲染 | ||
var cancel = function cancel(node) { | ||
if (node) clear((0, dom.getTimerId)(node)); // get the timer of DOM node(native / jq). | ||
else for (var tid in TimerPool) { | ||
clear(tid); | ||
} | ||
}; // 实时渲染一系列节点 | ||
exports.cancel = cancel; | ||
var render = function render(nodes, locale, nowDate) { | ||
// by .length | ||
if (nodes.length === undefined) nodes = [nodes]; | ||
var node; | ||
for (var i = 0; i < nodes.length; i++) { | ||
node = nodes[i]; | ||
var date = (0, dom.getDateAttribute)(node); | ||
var localeFunc = (0, locales.getLocale)(locale); | ||
run(node, date, localeFunc, nowDate); | ||
} | ||
return nodes; | ||
}; | ||
exports.render = render; | ||
}); | ||
unwrapExports(realtime); | ||
var realtime_1 = realtime.render; | ||
var realtime_2 = realtime.cancel; | ||
var lib = createCommonjsModule(function (module, exports) { | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
Object.defineProperty(exports, "format", { | ||
enumerable: true, | ||
get: function get() { | ||
return format_1.format; | ||
} | ||
}); | ||
Object.defineProperty(exports, "render", { | ||
enumerable: true, | ||
get: function get() { | ||
return realtime.render; | ||
} | ||
}); | ||
Object.defineProperty(exports, "cancel", { | ||
enumerable: true, | ||
get: function get() { | ||
return realtime.cancel; | ||
} | ||
}); | ||
Object.defineProperty(exports, "register", { | ||
enumerable: true, | ||
get: function get() { | ||
return locales.register; | ||
} | ||
}); | ||
exports.version = void 0; | ||
/** | ||
@@ -484,13 +261,9 @@ * Created by hustcc on 18/5/20. | ||
*/ | ||
var version = "4.0.0-beta.2"; | ||
exports.version = version; | ||
}); | ||
register('en_US', en_US); | ||
register('zh_CN', zh_CN); | ||
unwrapExports(lib); | ||
var lib_1 = lib.format; | ||
var lib_2 = lib.register; | ||
var lib_3 = lib.version; | ||
/** start date, could be Date instance, timestamp or date string */ | ||
/** timeago string */ | ||
var defaultOptions = { | ||
@@ -500,24 +273,21 @@ locale: 'en_US', | ||
}; | ||
var useTimeAgo = function useTimeAgo(dateTime, options) { | ||
var _useState = react.useState(null), | ||
_useState2 = _slicedToArray(_useState, 2), | ||
timeago = _useState2[0], | ||
setTimeago = _useState2[1]; | ||
var _defaultOptions$optio = _objectSpread2({}, defaultOptions, {}, options), | ||
locale = _defaultOptions$optio.locale, | ||
localeRegister = _defaultOptions$optio.localeRegister, | ||
interval = _defaultOptions$optio.interval; | ||
_useState2 = _slicedToArray(_useState, 2), | ||
timeago = _useState2[0], | ||
setTimeago = _useState2[1]; | ||
var _defaultOptions$optio = _objectSpread2(_objectSpread2({}, defaultOptions), options), | ||
locale = _defaultOptions$optio.locale, | ||
localeRegister = _defaultOptions$optio.localeRegister, | ||
interval = _defaultOptions$optio.interval; | ||
var updateTimeAge = function updateTimeAge() { | ||
setTimeago(lib_1(dateTime, locale)); | ||
setTimeago(format(dateTime, locale)); | ||
}; | ||
react.useEffect(function () { | ||
if (localeRegister) { | ||
lib_2(locale, localeRegister); | ||
register(locale, localeRegister); | ||
} | ||
updateTimeAge(); | ||
updateTimeAge(); // eslint-disable-next-line react-hooks/exhaustive-deps | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, []); | ||
@@ -528,3 +298,5 @@ react.useEffect(function () { | ||
clearInterval(intervalId); | ||
}; // eslint-disable-next-line react-hooks/exhaustive-deps | ||
}; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [dateTime, interval]); | ||
@@ -531,0 +303,0 @@ return timeago; |
{ | ||
"name": "@dh-react-hooks/use-timeago", | ||
"version": "0.4.1", | ||
"version": "0.4.4", | ||
"description": "react hooks for timeago.js", | ||
@@ -27,3 +27,3 @@ "main": "lib/index.js", | ||
"type": "git", | ||
"url": "https://github.com/danhuang1202/DrHooks" | ||
"url": "git+https://github.com/danhuang1202/DrHooks.git" | ||
}, | ||
@@ -41,3 +41,3 @@ "keywords": [ | ||
"peerDependencies": { | ||
"react": "^16.8.6 || ^17.0.0" | ||
"react": "^16.8.6 || ^17 || ^18" | ||
}, | ||
@@ -50,18 +50,19 @@ "devDependencies": { | ||
"@testing-library/react": "^9.1.4", | ||
"@types/jest": "^24.0.18", | ||
"@types/jest": "^29.5.2", | ||
"@types/jquery": "^3.3.31", | ||
"@types/react": "^16.8.6", | ||
"@types/react-dom": "^16.8.6", | ||
"@typescript-eslint/eslint-plugin": "^2.1.0", | ||
"@typescript-eslint/parser": "^2.1.0", | ||
"babel-jest": "^24.9.0", | ||
"eslint": "^6.3.0", | ||
"eslint-config-prettier": "^6.2.0", | ||
"eslint-plugin-react": "^7.14.3", | ||
"eslint-plugin-react-hooks": "^2.0.1", | ||
"jest": "^24.9.0", | ||
"@types/react": "^17.0.62", | ||
"@types/react-dom": "^17.0.20", | ||
"@typescript-eslint/eslint-plugin": "^5.59.11", | ||
"@typescript-eslint/parser": "^5.59.11", | ||
"babel-jest": "^29.5.0", | ||
"eslint": "^8.43.0", | ||
"eslint-config-prettier": "^8.8.0", | ||
"eslint-plugin-react": "^7.32.2", | ||
"eslint-plugin-react-hooks": "^4.6.0", | ||
"jest": "^29.5.0", | ||
"jest-environment-jsdom": "^29.5.0", | ||
"lint-staged": "^9.2.5", | ||
"prettier": "^1.18.2", | ||
"react": "^16.14.0", | ||
"react-dom": "^17.0.1", | ||
"react": "^17.0.0", | ||
"react-dom": "^17.0.0", | ||
"rollup": "^1.21.0", | ||
@@ -72,3 +73,3 @@ "rollup-plugin-babel": "^4.3.3", | ||
"rollup-plugin-peer-deps-external": "^2.2.0", | ||
"typescript": "^3.5.3" | ||
"typescript": "^5.0.4" | ||
}, | ||
@@ -78,3 +79,10 @@ "publishConfig": { | ||
}, | ||
"gitHead": "df5f03c99be69aa983cbfa804392839c73b8a71e" | ||
"engines": { | ||
"node": ">=18.0.0" | ||
}, | ||
"bugs": { | ||
"url": "https://github.com/danhuang1202/DrHooks/issues" | ||
}, | ||
"homepage": "https://github.com/danhuang1202/DrHooks#readme", | ||
"gitHead": "4381622be4f6614168a77dfea14d30089dc4d7b2" | ||
} |
/** start date, could be Date instance, timestamp or date string */ | ||
export declare type DateTime = Date | number | string; | ||
export declare type Options = { | ||
export type DateTime = Date | number | string; | ||
export type Options = { | ||
/** | ||
@@ -10,3 +10,3 @@ * locale | ||
/** custom local register function */ | ||
localeRegister?: (number: number, index: number, totalSecoends?: number) => string[]; | ||
localeRegister?: (number: number, index: number, totalSecoends?: number) => [string, string]; | ||
/** | ||
@@ -19,4 +19,4 @@ * update interval duration in milliseconds | ||
/** timeago string */ | ||
export declare type TimeAgo = string; | ||
declare const useTimeAgo: (dateTime: string | number | Date, options?: Options) => string; | ||
export type TimeAgo = string; | ||
declare const useTimeAgo: (dateTime: DateTime, options?: Options) => TimeAgo; | ||
export default useTimeAgo; |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No bug tracker
MaintenancePackage does not have a linked bug tracker in package.json.
Found 1 instance in 1 package
No website
QualityPackage does not have a website.
Found 1 instance in 1 package
0
1
29228
28
693
1