about summary refs log tree commit diff
path: root/src/components/dms/DateDivider.tsx
blob: a9c82e8ea2e9bdf4d58e56e50f4a6afd0a2601bc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import React from 'react'
import {View} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {subDays} from 'date-fns'

import {atoms as a, useTheme} from '#/alf'
import {Text} from '../Typography'
import {localDateString} from './util'

const timeFormatter = new Intl.DateTimeFormat(undefined, {
  hour: 'numeric',
  minute: 'numeric',
})
const weekdayFormatter = new Intl.DateTimeFormat(undefined, {
  weekday: 'long',
})
const longDateFormatter = new Intl.DateTimeFormat(undefined, {
  weekday: 'short',
  month: 'long',
  day: 'numeric',
})
const longDateFormatterWithYear = new Intl.DateTimeFormat(undefined, {
  weekday: 'short',
  month: 'long',
  day: 'numeric',
  year: 'numeric',
})

let DateDivider = ({date: dateStr}: {date: string}): React.ReactNode => {
  const {_} = useLingui()
  const t = useTheme()

  let date: string
  const time = timeFormatter.format(new Date(dateStr))

  const timestamp = new Date(dateStr)

  const today = new Date()
  const yesterday = subDays(today, 1)
  const oneWeekAgo = subDays(today, 7)

  if (localDateString(today) === localDateString(timestamp)) {
    date = _(msg`Today`)
  } else if (localDateString(yesterday) === localDateString(timestamp)) {
    date = _(msg`Yesterday`)
  } else {
    if (timestamp < oneWeekAgo) {
      if (timestamp.getFullYear() === today.getFullYear()) {
        date = longDateFormatter.format(timestamp)
      } else {
        date = longDateFormatterWithYear.format(timestamp)
      }
    } else {
      date = weekdayFormatter.format(timestamp)
    }
  }

  return (
    <View style={[a.w_full, a.my_lg]}>
      <Text
        style={[
          a.text_xs,
          a.text_center,
          t.atoms.bg,
          t.atoms.text_contrast_medium,
          a.px_md,
        ]}>
        <Trans>
          <Text style={[a.text_xs, t.atoms.text_contrast_medium, a.font_bold]}>
            {date}
          </Text>{' '}
          at {time}
        </Trans>
      </Text>
    </View>
  )
}
DateDivider = React.memo(DateDivider)
export {DateDivider}