From 5f48ac71c9a6e86249bd87d3370c7280ac414e7c Mon Sep 17 00:00:00 2001 From: karishmas6 Date: Fri, 14 Jun 2024 23:08:06 +0530 Subject: [PATCH] feat: url form for browser nav --- src/components/molecules/UrlForm.tsx | 73 ++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/components/molecules/UrlForm.tsx diff --git a/src/components/molecules/UrlForm.tsx b/src/components/molecules/UrlForm.tsx new file mode 100644 index 00000000..77e1139a --- /dev/null +++ b/src/components/molecules/UrlForm.tsx @@ -0,0 +1,73 @@ +import {useState, useCallback, useEffect,} from 'react'; +import type { SyntheticEvent, } from 'react'; +import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight'; + +import { NavBarForm, NavBarInput } from "../atoms/form"; +import { UrlFormButton } from "../atoms/buttons/buttons"; +import { useSocketStore } from '../../context/socket'; +import {Socket} from "socket.io-client"; + +type Props = { + currentAddress: string; + handleRefresh: (socket: Socket) => void; + setCurrentAddress: (address: string) => void; +}; + +export const UrlForm = ({ + currentAddress, + handleRefresh, + setCurrentAddress, +}: Props) => { + // states: + const [address, setAddress] = useState(currentAddress); + // context: + const { socket } = useSocketStore(); + + const areSameAddresses = address === currentAddress; + + const onChange = useCallback((event: SyntheticEvent): void => { + setAddress((event.target as HTMLInputElement).value); + }, [address]); + + const onSubmit = (event: SyntheticEvent): void => { + event.preventDefault(); + let url = address; + + // add protocol if missing + if (!/^(?:f|ht)tps?\:\/\//.test(address)) { + url = "https://" + address; + setAddress(url); + } + + if (areSameAddresses) { + if (socket) { + handleRefresh(socket); + } + } else { + try { + // try the validity of url + new URL(url); + setCurrentAddress(url); + } catch (e) { + alert(`ERROR: ${url} is not a valid url!`); + } + } + }; + + useEffect(() => { + setAddress(currentAddress) + }, [currentAddress]); + + return ( + + + + + + + ); +};