calckey/src/client/components/time.vue

73 lines
1.9 KiB
Vue
Raw Normal View History

2018-02-05 05:25:19 +00:00
<template>
<time class="mk-time" :title="absolute">
<span v-if="mode == 'relative'">{{ relative }}</span>
<span v-if="mode == 'absolute'">{{ absolute }}</span>
<span v-if="mode == 'detail'">{{ absolute }} ({{ relative }})</span>
2018-02-13 04:49:48 +00:00
</time>
2018-02-05 05:25:19 +00:00
</template>
2016-12-28 22:49:51 +00:00
2018-02-13 04:49:48 +00:00
<script lang="ts">
import Vue from 'vue';
2018-02-09 09:28:06 +00:00
2018-02-13 04:49:48 +00:00
export default Vue.extend({
props: {
time: {
type: [Date, String],
required: true
2018-02-05 05:25:19 +00:00
},
2018-02-13 04:49:48 +00:00
mode: {
type: String,
default: 'relative'
}
},
data() {
return {
tickId: null,
now: new Date()
};
},
computed: {
_time(): Date {
return typeof this.time == 'string' ? new Date(this.time) : this.time;
2018-02-05 05:25:19 +00:00
},
2018-02-13 04:49:48 +00:00
absolute(): string {
2018-12-18 16:10:53 +00:00
return this._time.toLocaleString();
2018-02-05 05:25:19 +00:00
},
2018-02-13 04:49:48 +00:00
relative(): string {
const time = this._time;
const ago = (this.now.getTime() - time.getTime()) / 1000/*ms*/;
return (
ago >= 31536000 ? this.$t('_ago.yearsAgo', { n: (~~(ago / 31536000)).toString() }) :
ago >= 2592000 ? this.$t('_ago.monthsAgo', { n: (~~(ago / 2592000)).toString() }) :
ago >= 604800 ? this.$t('_ago.weeksAgo', { n: (~~(ago / 604800)).toString() }) :
ago >= 86400 ? this.$t('_ago.daysAgo', { n: (~~(ago / 86400)).toString() }) :
ago >= 3600 ? this.$t('_ago.hoursAgo', { n: (~~(ago / 3600)).toString() }) :
ago >= 60 ? this.$t('_ago.minutesAgo', { n: (~~(ago / 60)).toString() }) :
ago >= 10 ? this.$t('_ago.secondsAgo', { n: (~~(ago % 60)).toString() }) :
ago >= -1 ? this.$t('_ago.justNow') :
ago < -1 ? this.$t('_ago.future') :
this.$t('_ago.unknown'));
2018-02-13 04:49:48 +00:00
}
},
created() {
if (this.mode == 'relative' || this.mode == 'detail') {
2018-06-09 23:03:02 +00:00
this.tickId = window.requestAnimationFrame(this.tick);
2018-02-13 04:49:48 +00:00
}
},
destroyed() {
if (this.mode === 'relative' || this.mode === 'detail') {
2018-06-09 23:03:02 +00:00
window.clearTimeout(this.tickId);
2018-02-13 04:49:48 +00:00
}
},
methods: {
tick() {
this.now = new Date();
2018-06-09 23:03:02 +00:00
this.tickId = setTimeout(() => {
window.requestAnimationFrame(this.tick);
}, 10000);
2018-02-05 05:25:19 +00:00
}
2018-02-13 04:49:48 +00:00
}
});
2018-02-05 05:25:19 +00:00
</script>