import { useState } 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) { // Regular expression to check if the URL starts with http://, https://, or ftp:// const protocolRegex = /^(http:\/\/|https:\/\/|ftp:\/\/)/; // Check if the URL starts with one of the protocols if (protocolRegex.test(inputUrl)) { return inputUrl; // The URL is fine as is } else { return `https://${inputUrl}`; // Prepend https:// to the URL } } export default function Shortcuts() { const { settingsState, setSettingsState } = useSettingsContext(); const switchChange = (shortcutName: string, isOn: boolean): void => { const updatedShortcuts = settingsState.shortcuts.map((shortcut) => { if (shortcut.name === shortcutName) { return { ...shortcut, enabled: isOn }; } return shortcut; }); setSettingsState({ ...settingsState, shortcuts: updatedShortcuts }); }; const [newTitle, setNewTitle] = useState(""); const [newURL, setNewURL] = useState(""); const isValidTitle = (title: string): boolean => title.trim() !== ""; const isValidURL = (url: string): boolean => { const pattern = new RegExp("^(https?:\\/\\/)?[\\w.-]+[\\w.-]+$", "i"); return pattern.test(url); }; const addNewCustomShortcut = (): void => { 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 console.error("Please enter a valid title and URL."); } }; const deleteCustomShortcut = (index: number): void => { const updatedCustomShortcuts = settingsState.customshortcuts.filter((_, i) => i !== index); setSettingsState({ ...settingsState, customshortcuts: updatedCustomShortcuts }); }; const [isFormVisible, setFormVisible] = useState(false); const toggleForm = () => { setFormVisible(!isFormVisible); }; return (
{isFormVisible ? (
setNewTitle(e.target.value)} /> setNewURL(e.target.value)} /> Add
) : ( Add Custom Shortcut )}
{/* 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...

)}
); }