68 lines
1.9 KiB
JavaScript
68 lines
1.9 KiB
JavaScript
|
|
document.addEventListener('alpine:init', () => {
|
||
|
|
Alpine.data('rtime', (unixTimestamp) => ({
|
||
|
|
targetDate: new Date(unixTimestamp * 1000),
|
||
|
|
timeString: '',
|
||
|
|
timer: null,
|
||
|
|
interval: 1000,
|
||
|
|
|
||
|
|
colorClasses: {
|
||
|
|
green: 't-green',
|
||
|
|
yellow: 't-yellow',
|
||
|
|
orange: 't-orange',
|
||
|
|
red: 't-red'
|
||
|
|
},
|
||
|
|
|
||
|
|
currentColor: 'green',
|
||
|
|
|
||
|
|
get textColorClass() {
|
||
|
|
return this.colorClasses[this.currentColor];
|
||
|
|
},
|
||
|
|
|
||
|
|
init() {
|
||
|
|
this.updateTime();
|
||
|
|
this.timer = setInterval(() => this.updateTime(), this.interval);
|
||
|
|
|
||
|
|
this.$el.addEventListener('alpine:removing', () => {
|
||
|
|
if (this.interval) clearInterval(this.interval);
|
||
|
|
});
|
||
|
|
},
|
||
|
|
|
||
|
|
updateTime() {
|
||
|
|
const now = new Date();
|
||
|
|
const diffInSeconds = Math.floor((now - this.targetDate) / 1000);
|
||
|
|
const diffInMinutes = Math.floor(diffInSeconds / 60);
|
||
|
|
const diffInHours = Math.floor(diffInSeconds / 3600);
|
||
|
|
const diffInDays = Math.floor(diffInSeconds / 86400);
|
||
|
|
|
||
|
|
let newInterval = this.interval;
|
||
|
|
|
||
|
|
if (diffInSeconds < 60) {
|
||
|
|
this.timeString = 'a moment ago';
|
||
|
|
} else if (diffInMinutes < 60) {
|
||
|
|
this.timeString = `${diffInMinutes} m ago`;
|
||
|
|
newInterval = 10000;
|
||
|
|
} else if (diffInHours < 24) {
|
||
|
|
this.timeString = `${diffInHours} h ago`;
|
||
|
|
newInterval = 60000;
|
||
|
|
} else {
|
||
|
|
this.timeString = `${diffInDays} d ago`;
|
||
|
|
clearInterval(this.timer);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (diffInMinutes <= 15) {
|
||
|
|
this.currentColor = 'green';
|
||
|
|
} else if (diffInHours < 1) {
|
||
|
|
this.currentColor = 'yellow';
|
||
|
|
} else if (diffInDays < 1) {
|
||
|
|
this.currentColor = 'orange';
|
||
|
|
} else {
|
||
|
|
this.currentColor = 'red';
|
||
|
|
}
|
||
|
|
|
||
|
|
if (this.interval != newInterval) {
|
||
|
|
clearInterval(this.timer)
|
||
|
|
this.timer = setInterval(() => this.updateTime(), newInterval);
|
||
|
|
}
|
||
|
|
},
|
||
|
|
}));
|
||
|
|
});
|