import React, { useState, useEffect } from 'react'; import { api, ShareWith, ShareType, ShareWithOption } from '../Common/Api'; import './ShareSelection.scss'; type Props = { selectShare: (selection: ShareWithOption) => void; shareType?: ShareType[]; excluded?: { groupIds?: string[]; userIds?: string[]; }; placeholder?: string; } const ShareSelection: React.FC = (props) => { const [search, setSearch] = useState(''); const [hasFocus, setFocus] = useState(false); const [showSearchResults, setShowSearchResults] = useState(false); const [recommendations, setRecommendations] = useState(); const [searchResults, setSearchResults] = useState(); const shareType = props.shareType || [ShareType.User, ShareType.Group]; const excluded = { userIds: props.excluded?.userIds || [], groupIds: props.excluded?.groupIds || [], }; const placeholder = props.placeholder || t('bbb', 'Name, group, ...'); useEffect(() => { setSearchResults(undefined); const searchQuery = search; if (!searchQuery) { return; } api.searchShareWith(searchQuery, shareType).then(result => { if (searchQuery === search) { setSearchResults(result); } }); }, [search]); useEffect(() => { api.getRecommendedShareWith(shareType).then(result => setRecommendations(result)); }, []); useEffect(() => { setTimeout(() => setShowSearchResults(hasFocus), 100); }, [hasFocus]); async function selectShare(share: ShareWithOption) { props.selectShare(share); setSearch(''); } function renderSearchResults(options: ShareWith|undefined) { const results = options ? [ ...options.users.filter(user => !excluded.userIds.includes(user.value.shareWith)), ...options.groups.filter(group => !excluded.groupIds.includes(group.value.shareWith)), ] : []; const renderOption = (option: ShareWithOption) => { return (
  • selectShare(option)}> {option.label}{option.value.shareType === ShareType.Group ? ` (${t('bbb', 'Group')})` : ''}
  • ); }; return (
      {!options ?
    • {t('bbb', 'Searching')}
    • : ( (results.length === 0 && search) ?
    • {t('bbb', 'No matches')}
    • : results.map(renderOption) )}
    ); } return (
    setSearch(ev.currentTarget.value)} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} placeholder={placeholder} /> {showSearchResults && renderSearchResults((search && searchResults) ? searchResults : ((recommendations && !search) ? recommendations : undefined))}
    ); }; export default ShareSelection;