-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathOptionFieldSet.tsx
More file actions
86 lines (81 loc) · 3.08 KB
/
OptionFieldSet.tsx
File metadata and controls
86 lines (81 loc) · 3.08 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
import clsx from 'clsx';
import React, { useCallback } from 'react';
import { FieldError } from '../../Form/FieldError';
import { DragAndDropContainer } from '../../DragAndDrop/DragAndDropContainer';
import { useTranslationContext } from '../../../context';
import { useMessageComposer } from '../../MessageInput';
import { useStateStore } from '../../../store';
import type { PollComposerState } from 'stream-chat';
const pollComposerStateSelector = (state: PollComposerState) => ({
errors: state.errors.options,
options: state.data.options,
});
export const OptionFieldSet = () => {
const { pollComposer } = useMessageComposer();
const { errors, options } = useStateStore(
pollComposer.state,
pollComposerStateSelector,
);
const { t } = useTranslationContext('OptionFieldSet');
const onSetNewOrder = useCallback(
(newOrder: number[]) => {
const prevOptions = pollComposer.options;
pollComposer.updateFields({ options: newOrder.map((index) => prevOptions[index]) });
},
[pollComposer],
);
const draggable = options.length > 1;
return (
<fieldset className='str-chat__form__field str-chat__form__input-fieldset'>
<legend className='str-chat__form__field-label'>{t('Options')}</legend>
<DragAndDropContainer
className='str-chat__form__input-fieldset__values'
draggable={draggable}
onSetNewOrder={onSetNewOrder}
>
{options.map((option, i) => {
const error = errors?.[option.id];
return (
<div
className={clsx('str-chat__form__input-field', {
'str-chat__form__input-field--draggable': draggable,
'str-chat__form__input-field--has-error': error,
})}
key={`new-poll-option-${i}`}
>
<div className='str-chat__form__input-field__value'>
<FieldError
className='str-chat__form__input-field__error'
data-testid={'poll-option-input-field-error'}
text={error && t(error)}
/>
<input
id={option.id}
onBlur={() => {
pollComposer.handleFieldBlur('options');
}}
onChange={(e) => {
pollComposer.updateFields({
options: { index: i, text: e.target.value },
});
}}
onKeyUp={(event) => {
const isFocusedLastOptionField = i === options.length - 1;
if (event.key === 'Enter' && !isFocusedLastOptionField) {
const nextInputId = options[i + 1].id;
document.getElementById(nextInputId)?.focus();
}
}}
placeholder={t('Add an option')}
type='text'
value={option.text}
/>
</div>
{draggable && <div className='str-chat__drag-handle' />}
</div>
);
})}
</DragAndDropContainer>
</fieldset>
);
};