1 import axios from 'axios';
2 import PropTypes from 'prop-types';
3 import React, { useCallback, useEffect, useState } from 'react';
4 import { Alert, Button, Form, ListGroup } from 'react-bootstrap';
5 import { useTranslation } from 'react-i18next';
7 import Icon from './Icon';
8 import ChannelBox from '../discord-guilds/ChannelBox';
9 import debounce from '../../helpers/debounce';
11 const DiscordChannelSelect = ({
20 const [resolved, setResolved] = useState(null);
21 const [results, setResults] = useState([]);
22 const [search, setSearch] = useState('');
23 const [showResults, setShowResults] = useState(false);
25 const ref = React.useRef(null);
26 const { t } = useTranslation();
29 const handleEventOutside = e => {
30 if (ref.current && !ref.current.contains(e.target)) {
31 setShowResults(false);
34 document.addEventListener('click', handleEventOutside, true);
35 document.addEventListener('focus', handleEventOutside, true);
37 document.removeEventListener('click', handleEventOutside, true);
38 document.removeEventListener('focus', handleEventOutside, true);
43 const fetch = useCallback(debounce(async (guild, phrase, types) => {
47 ctrl = new AbortController();
49 const response = await axios.get(`/api/discord-guilds/${guild}/channels`, {
57 setResults(response.data);
63 if (ctrl) ctrl.abort();
68 fetch(guild, search, types);
69 }, [guild, search, ...types]);
74 .get(`/api/discord-channels/${value}`)
76 setResolved(response.data);
84 return <div className="d-flex align-items-center justify-content-between">
85 <span>{resolved ? <ChannelBox channel={resolved} /> : value}</span>
88 onClick={() => onChange({ guild: null, target: { name, value: '' }})}
89 title={t('button.unset')}
90 variant="outline-danger"
92 <Icon.REMOVE title="" />
96 return <div className={`discord-select ${showResults ? 'expanded' : 'collapsed'}`} ref={ref}>
98 className="search-input"
99 name={Math.random().toString(20).substr(2, 10)}
100 onChange={e => setSearch(e.target.value)}
101 onFocus={() => setShowResults(true)}
105 <div className="search-results-holder">
107 <ListGroup className="search-results">
108 {results.map(result =>
112 onClick={() => onChange({
114 target: { name, value: result.channel_id },
117 <ChannelBox channel={result} />
122 <Alert className="search-results" variant="info">
123 {t('search.noResults')}
130 DiscordChannelSelect.propTypes = {
131 guild: PropTypes.string,
132 isInvalid: PropTypes.bool,
133 name: PropTypes.string,
134 onBlur: PropTypes.func,
135 onChange: PropTypes.func,
136 types: PropTypes.arrayOf(PropTypes.number),
137 value: PropTypes.string,
140 export default DiscordChannelSelect;