wildlyinaccurate / angular-relative-date

AngularJS filter to provide relative, human-readable dates.
69 stars 23 forks source link

Auto-update the relative date #29

Open matthieusieben opened 7 years ago

matthieusieben commented 7 years ago

Relative dates have a particularity: being relative to the current time, which (sadly?) is ever increasing, they are themselves always changing.

The following decorator will allow to take this particularity into account, making the relative dates update themselves.

const getDigestDelay = (date) => {
  const _date = date instanceof Date ? date : new Date(date)
  const delta = Math.abs(new Date() - _date) / 1000
  if (delta < 60) return 5
  if (delta < 120) return 30
  if (delta < 7200) return 60
  return 600
}

export default function relativeDateFilterDecorator ($delegate, $timeout) {
  let timer = null

  relativeDateFilter.$stateful = true

  return relativeDateFilter

  function relativeDateFilter (date) {
    const delay = getDigestDelay(date)

    if (!timer || delay < timer.delay) {
      $timeout.cancel(timer)
      timer = $timeout(() => { timer = null }, delay * 1000, true)
      timer.delay = delay
    }

    return $delegate(date)
  }
}