about summary refs log tree commit diff
path: root/src/view/com/util/Selector.tsx
blob: 66e363cd41568c3e86cf35457727a9d22cfc4007 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import React, {createRef, useState, useMemo, useRef} from 'react'
import {Animated, Pressable, StyleSheet, View} from 'react-native'
import {Text} from './text/Text'
import {usePalette} from 'lib/hooks/usePalette'
import {useLingui} from '@lingui/react'
import {msg} from '@lingui/macro'

interface Layout {
  x: number
  width: number
}

export function Selector({
  selectedIndex,
  items,
  panX,
  onSelect,
}: {
  selectedIndex: number
  items: string[]
  panX: Animated.Value
  onSelect?: (index: number) => void
}) {
  const {_} = useLingui()
  const containerRef = useRef<View>(null)
  const pal = usePalette('default')
  const [itemLayouts, setItemLayouts] = useState<undefined | Layout[]>(
    undefined,
  )
  const itemRefs = useMemo(
    () => Array.from({length: items.length}).map(() => createRef<View>()),
    [items.length],
  )

  const currentLayouts = useMemo(() => {
    const left = itemLayouts?.[selectedIndex - 1] || {x: 0, width: 0}
    const middle = itemLayouts?.[selectedIndex] || {x: 0, width: 0}
    const right = itemLayouts?.[selectedIndex + 1] || {
      x: middle.x + 20,
      width: middle.width,
    }
    return [left, middle, right]
  }, [selectedIndex, itemLayouts])

  const underlineStyle = {
    backgroundColor: pal.colors.text,
    left: panX.interpolate({
      inputRange: [-1, 0, 1],
      outputRange: [
        currentLayouts[0].x,
        currentLayouts[1].x,
        currentLayouts[2].x,
      ],
    }),
    width: panX.interpolate({
      inputRange: [-1, 0, 1],
      outputRange: [
        currentLayouts[0].width,
        currentLayouts[1].width,
        currentLayouts[2].width,
      ],
    }),
  }

  const onLayout = () => {
    const promises = []
    for (let i = 0; i < items.length; i++) {
      promises.push(
        new Promise<Layout>(resolve => {
          if (!containerRef.current || !itemRefs[i].current) {
            return resolve({x: 0, width: 0})
          }
          itemRefs[i].current?.measureLayout(
            containerRef.current,
            (x: number, _y: number, width: number) => {
              resolve({x, width})
            },
          )
        }),
      )
    }
    Promise.all(promises).then((layouts: Layout[]) => {
      setItemLayouts(layouts)
    })
  }

  const onPressItem = (index: number) => {
    onSelect?.(index)
  }

  const numItems = items.length

  return (
    <View
      style={[pal.view, styles.outer]}
      onLayout={onLayout}
      ref={containerRef}>
      <Animated.View style={[styles.underline, underlineStyle]} />
      {items.map((item, i) => {
        const selected = i === selectedIndex
        return (
          <Pressable
            testID={`selector-${i}`}
            key={item}
            onPress={() => onPressItem(i)}
            accessibilityLabel={_(msg`Select ${item}`)}
            accessibilityHint={_(msg`Select option ${i} of ${numItems}`)}>
            <View style={styles.item} ref={itemRefs[i]}>
              <Text
                style={
                  selected
                    ? [styles.labelSelected, pal.text]
                    : [styles.label, pal.textLight]
                }>
                {item}
              </Text>
            </View>
          </Pressable>
        )
      })}
    </View>
  )
}

const styles = StyleSheet.create({
  outer: {
    flexDirection: 'row',
    paddingTop: 8,
    paddingBottom: 12,
    paddingHorizontal: 14,
  },
  item: {
    marginRight: 14,
    paddingHorizontal: 10,
  },
  label: {
    fontWeight: '600',
  },
  labelSelected: {
    fontWeight: '600',
  },
  underline: {
    position: 'absolute',
    height: 4,
    bottom: 0,
  },
})