improved ContactForm.tsx UI

This commit is contained in:
slawk0
2024-12-01 14:02:47 +01:00
parent 679abd1c55
commit c3088e9d4e
2 changed files with 49 additions and 13 deletions

View File

@@ -4,6 +4,7 @@ import { axiosClient } from '../../App.tsx';
import { AxiosResponse } from 'axios';
import { useEffect, useState } from 'react';
import LoadingWheel from './LoadingWheel.tsx';
type Input = {
contact: string;
};
@@ -19,6 +20,8 @@ function ContactForm({ InitializeContact, setContactsList }: ContactFormProps) {
const [suggestions, setSuggestions] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [notFound, setNotFound] = useState<boolean>(false);
const [selectedIndex, setSelectedIndex] = useState<number>(0);
useEffect(() => {
const fetchSuggestions = async () => {
if (contactInput?.length >= 3) {
@@ -28,6 +31,7 @@ function ContactForm({ InitializeContact, setContactsList }: ContactFormProps) {
`/api/chat/contacts/suggestions/${contactInput}`,
);
setSuggestions(response.data);
setSelectedIndex(0); // Reset selection to first item when suggestions update
if (response.data.length < 1) {
setIsLoading(false);
setNotFound(true);
@@ -51,38 +55,62 @@ function ContactForm({ InitializeContact, setContactsList }: ContactFormProps) {
}, [contactInput]);
const submitContact: SubmitHandler<Input> = async (data) => {
const contact = data.contact.trim();
const contactToSubmit =
suggestions.length > 0 ? suggestions[selectedIndex] : data.contact.trim();
try {
// Checks if contact username already exist on the list
setContactsList((prevContacts) => {
if (prevContacts.some((c) => c.username === contact)) {
if (prevContacts.some((c) => c.username === contactToSubmit)) {
return prevContacts;
}
return prevContacts;
});
const response: AxiosResponse<ContactsProps> = await axiosClient.post(
`/api/chat/contact/${contact}`,
`/api/chat/contact/${contactToSubmit}`,
);
console.log('contact post response: ', response.data);
InitializeContact(response.data);
setContactsList((prevContacts) => {
if (!prevContacts.some((c) => c.username === contact)) {
if (!prevContacts.some((c) => c.username === contactToSubmit)) {
return [...prevContacts, response.data];
}
return prevContacts;
});
reset({ contact: '' });
setSuggestions([]); // Clear suggestions after adding contact
setSuggestions([]);
} catch (error) {
console.error('Error adding contact:', error);
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (suggestions.length > 0) {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setSelectedIndex((prev) => (prev + 1) % suggestions.length);
break;
case 'ArrowUp':
e.preventDefault();
setSelectedIndex(
(prev) => (prev - 1 + suggestions.length) % suggestions.length,
);
break;
case 'Enter':
if (suggestions.length > 0) {
e.preventDefault();
reset({ contact: suggestions[selectedIndex] });
handleSubmit(submitContact)();
}
break;
}
}
};
return (
<>
<div className="text-center">
@@ -91,6 +119,7 @@ function ContactForm({ InitializeContact, setContactsList }: ContactFormProps) {
className="text-black bg-green-50 pl-2 shadow-lg rounded-md h-8 mb-2 mt-2"
type="text"
placeholder="Enter contact"
onKeyDown={handleKeyDown}
{...register('contact', {
minLength: 4,
maxLength: 20,
@@ -99,13 +128,20 @@ function ContactForm({ InitializeContact, setContactsList }: ContactFormProps) {
</form>
<div className="m-1">
{suggestions?.length > 0 ? (
<ul className="text-left p-1 bg-gray-800 shadow-md rounded-md w-full border">
{suggestions.map((suggestion) => (
<ul className="text-left p-1 bg-gray-900 shadow-md rounded-md w-full border">
{suggestions.map((suggestion, index) => (
<li
key={suggestion}
className="p-2 hover:bg-gray-100 cursor-pointer"
className={`p-2 cursor-pointer ${
index === selectedIndex
? 'bg-gray-500'
: 'hover:bg-gray-500'
}`}
onClick={() => {
reset({ contact: suggestion });
handleSubmit(() =>
submitContact({ contact: suggestion }),
)();
setSuggestions([]);
}}
>

View File

@@ -49,7 +49,7 @@ function Chat() {
try {
const parsedContact = JSON.parse(storedContact);
if (parsedContact) {
InitializeContact(parsedContact);
initializeContact(parsedContact);
}
} catch (error) {
console.error('Failed to parse stored contact:', error);
@@ -58,7 +58,7 @@ function Chat() {
}
}, []);
function InitializeContact(newContact: ContactsProps) {
function initializeContact(newContact: ContactsProps) {
setMessages([]); // Clear messages from previous contact
localStorage.setItem('contact', JSON.stringify(newContact)); // Set current contact in localstorage
setCurrentContact(newContact);
@@ -146,10 +146,10 @@ function Chat() {
<div className="h-screen bg-[#1E1E1E] flex flex-col">
<ContactForm
setContactsList={setContactsList}
InitializeContact={InitializeContact}
InitializeContact={initializeContact}
/>
<ContactsList
InitializeContact={InitializeContact}
InitializeContact={initializeContact}
contactsList={contactsList}
setContactsList={setContactsList}
setCurrentContact={setCurrentContact}