Newer
Older
navi-1 / webclient / src / composables / useTime.js
@Eugene Sukhodolskiy Eugene Sukhodolskiy 1 day ago 1 KB webclient: the sidebar in en, uk and ru
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { locale, t } from '@/i18n/index.js'

/**
 * Format a timestamp as a relative/short label (same logic as old client).
 * < 1 min  → "just now"
 * < 1 hour → "5 min ago"
 * today    → "14:32"
 * older    → "12.04.2024"
 */
export function formatTimeLabel(ts) {
  if (!ts) return ''
  const d = new Date(ts)
  if (isNaN(d)) return ''
  const diff = Date.now() - d
  if (diff < 60_000)     return t('common.justNow')
  if (diff < 3_600_000)  return t('common.minutesAgo', { n: Math.floor(diff / 60_000) })
  if (diff < 86_400_000) return d.toLocaleTimeString(locale.value, { hour: '2-digit', minute: '2-digit' })
  return d.toLocaleDateString(locale.value)
}

/**
 * Reactive time label that auto-updates every minute.
 * Returns a ref that ticks so "5 min ago" stays current.
 */
export function useTimeLabel(tsRef) {
  const label = ref(formatTimeLabel(tsRef.value))

  let timer = null

  function update() {
    label.value = formatTimeLabel(tsRef.value)
  }

  // The label is a string, not a template that re-renders — a new interface
  // language has to rewrite it, or the sidebar keeps the old one until the
  // next tick.
  watch(locale, update)

  onMounted(() => {
    update()
    timer = setInterval(update, 30_000)
  })

  onUnmounted(() => {
    if (timer) clearInterval(timer)
  })

  return label
}