import React, { useEffect, useRef, useState } from 'react'; import Modal, { RequiredModalProps } from '@/components/elements/Modal'; import { Field, Form, Formik, FormikHelpers, useFormikContext } from 'formik'; import { Actions, useStoreActions, useStoreState } from 'easy-peasy'; import { object, string } from 'yup'; import { debounce } from 'lodash-es'; import FormikFieldWrapper from '@/components/elements/FormikFieldWrapper'; import InputSpinner from '@/components/elements/InputSpinner'; import getServers from '@/api/getServers'; import { Server } from '@/api/server/getServer'; import { ApplicationStore } from '@/state'; import { httpErrorToHuman } from '@/api/http'; import { Link } from 'react-router-dom'; import styled from 'styled-components/macro'; import tw from 'twin.macro'; type Props = RequiredModalProps; interface Values { term: string; } const ServerResult = styled(Link)` ${tw`flex items-center bg-neutral-900 p-4 rounded border-l-4 border-neutral-900 no-underline`}; transition: all 250ms linear; &:hover { ${tw`shadow border-cyan-500`}; } &:not(:last-of-type) { ${tw`mb-2`}; } `; const SearchWatcher = () => { const { values, submitForm } = useFormikContext(); useEffect(() => { if (values.term.length >= 3) { submitForm(); } }, [ values.term ]); return null; }; export default ({ ...props }: Props) => { const ref = useRef(null); const [ loading, setLoading ] = useState(false); const [ servers, setServers ] = useState([]); const isAdmin = useStoreState(state => state.user.data!.rootAdmin); const { addError, clearFlashes } = useStoreActions((actions: Actions) => actions.flashes); const search = debounce(({ term }: Values, { setSubmitting }: FormikHelpers) => { setLoading(true); setSubmitting(false); clearFlashes('search'); getServers(term) .then(servers => setServers(servers.items.filter((_, index) => index < 5))) .catch(error => { console.error(error); addError({ key: 'search', message: httpErrorToHuman(error) }); }) .then(() => setLoading(false)); }, 500); useEffect(() => { if (props.visible) { setTimeout(() => ref.current?.focus(), 250); } }, [ props.visible ]); return (
{servers.length > 0 &&
{ servers.map(server => ( props.onDismissed()} >

{server.name}

{ server.allocations.filter(alloc => alloc.default).map(allocation => ( {allocation.alias || allocation.ip}:{allocation.port} )) }

{server.node}
)) }
}
); };