diff --git a/src/components/CenterPanel/forms/URLForm.tsx b/src/components/CenterPanel/forms/URLForm.tsx new file mode 100644 index 0000000..d38de2a --- /dev/null +++ b/src/components/CenterPanel/forms/URLForm.tsx @@ -0,0 +1,69 @@ +import { useState } from 'react'; +import { useQR } from '../../../context/QRContext'; +import { useToast } from '../../../context/ToastContext'; + +function isValidUrl(v: string) { + if (!v.trim()) return true; + return /^https?:\/\/.+\..+/.test(v.trim()); +} + +export function URLForm() { + const { state, dispatch } = useQR(); + const { show } = useToast(); + const { websiteUrl } = state.formData.url; + const [shortening, setShortening] = useState(false); + const valid = isValidUrl(websiteUrl); + + const set = (v: string) => dispatch({ type: 'SET_FORM_FIELD', qrType: 'url', field: 'websiteUrl', value: v }); + + const shorten = async () => { + if (!websiteUrl.trim() || !valid) return; + setShortening(true); + try { + const res = await fetch(`https://is.gd/create.php?format=json&url=${encodeURIComponent(websiteUrl)}`); + const data = await res.json(); + if (data.shorturl) { set(data.shorturl); show('URL shortened!', 'success'); } + else show(data.errormessage ?? 'Could not shorten URL', 'error'); + } catch { + show('Shortener unavailable', 'error'); + } finally { + setShortening(false); + } + }; + + return ( +
Must start with http:// or https://
} +