Untitled

mail@pastecode.io avatar
unknown
plain_text
20 days ago
1.9 kB
8
Indexable
Never
import { differenceInDays, getHours, getMinutes } from 'date-fns'
import React, { ReactElement, useEffect } from 'react'
import { StyleSheet, View } from 'react-native'
import Animated, { useAnimatedStyle, useSharedValue } from 'react-native-reanimated'
import { useCalendarContext } from '../context/CalendarProvider'

type Props = {
  firstDateOfPeriod: string
}

const NowIndicator = (props: Props): ReactElement => {
  const { firstDateOfPeriod } = props

  const { timeSlotHeight, timelineColumnWidth } = useCalendarContext()

  const now = new Date()
  const hour = getHours(now)
  const minutes = getMinutes(now)

  const yPos = useSharedValue(hour * timeSlotHeight + (minutes / 60) * timeSlotHeight)
  const xPos = useSharedValue(differenceInDays(now, new Date(firstDateOfPeriod)) * timelineColumnWidth)

  useEffect(() => {
    function move() {
      const now = new Date()
      const hour = getHours(now)
      const minutes = getMinutes(now)

      yPos.value = hour * timeSlotHeight + (minutes / 60) * timeSlotHeight
      xPos.value = differenceInDays(now, new Date(firstDateOfPeriod)) * timelineColumnWidth
    }

    const interval = setInterval(move, 1000)

    return () => clearInterval(interval)
  }, [])

  const animatedStyle = useAnimatedStyle(() => {
    return {
      top: yPos.value,
      left: xPos.value,
    }
  })

  return (
    <Animated.View
      style={[
        {
          width: timelineColumnWidth,
        },
        styles.line,
        animatedStyle,
      ]}
    >
      <View style={styles.dot}></View>
    </Animated.View>
  )
}

export default NowIndicator

const styles = StyleSheet.create({
  line: {
    height: 2,
    backgroundColor: 'red',
    transform: [{ translateY: -1 }],
    zIndex: 10,
  },
  dot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: 'red',
    transform: [{ translateY: -3 }, { translateX: -4 }],
  },
})
Leave a Comment