feat: ensure manual & programmatic url works

This commit is contained in:
karishmas6
2024-10-11 05:51:14 +05:30
parent b8e12cba35
commit f8ea0aeefc

View File

@@ -1,7 +1,6 @@
import { useState, useCallback, useEffect, } from 'react';
import type { SyntheticEvent, } from 'react';
import { useState, useEffect, useCallback } 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';
@@ -18,44 +17,41 @@ export const UrlForm = ({
handleRefresh,
setCurrentAddress,
}: Props) => {
// states:
// Internal address state, initially set to currentAddress. We need this else the input field will not update with recordingUrl
const [address, setAddress] = useState<string>(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 no manual change, use the currentAddress prop
if (address === currentAddress) {
url = currentAddress;
}
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!`);
}
// Add protocol if missing
if (!/^(?:f|ht)tps?\:\/\//.test(url)) {
url = "https://" + url;
setAddress(url); // Update the input field to reflect protocol addition
}
try {
// Validate the URL
new URL(url);
setCurrentAddress(url);
} catch (e) {
alert(`ERROR: ${url} is not a valid url!`);
}
};
// Sync internal state with currentAddress prop when it changes
useEffect(() => {
setAddress(currentAddress)
setAddress(currentAddress);
}, [currentAddress]);
return (