@aplus-frontend/ui
Version:
57 lines (56 loc) • 1.59 kB
JavaScript
import m from "dayjs";
import { ref as v, watch as M, onBeforeUnmount as h } from "vue";
function s(n, u) {
const t = Math.abs(n - u), e = {
diffMs: t,
type: n < u ? "ago" : "late"
};
return t < 60 * 1e3 ? (e.unit = "s", e.count = Math.round(t / 1e3)) : t < 3600 * 1e3 ? (e.unit = "m", e.count = Math.round(t / (60 * 1e3))) : t < 1440 * 60 * 1e3 ? (e.unit = "h", e.count = Math.round(t / (3600 * 1e3))) : t < 720 * 60 * 60 * 1e3 ? (e.unit = "d", e.count = Math.round(t / (1440 * 60 * 1e3))) : t < 365 * 24 * 60 * 60 * 1e3 ? (e.unit = "M", e.count = Math.round(t / (720 * 60 * 60 * 1e3))) : (e.unit = "y", e.count = Math.round(t / 365 / (1440 * 60 * 1e3))), e;
}
function i(n) {
return m(n).valueOf();
}
let p = 1;
function g() {
return p++;
}
const o = /* @__PURE__ */ new Map();
let r, l;
function w(n, u) {
o.set(n, u), o.size && !l && (clearInterval(r), r = setInterval(() => {
l = !0;
const t = Date.now();
o.forEach((e) => {
e.interval && Math.abs(t - e.updated - e.interval) < 50 && (e.timeAgo.value = s(e.ts, t), e.updated = t);
});
}, 5e3));
}
function b(n) {
o.delete(n), o.size || (clearInterval(r), l = !1);
}
const y = (n, u, t) => {
const e = g(), a = v(
s(i(n.value), i(u))
), f = {
ts: i(n.value),
timeAgo: a,
interval: t.value,
updated: Date.now()
};
return M(
() => n.value,
(d) => {
const c = i(d);
f.ts = c, a.value = s(c, i(u));
}
), w(e, f), h(() => {
b(e);
}), a;
};
export {
y as default,
g as getId,
s as getTimeAgo,
w as subscribe,
b as unsubscribe
};