about summary refs log tree commit diff
path: root/src/view/com/util/ViewSelector.tsx
blob: b5075707a20bc8bc535ebfb7eff5f40179c0358b (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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import React, {useEffect, useState} from 'react'
import {
  NativeScrollEvent,
  NativeSyntheticEvent,
  Pressable,
  RefreshControl,
  ScrollView,
  StyleSheet,
  View,
} from 'react-native'

import {useColorSchemeStyle} from '#/lib/hooks/useColorSchemeStyle'
import {usePalette} from '#/lib/hooks/usePalette'
import {clamp} from '#/lib/numbers'
import {colors, s} from '#/lib/styles'
import {isAndroid} from '#/platform/detection'
import {Text} from './text/Text'
import {FlatList_INTERNAL} from './Views'

const HEADER_ITEM = {_reactKey: '__header__'}
const SELECTOR_ITEM = {_reactKey: '__selector__'}
const STICKY_HEADER_INDICES = [1]

export type ViewSelectorHandle = {
  scrollToTop: () => void
}

export const ViewSelector = React.forwardRef<
  ViewSelectorHandle,
  {
    sections: string[]
    items: any[]
    refreshing?: boolean
    swipeEnabled?: boolean
    renderHeader?: () => JSX.Element
    renderItem: (item: any) => JSX.Element
    ListFooterComponent?:
      | React.ComponentType<any>
      | React.ReactElement
      | null
      | undefined
    onSelectView?: (viewIndex: number) => void
    onScroll?: (event: NativeSyntheticEvent<NativeScrollEvent>) => void
    onRefresh?: () => void
    onEndReached?: (info: {distanceFromEnd: number}) => void
  }
>(function ViewSelectorImpl(
  {
    sections,
    items,
    refreshing,
    renderHeader,
    renderItem,
    ListFooterComponent,
    onSelectView,
    onScroll,
    onRefresh,
    onEndReached,
  },
  ref,
) {
  const pal = usePalette('default')
  const [selectedIndex, setSelectedIndex] = useState<number>(0)
  const flatListRef = React.useRef<FlatList_INTERNAL>(null)

  // events
  // =

  const keyExtractor = React.useCallback((item: any) => item._reactKey, [])

  const onPressSelection = React.useCallback(
    (index: number) => setSelectedIndex(clamp(index, 0, sections.length)),
    [setSelectedIndex, sections],
  )
  useEffect(() => {
    onSelectView?.(selectedIndex)
  }, [selectedIndex, onSelectView])

  React.useImperativeHandle(ref, () => ({
    scrollToTop: () => {
      flatListRef.current?.scrollToOffset({offset: 0})
    },
  }))

  // rendering
  // =

  const renderItemInternal = React.useCallback(
    ({item}: {item: any}) => {
      if (item === HEADER_ITEM) {
        if (renderHeader) {
          return renderHeader()
        }
        return <View />
      } else if (item === SELECTOR_ITEM) {
        return (
          <Selector
            items={sections}
            selectedIndex={selectedIndex}
            onSelect={onPressSelection}
          />
        )
      } else {
        return renderItem(item)
      }
    },
    [sections, selectedIndex, onPressSelection, renderHeader, renderItem],
  )

  const data = React.useMemo(
    () => [HEADER_ITEM, SELECTOR_ITEM, ...items],
    [items],
  )
  return (
    <FlatList_INTERNAL
      // @ts-expect-error FlatList_INTERNAL ref type is wrong -sfn
      ref={flatListRef}
      data={data}
      keyExtractor={keyExtractor}
      renderItem={renderItemInternal}
      ListFooterComponent={ListFooterComponent}
      // NOTE sticky header disabled on android due to major performance issues -prf
      stickyHeaderIndices={isAndroid ? undefined : STICKY_HEADER_INDICES}
      onScroll={onScroll}
      onEndReached={onEndReached}
      refreshControl={
        <RefreshControl
          refreshing={refreshing!}
          onRefresh={onRefresh}
          tintColor={pal.colors.text}
        />
      }
      onEndReachedThreshold={0.6}
      contentContainerStyle={s.contentContainer}
      removeClippedSubviews={true}
      scrollIndicatorInsets={{right: 1}} // fixes a bug where the scroll indicator is on the middle of the screen https://github.com/bluesky-social/social-app/pull/464
    />
  )
})

export function Selector({
  selectedIndex,
  items,
  onSelect,
}: {
  selectedIndex: number
  items: string[]
  onSelect?: (index: number) => void
}) {
  const pal = usePalette('default')
  const borderColor = useColorSchemeStyle(
    {borderColor: colors.black},
    {borderColor: colors.white},
  )

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

  return (
    <View
      style={{
        width: '100%',
        backgroundColor: pal.colors.background,
      }}>
      <ScrollView
        testID="selector"
        horizontal
        showsHorizontalScrollIndicator={false}>
        <View style={[pal.view, styles.outer]}>
          {items.map((item, i) => {
            const selected = i === selectedIndex
            return (
              <Pressable
                testID={`selector-${i}`}
                key={item}
                onPress={() => onPressItem(i)}
                accessibilityLabel={item}
                accessibilityHint={`Selects ${item}`}
                // TODO: Modify the component API such that lint fails
                // at the invocation site as well
              >
                <View
                  style={[
                    styles.item,
                    selected && styles.itemSelected,
                    borderColor,
                  ]}>
                  <Text
                    style={
                      selected
                        ? [styles.labelSelected, pal.text]
                        : [styles.label, pal.textLight]
                    }>
                    {item}
                  </Text>
                </View>
              </Pressable>
            )
          })}
        </View>
      </ScrollView>
    </View>
  )
}

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