-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathCreatePollContent.tsx
More file actions
318 lines (287 loc) · 11.1 KB
/
CreatePollContent.tsx
File metadata and controls
318 lines (287 loc) · 11.1 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { StyleSheet, Switch, Text, View } from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';
import Animated, { LinearTransition, useSharedValue } from 'react-native-reanimated';
import { PollComposerState, StateStore, VotingVisibility } from 'stream-chat';
import { CreatePollOptions, CurrentOptionPositionsCache } from './components';
import { CreatePollHeader } from './components/CreatePollHeader';
import { MultipleAnswersField } from './components/MultipleAnswersField';
import { NameField } from './components/NameField';
import {
CreatePollModalState,
CreatePollContentContextValue,
CreatePollContentProvider,
InputMessageInputContextValue,
useCreatePollContentContext,
useTheme,
useTranslationContext,
} from '../../contexts';
import { useMessageComposer } from '../../contexts/messageInputContext/hooks/useMessageComposer';
import { useStateStore } from '../../hooks/useStateStore';
import { primitives } from '../../theme';
const pollComposerStateSelector = (state: PollComposerState) => ({
options: state.data.options,
});
export const CreatePollContent = () => {
const [isAnonymousPoll, setIsAnonymousPoll] = useState<boolean>(false);
const [allowUserSuggestedOptions, setAllowUserSuggestedOptions] = useState<boolean>(false);
const [allowAnswers, setAllowAnswers] = useState<boolean>(false);
const { t } = useTranslationContext();
const messageComposer = useMessageComposer();
const { pollComposer } = messageComposer;
const { options } = useStateStore(pollComposer.state, pollComposerStateSelector);
const {
createPollOptionGap = 8,
closePollCreationDialog,
createAndSendPoll,
} = useCreatePollContentContext();
const normalizedCreatePollOptionGap =
Number.isFinite(createPollOptionGap) && createPollOptionGap > 0 ? createPollOptionGap : 0;
const optionIdsKey = useMemo(() => options.map((option) => option.id).join('|'), [options]);
const optionsRef = useRef(options);
optionsRef.current = options;
// positions and index lookup map
// TODO: Please rethink the structure of this, bidirectional data flow is not great
const currentOptionPositions = useSharedValue<CurrentOptionPositionsCache>({
inverseIndexCache: {},
positionCache: {},
totalHeight: 0,
});
const {
theme: {
poll: {
createContent: { addComment, anonymousPoll, optionCardWrapper, scrollView, suggestOption },
},
},
} = useTheme();
const styles = useStyles();
useEffect(() => {
const latestOptions = optionsRef.current;
const currentPositions = currentOptionPositions.value;
const isCacheAlignedWithOptions =
latestOptions.length === Object.keys(currentPositions.inverseIndexCache).length &&
latestOptions.every(
(option, index) =>
currentPositions.inverseIndexCache[index] === option.id &&
currentPositions.positionCache[option.id] !== undefined,
);
// Avoid overwriting freshly measured heights/tops from CreatePollOptions onLayout.
// We only need this effect when options ids/order introduced missing cache entries.
if (isCacheAlignedWithOptions) {
return;
}
const previousPositionCache = currentOptionPositions.value.positionCache;
const newCurrentOptionPositions: CurrentOptionPositionsCache = {
inverseIndexCache: {},
positionCache: {},
totalHeight: 0,
};
let runningTop = 0;
latestOptions.forEach((option, index) => {
const preservedHeight = previousPositionCache[option.id]?.updatedHeight ?? 0;
newCurrentOptionPositions.inverseIndexCache[index] = option.id;
newCurrentOptionPositions.positionCache[option.id] = {
updatedHeight: preservedHeight,
updatedIndex: index,
updatedTop: runningTop,
};
const gap = index === latestOptions.length - 1 ? 0 : normalizedCreatePollOptionGap;
runningTop += preservedHeight + gap;
newCurrentOptionPositions.totalHeight = runningTop;
});
currentOptionPositions.value = newCurrentOptionPositions;
}, [currentOptionPositions, normalizedCreatePollOptionGap, optionIdsKey]);
const onBackPressHandler = useCallback(() => {
closePollCreationDialog?.();
}, [closePollCreationDialog]);
const onCreatePollPressHandler = useCallback(async () => {
await createAndSendPoll();
}, [createAndSendPoll]);
const onAnonymousPollChangeHandler = useCallback(
async (value: boolean) => {
setIsAnonymousPoll(value);
await pollComposer.updateFields({
voting_visibility: value ? VotingVisibility.anonymous : VotingVisibility.public,
});
},
[pollComposer],
);
const onAllowUserSuggestedOptionsChangeHandler = useCallback(
async (value: boolean) => {
setAllowUserSuggestedOptions(value);
await pollComposer.updateFields({ allow_user_suggested_options: value });
},
[pollComposer],
);
const onAllowAnswersChangeHandler = useCallback(
async (value: boolean) => {
setAllowAnswers(value);
await pollComposer.updateFields({ allow_answers: value });
},
[pollComposer],
);
return (
<>
<CreatePollHeader
onBackPressHandler={onBackPressHandler}
onCreatePollPressHandler={onCreatePollPressHandler}
/>
<ScrollView
contentContainerStyle={styles.contentContainerStyle}
style={[styles.scrollView, scrollView]}
>
<NameField />
<CreatePollOptions currentOptionPositions={currentOptionPositions} />
<Animated.View
layout={LinearTransition.duration(200)}
style={[styles.optionCardWrapper, optionCardWrapper]}
>
<MultipleAnswersField />
<Animated.View
layout={LinearTransition.duration(200)}
style={[styles.optionCardWrapper, optionCardWrapper]}
>
<View style={[styles.optionCard, anonymousPoll.wrapper]}>
<View style={[styles.optionCardContent, anonymousPoll.optionCardContent]}>
<Text style={[styles.title, anonymousPoll.title]}>{t('Anonymous voting')}</Text>
<Text style={[styles.description, anonymousPoll.description]}>Hide who voted</Text>
</View>
<Switch
onValueChange={onAnonymousPollChangeHandler}
value={isAnonymousPoll}
style={[styles.optionCardSwitch, anonymousPoll.optionCardSwitch]}
/>
</View>
<View style={[styles.optionCard, suggestOption.wrapper]}>
<View style={[styles.optionCardContent, suggestOption.optionCardContent]}>
<Text style={[styles.title, suggestOption.title]}>{t('Suggest an option')}</Text>
<Text style={[styles.description, suggestOption.description]}>
Let others add options
</Text>
</View>
<Switch
onValueChange={onAllowUserSuggestedOptionsChangeHandler}
value={allowUserSuggestedOptions}
style={[styles.optionCardSwitch, suggestOption.optionCardSwitch]}
/>
</View>
<View style={[styles.optionCard, addComment.wrapper]}>
<View style={[styles.optionCardContent, addComment.optionCardContent]}>
<Text style={[styles.title, addComment.title]}>{t('Add a comment')}</Text>
<Text style={[styles.description, addComment.description]}>
Add a comment to the poll
</Text>
</View>
<Switch
onValueChange={onAllowAnswersChangeHandler}
value={allowAnswers}
style={[styles.optionCardSwitch, addComment.optionCardSwitch]}
/>
</View>
</Animated.View>
</Animated.View>
</ScrollView>
</>
);
};
export const CreatePoll = ({
closePollCreationDialog,
CreatePollContent: CreatePollContentOverride,
createPollOptionGap = 8,
sendMessage,
}: Pick<
CreatePollContentContextValue,
'createPollOptionGap' | 'closePollCreationDialog' | 'sendMessage'
> &
Pick<InputMessageInputContextValue, 'CreatePollContent'>) => {
const messageComposer = useMessageComposer();
const [modalStateStore] = useState(
() => new StateStore<CreatePollModalState>({ isClosing: false }),
);
const closeFrameRef = useRef<number | null>(null);
const closeCreatePollDialog = useCallback(() => {
if (closeFrameRef.current !== null || modalStateStore.getLatestValue().isClosing) {
return;
}
// Let the modal render once with exit animations disabled before we dismiss it.
modalStateStore.partialNext({ isClosing: true });
closeFrameRef.current = requestAnimationFrame(() => {
closeFrameRef.current = null;
closePollCreationDialog?.();
});
}, [closePollCreationDialog, modalStateStore]);
useEffect(() => {
return () => {
if (closeFrameRef.current !== null) {
cancelAnimationFrame(closeFrameRef.current);
}
// Reset after teardown so poll field exit animations do not delay modal dismissal.
messageComposer.pollComposer.initState();
};
}, [messageComposer]);
const createAndSendPoll = useCallback(async () => {
try {
await messageComposer.createPoll();
await sendMessage();
closeCreatePollDialog();
} catch (error) {
console.log('Error creating a poll and sending a message:', error);
}
}, [closeCreatePollDialog, messageComposer, sendMessage]);
return (
<CreatePollContentProvider
value={{
closePollCreationDialog: closeCreatePollDialog,
createAndSendPoll,
createPollOptionGap,
modalStateStore,
sendMessage,
}}
>
{CreatePollContentOverride ? <CreatePollContentOverride /> : <CreatePollContent />}
</CreatePollContentProvider>
);
};
const useStyles = () => {
const {
theme: { semantics },
} = useTheme();
return useMemo(() => {
return StyleSheet.create({
scrollView: {
flex: 1,
padding: primitives.spacingMd,
backgroundColor: semantics.backgroundCoreElevation1,
},
contentContainerStyle: { paddingBottom: 70 },
title: {
color: semantics.textPrimary,
fontSize: primitives.typographyFontSizeMd,
fontWeight: primitives.typographyFontWeightSemiBold,
lineHeight: primitives.typographyLineHeightNormal,
},
description: {
color: semantics.textTertiary,
fontSize: primitives.typographyFontSizeSm,
fontWeight: primitives.typographyFontWeightRegular,
lineHeight: primitives.typographyLineHeightNormal,
},
optionCardContent: {
gap: primitives.spacingXxs,
},
optionCard: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-between',
flexDirection: 'row',
backgroundColor: semantics.backgroundCoreSurfaceCard,
padding: primitives.spacingMd,
borderRadius: primitives.radiusLg,
},
optionCardWrapper: {
gap: primitives.spacingMd,
},
optionCardSwitch: { width: 64 },
});
}, [semantics]);
};