import { useState, memo, useCallback } from "react"; import Switch from "../../components/Switch"; import { useSettingsContext } from "../../SettingsContext"; import { motion, AnimatePresence } from "framer-motion"; import { CustomShortcut } from "../../types/AppProps"; function formatUrl(inputUrl: string) { const protocolRegex = /^(http:\/\/|https:\/\/|ftp:\/\/)/; return protocolRegex.test(inputUrl) ? inputUrl : `https://${inputUrl}`; } const Shortcuts = memo(() => { const { settingsState, setSettingsState } = useSettingsContext(); const [newTitle, setNewTitle] = useState(""); const [isFormVisible, setFormVisible] = useState(false); const [newURL, setNewURL] = useState(""); const switchChange = useCallback((shortcutName: string, isOn: boolean) => { setSettingsState((prevState) => { const updatedShortcuts = prevState.shortcuts.map((shortcut) => shortcut.name === shortcutName ? { ...shortcut, enabled: isOn } : shortcut ); return { ...prevState, shortcuts: updatedShortcuts }; }); }, [setSettingsState]); const isValidTitle = useCallback((title: string) => title.trim() !== "", []); const isValidURL = useCallback((url: string) => { const pattern = new RegExp("^(https?:\\/\\/)?[\\w.-]+[\\w.-]+(/[\\w.-]*)*$", "i"); return pattern.test(url); }, []); const addNewCustomShortcut = useCallback(() => { if (isValidTitle(newTitle) && isValidURL(newURL)) { const newShortcut: CustomShortcut = { name: newTitle.trim(), url: formatUrl(newURL).trim(), icon: newTitle[0] }; const updatedCustomShortcuts = [...settingsState.customshortcuts, newShortcut]; setSettingsState({ ...settingsState, customshortcuts: updatedCustomShortcuts }); setNewTitle(""); setNewURL(""); setFormVisible(false); } else { // Replace with a more user-friendly way to display errors alert("Please enter a valid title and URL."); } }, [newTitle, newURL, isValidTitle, isValidURL, setSettingsState]); const deleteCustomShortcut = useCallback((index: number) => { setSettingsState((prevState) => ({ ...prevState, customshortcuts: prevState.customshortcuts.filter((_, i) => i !== index), })); }, [setSettingsState]); const toggleForm = useCallback(() => { setFormVisible((isVisible) => !isVisible); }, []); return (
{isFormVisible &&
setNewTitle(e.target.value)} /> setNewURL(e.target.value)} /> Add
}
{!isFormVisible && ( )} {/* Shortcuts Section */} {settingsState.shortcuts ? ( settingsState.shortcuts.map((shortcut, index) => shortcut.name && (
{shortcut.name} switchChange(shortcut.name, isOn)} />
)) ) : (

Loading shortcuts...

)} {/* Custom Shortcuts Section */} {settingsState.customshortcuts ? ( settingsState.customshortcuts.map((shortcut, index) => (
{shortcut.name}
)) ) : (

Loading custom shortcuts...

)}
); }); export default Shortcuts;