umami/src/components/input/WebsiteSelect.tsx

66 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-12-27 22:20:36 +00:00
import { useState, Key } from 'react';
2023-02-15 10:27:18 +00:00
import { Dropdown, Item } from 'react-basics';
import useApi from 'components/hooks/useApi';
import useMessages from 'components/hooks/useMessages';
2023-10-15 21:07:53 +00:00
import styles from './WebsiteSelect.module.css';
2023-12-27 22:20:36 +00:00
import Empty from 'components/common/Empty';
2023-02-15 10:27:18 +00:00
2023-12-03 11:07:03 +00:00
export function WebsiteSelect({
websiteId,
onSelect,
}: {
2023-12-27 22:20:36 +00:00
websiteId?: string;
2023-12-03 11:07:03 +00:00
onSelect?: (key: any) => void;
}) {
2023-12-27 22:20:36 +00:00
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState<Key>(websiteId);
const { formatMessage, labels, messages } = useMessages();
2023-02-15 10:27:18 +00:00
const { get, useQuery } = useApi();
2023-12-27 22:20:36 +00:00
const { data: websites, isLoading } = useQuery({
queryKey: ['websites:me', { query }],
queryFn: () => get('/me/websites', { query, pageSize: 5 }),
2023-12-02 04:27:59 +00:00
});
2023-12-27 22:20:36 +00:00
const { data: website } = useQuery({
queryKey: ['websites', { selectedId }],
queryFn: () => get(`/websites/${selectedId}`),
enabled: !!selectedId,
});
const renderValue = () => {
return website?.name;
};
const renderEmpty = () => {
return <Empty message={formatMessage(messages.noResultsFound)} />;
};
const handleSelect = (value: any) => {
setSelectedId(value);
onSelect?.(value);
};
2023-02-15 10:27:18 +00:00
2023-12-27 22:20:36 +00:00
const handleSearch = (value: string) => {
setQuery(value);
2023-02-15 10:27:18 +00:00
};
return (
<Dropdown
2023-10-15 21:07:53 +00:00
menuProps={{ className: styles.dropdown }}
2023-12-27 22:20:36 +00:00
items={websites?.data}
value={selectedId as string}
2023-02-15 10:27:18 +00:00
renderValue={renderValue}
2023-12-27 22:20:36 +00:00
renderEmpty={renderEmpty}
onSelect={handleSelect}
2023-02-15 10:27:18 +00:00
alignment="end"
placeholder={formatMessage(labels.selectWebsite)}
2023-12-27 22:20:36 +00:00
allowSearch={true}
onSearch={handleSearch}
isLoading={isLoading}
2023-02-15 10:27:18 +00:00
>
2023-02-24 10:41:02 +00:00
{({ id, name }) => <Item key={id}>{name}</Item>}
2023-02-15 10:27:18 +00:00
</Dropdown>
);
}
2023-04-21 15:00:42 +00:00
export default WebsiteSelect;