pleased complete this incomplete compnent perfectly """… · The Chat Archive
Explore / Programming pleased complete this incomplete compnent perfectly """ import React, { useState,… Save Share Download ▾ Reportpleased complete this incomplete compnent perfectly
"""
import React, { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { z } from 'zod';
import { motion, AnimatePresence } from 'framer-motion';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "../hooks/use-toast";
import { AlertCircle, CheckCircle2, Trash2, Plus, Save, RefreshCw, Settings2, Mail, Globe, Clock, Bell } from 'lucide-react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { userService } from '../app/services/user.service';
import { User, userSchema } from '../app/types/api.types';
export default function SettingsComponent() {
const router = useRouter();
const { toast } = useToast();
const [user, setUser] = useState<User | null>(null);
const [isMonitoring, setIsMonitoring] = useState(false);
const [monitoringStatus, setMonitoringStatus] = useState('');
const [errors, setErrors] = useState<Partial<Record<keyof User, string>>>({});
const [isSaving, setIsSaving] = useState(false);
const [showResetDialog, setShowResetDialog] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
// Load initial settings
useEffect(() => {
const fetchSettings = async () => {
try {
setIsLoading(true);
const userData = await userService.getSettings();
setUser(userData);
setIsMonitoring(userData.verified);
setHasUnsavedChanges(false);
} catch (error: any) {
console.error('Error fetching settings:', error);
toast({
title: "Error Loading Settings",
description: error.message || "Failed to load settings. Please try again.",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
};
fetchSettings();
}, [toast]);
// Form validation
const validateForm = useCallback(() => {
if (!user) return false;
try {
userSchema.parse(user);
setErrors({});
return true;
} catch (error) {
if (error instanceof z.ZodError) {
const newErrors: Partial<Record<keyof User, string>> = {};
error.errors.forEach((err) => {
if (err.path[0]) {
newErrors[err.path[0] as keyof User] = err.message;
}
});
setErrors(newErrors);
}
return false;
}
}, [user]);
// Save settings handler
const handleUpdateSettings = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
Assistant2024-11-14 20:19 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Nov 14, 2024
Added to archive Nov 16, 2026
ID 01m7h4294g2hbxm3d3e4c6a6h8Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: fe38c28a3249e8ecd77f83d5a3e0a91f
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
if (!validateForm()) {
toast({
title: "Validation Error",
description: "Please check the form for errors.",
variant: "destructive",
});
return;
}
setIsSaving(true);
try {
const payload = {
listOfUrls: user.listOfUrls,
timePeriod: user.timePeriod,
emailSend: user.emailSend,
};
const data = await userService.updateSettings(payload);
setUser(data.user);
setHasUnsavedChanges(false);
toast({
title: "Settings Updated",
description: "Your settings have been saved successfully.",
});
// Navigate to home after successful save
router.push('/home');
} catch (error: any) {
console.error('Error updating settings:', error);
toast({
title: "Update Failed",
description: error.message || 'Failed to update settings. Please try again.',
variant: "destructive",
});
} finally {
setIsSaving(false);
}
// URL management handlers
const handleUrlChange = useCallback((index: number, value: string) => {
if (!user) return;
const newUrls = [...user.listOfUrls];
newUrls[index] = value;
setUser({ ...user, listOfUrls: newUrls });
setHasUnsavedChanges(true);
}, [user]);
const addUrl = useCallback(() => {
if (!user) return;
setUser({ ...user, listOfUrls: [...user.listOfUrls, ''] });
setHasUnsavedChanges(true);
}, [user]);
const removeUrl = useCallback((index: number) => {
if (!user) return;
const newUrls = user.listOfUrls.filter((_, i) => i !== index);
setUser({ ...user, listOfUrls: newUrls });
setHasUnsavedChanges(true);
}, [user]);
// Reset settings handler
const resetSettings = useCallback(() => {
if (!user?.id) return;
setUser({
...user,
listOfUrls: [],
timePeriod: '5m',
emailSend: false,
verified: false,
});
setShowResetDialog(false);
setHasUnsavedChanges(true);
toast({
title: "Settings Reset",
description: "Settings have been reset to default values. Don't forget to save your changes.",
});
// Monitoring toggle handler
const handleMonitoringToggle = async () => {
if (!user) return;
try {
setMonitoringStatus('Updating monitoring status...');
if (isMonitoring) {
await userService.stopMonitoring();
setIsMonitoring(false);
toast({
title: "Monitoring Stopped",
description: "Website monitoring has been deactivated.",
});
} else {
await userService.startMonitoring();
setIsMonitoring(true);
toast({
title: "Monitoring Started",
description: "Website monitoring has been activated.",
});
}
} catch (error: any) {
console.error('Error toggling monitoring:', error);
toast({
title: "Error",
description: error.message || "Failed to update monitoring status",
variant: "destructive",
});
setIsMonitoring(!isMonitoring); // Revert state on error
} finally {
setMonitoringStatus('');
}
// Loading state
if (isLoading) {
return (
Loading your settings...
);
}
// Error state
if (!user) {
return (
Failed to Load Settings
Please refresh the page to try again.
<Button onClick={() => window.location.reload()}>
Refresh Page
);
}
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
className="container mx-auto py-8 px-4 md:px-0 max-w-4xl"
>
Account Settings
<Tabs defaultValue="monitoring" className="space-y-8">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="monitoring">Monitoring</TabsTrigger>
<TabsTrigger value="account">Account</TabsTrigger>
<TabsTrigger value="notifications">Notifications</TabsTrigger>
</TabsList>
<form onSubmit={handleUpdateSettings} className="space-y-8">
<TabsContent value="monitoring">
<Card>
<CardHeader>
<CardTitle className="flex items-center text-2xl">
<Globe className="mr-2" /> Monitoring Settings
</CardTitle>
<CardDescription>
Configure your website monitoring preferences
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="space-y-4">
<div>
<Label htmlFor="timePeriod">Check Interval</Label>
<Select
value={user.timePeriod}
onValueChange={(value: User['timePeriod']) => {
setUser(prev => prev ? { ...prev, timePeriod: value } : prev);
setHasUnsavedChanges(true);
}}
>
<SelectTrigger>
<SelectValue placeholder="Select interval" />
</SelectTrigger>
<SelectContent>
<SelectItem value="30s">Every 30 seconds</SelectItem>
<SelectItem value="1m">Every minute</SelectItem>
<SelectItem value="3m">Every 3 minutes</SelectItem>
<SelectItem value="5m">Every 5 minutes</SelectItem>
<SelectItem value="10m">Every 10 minutes</SelectItem>
<SelectItem value="1h">Every hour</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>URLs to Monitor</Label>
<AnimatePresence>
{user.listOfUrls.map((url, index) => (
<motion.div
key={index}
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="flex gap-2"
>
<Input
value={url}
onChange={(e) => handleUrlChange(index, e.target.value)}
placeholder="https://example.com"
className={errors.listOfUrls ? 'border-destructive' : ''}
/>
<Button
type="button"
variant="destructive"
size="icon"
onClick={() => removeUrl(index)}
disabled={user.listOfUrls.length === 1}
>
<Trash2 className="h-4 w-4" />
</Button>
</motion.div>
))}
</AnimatePresence>
<Button
type="button"
variant="outline"
onClick={addUrl}
className="w-full mt-2"
>
<Plus className="mr-2 h-4 w-4" />
Add URL
</Button>
</div>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="account">
<Card>
<CardHeader>
<CardTitle className="flex items-center text-2xl">
<Mail className="mr-2" /> Account Information
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label>Username</Label>
<Input value={user.username} disabled />
</div>
<div>
<Label>Email</Label>
<Input value={user.email} disabled />
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="notifications">
<Card>
<CardHeader>
<CardTitle className="flex items-center text-2xl">
<Bell className="mr-2" /> Notification Settings
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center space-x-2">
<Switch
id="emailSend"
checked={user.emailSend}
onCheckedChange={(checked) => {
setUser(prev => prev ? { ...prev, emailSend: checked } : prev);
setHasUnsavedChanges(true);
}}
/>
<Label htmlFor="emailSend">Receive email notifications</Label>
</div>
</CardContent>
</Card>
</TabsContent>
<div className="flex justify-between pt-6">
<Button
type="button"
variant="outline"
onClick={() => setShowResetDialog(true)}
>
Reset to Defaults
</Button>
<div className="flex items-center gap-4">
{hasUnsavedChanges && (
<span className="text-sm text-muted-foreground">
You have unsaved changes
</span>
)}
<Button
type="submit"
disabled={isSaving || !hasUnsavedChanges}
className="min-w-[120px]"
>
{isSaving ? (
<>
<RefreshCw className="mr-2 h-4 w-4 animate-spin" />
Saving...
</>
) : (
<>
<Save className="mr-2 h-4 w-4" />
Save
</>
)}
</Button>
</div>
</div>
</form>
</Tabs>
<Dialog open={showResetDialog} onOpenChange={setShowResetDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>Reset Settings</DialogTitle>
<DialogDescription>
This will reset all settings to their default values.
"""
"""
from its old version
""
'use client'
import { useState, useEffect, useCallback } from 'react'
import { z } from 'zod'
import { motion, AnimatePresence } from 'framer-motion'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { useToast } from "../hooks/use-toast"
import { AlertCircle, CheckCircle2, Trash2, Plus, Save, RefreshCw, Settings2, Mail, Globe, Clock, Bell } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Progress } from "@/components/ui/progress"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import { userService } from '../app/services/user.service'
import { User, userSchema } from '../app/types/api.types'
const DEBOUNCE_DELAY = 500 // ms
export default function SettingsPage() {
// State Management
const [user, setUser] = useState<User | null>(null)
const [isMonitoring, setIsMonitoring] = useState(false)
const [monitoringStatus, setMonitoringStatus] = useState('')
const [errors, setErrors] = useState<Partial<Record<keyof User, string>>>({})
const [isSaving, setIsSaving] = useState(false)
const [showResetDialog, setShowResetDialog] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
const { toast } = useToast()
// Initial Data Fetching
useEffect(() => {
const fetchSettings = async () => {
try {
setIsLoading(true)
const userData = await userService.getSettings()
setUser(userData)
setIsMonitoring(userData.verified)
setHasUnsavedChanges(false)
} catch (error: any) {
console.error('Error fetching settings:', error)
toast({
title: "Error Loading Settings",
description: error.message || "Failed to load settings. Please try again.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}
// Form Validation
const validateForm = useCallback((): boolean => {
try {
if (user) {
userSchema.parse(user)
setErrors({})
return true
}
return false
} catch (error) {
if (error instanceof z.ZodError) {
const newErrors: Partial<Record<keyof User, string>> = {}
error.errors.forEach((err) => {
if (err.path[0]) {
newErrors[err.path[0] as keyof User] = err.message
}
})
setErrors(newErrors)
}
return false
}
}, [user])
// Unsaved Changes Warning
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (hasUnsavedChanges) {
e.preventDefault()
e.returnValue = ''
}
}
window.addEventListener('beforeunload', handleBeforeUnload)
return () => window.removeEventListener('beforeunload', handleBeforeUnload)
// Settings Update Handler
const handleUpdateSettings = async (e: React.FormEvent) => {
e.preventDefault()
if (!user) return
if (!validateForm()) {
toast({
title: "Validation Error",
description: "Please check the form for errors.",
variant: "destructive",
})
return
}
setIsSaving(true)
try {
const payload = {
listOfUrls: user.listOfUrls,
timePeriod: user.timePeriod,
emailSend: user.emailSend,
}
const data = await userService.updateSettings(payload)
setUser(data.user)
setHasUnsavedChanges(false)
toast({
title: "Settings Updated",
description: data.message,
})
} catch (error: any) {
console.error('Error updating settings:', error)
toast({
title: "Update Failed",
description: error.message || 'Failed to update settings. Please try again.',
variant: "destructive",
})
} finally {
setIsSaving(false)
}
// Monitoring Toggle Handler
const handleMonitoringToggle = async () => {
if (!user) return
try {
setMonitoringStatus('Updating monitoring status...')
if (isMonitoring) {
await userService.stopMonitoring()
setIsMonitoring(false)
toast({
title: "Monitoring Stopped",
description: "Website monitoring has been deactivated.",
})
} else {
await userService.startMonitoring()
setIsMonitoring(true)
toast({
title: "Monitoring Started",
description: "Website monitoring has been activated.",
})
}
} catch (error: any) {
console.error('Error toggling monitoring:', error)
toast({
title: "Error",
description: error.message || "Failed to update monitoring status",
variant: "destructive",
})
// Revert the monitoring state on error
setIsMonitoring(!isMonitoring)
} finally {
setMonitoringStatus('')
}
}
// URL Management Handlers
const handleUrlChange = useCallback((index: number, value: string) => {
if (!user) return
const newUrls = [...user.listOfUrls]
newUrls[index] = value
setUser({ ...user, listOfUrls: newUrls })
setHasUnsavedChanges(true)
}, [user])
const addUrl = useCallback(() => {
if (!user) return
setUser({ ...user, listOfUrls: [...user.listOfUrls, ''] })
setHasUnsavedChanges(true)
}, [user])
const removeUrl = useCallback((index: number) => {
if (!user) return
const newUrls = user.listOfUrls.filter((_, i) => i !== index)
setUser({ ...user, listOfUrls: newUrls })
setHasUnsavedChanges(true)
}, [user])
// Reset Settings Handler
const resetSettings = useCallback(() => {
if (!user?.id) return
setUser({
id: user.id,
username: user.username,
email: user.email,
listOfUrls: [],
timePeriod: '5m',
emailSend: false,
verified: false,
})
setShowResetDialog(false)
setHasUnsavedChanges(true)
toast({
title: "Settings Reset",
description: "All settings have been reset to default values. Don't forget to save your changes.",
})
}, [user, toast])
// Loading State
if (isLoading) {
return (
)
}
// Error State
if (!user) {
return (
Failed to Load Settings
Please refresh the page to try again.
<Button onClick={() => window.location.reload()}>
Refresh Page
)
}
return (
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="flex items-center justify-between mb-8"
>
Account Settings
</motion.div>
<Tabs defaultValue="monitoring" className="space-y-8">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="monitoring">Monitoring</TabsTrigger>
<TabsTrigger value="account">Account</TabsTrigger>
<TabsTrigger value="notifications">Notifications</TabsTrigger>
</TabsList>
<form onSubmit={handleUpdateSettings}>
<TabsContent value="monitoring" className="space-y-8">
<Card>
<CardHeader className="bg-gradient-to-r from-primary to-primary-foreground text-primary-foreground">
<CardTitle className="text-2xl flex items-center">
<Globe className="mr-2" /> Monitoring Settings
</CardTitle>
<CardDescription className="text-primary-foreground/90">
Configure your website monitoring preferences.
</CardDescription>
</CardHeader>
<CardContent className="p-6">
<div className="space-y-6">
<div>
<Label htmlFor="timePeriod" className="text-lg font-semibold mb-2 block">
Check Interval
</Label>
<Select
value={user.timePeriod}
onValueChange={(value: string) => {
setUser(prev => prev ? { ...prev, timePeriod: value as User['timePeriod'] } : prev)
setHasUnsavedChanges(true)
}}
>
<SelectTrigger id="timePeriod" className="w-full">
<SelectValue placeholder="Select interval" />
</SelectTrigger>
<SelectContent>
<SelectItem value="30s">Every 30 seconds</SelectItem>
<SelectItem value="1m">Every 1 minute</SelectItem>
<SelectItem value="3m">Every 3 minutes</SelectItem>
<SelectItem value="5m">Every 5 minutes</SelectItem>
<SelectItem value="10m">Every 10 minutes</SelectItem>
<SelectItem value="1h">Every 1 hour</SelectItem>
</SelectContent>
</Select>
{errors.timePeriod && (
<p className="text-destructive text-sm mt-1">{errors.timePeriod}</p>
)}
</div>
<div>
<Label className="text-lg font-semibold mb-2 block">URLs to Monitor</Label>
<AnimatePresence>
{user.listOfUrls.map((url, index) => (
<motion.div
key={index}
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.2 }}
className="flex items-center space-x-2 mb-2"
>
<Input
value={url}
onChange={(e) => handleUrlChange(index, e.target.value)}
placeholder="https://example.com"
className={errors.listOfUrls ? 'border-destructive' : ''}
/>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="destructive"
size="icon"
onClick={() => removeUrl(index)}
disabled={user.listOfUrls.length === 1}
>
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
{user.listOfUrls.length === 1
? "At least one URL is required"
: "Remove URL"
}
</TooltipContent>
</Tooltip>
</motion.div>
))}
</AnimatePresence>
{errors.listOfUrls && (
<p className="text-destructive text-sm mt-1">{errors.listOfUrls}</p>
)}
<Button
type="button"
variant="outline"
size="sm"
onClick={addUrl}
className="mt-2"
>
<Plus className="mr-2 h-4 w-4" />
Add URL
</Button>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-2xl flex items-center">
<Clock className="mr-2" /> Monitoring Status
</CardTitle>
<CardDescription>Manage your website monitoring status.</CardDescription>
</CardHeader>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<Switch
id="monitoring-toggle"
checked={isMonitoring}
onCheckedChange={handleMonitoringToggle}
disabled={user.listOfUrls.length === 0}
/>
<Label htmlFor="monitoring-toggle" className="text-lg select-none">
{isMonitoring ? 'Monitoring is Active' : 'Monitoring is Inactive'}
</Label>
</div>
{isMonitoring ? (
<CheckCircle2 className="h-6 w-6 text-green-500" />
) : (
<AlertCircle className="h-6 w-6 text-yellow-500" />
)}
</div>
{monitoringStatus && (
<p className="text-blue-500 text-sm mt-2">{monitoringStatus}</p>
)}
{user.listOfUrls.length === 0 && (<p className="text-destructive text-sm mt-2">
Add at least one URL to enable monitoring
</p>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="account" className="space-y-8">
<Card>
<CardHeader>
<CardTitle className="text-2xl flex items-center">
<Mail className="mr-2" /> Account Information
</CardTitle>
<CardDescription>Manage your account details.</CardDescription>
</CardHeader>
<CardContent className="p-6 space-y-4">
<div>
<Label className="text-lg font-semibold mb-2 block">Username</Label>
<Tooltip>
<TooltipTrigger asChild>
<Input
value={user?.username}
disabled
className="bg-muted cursor-not-allowed"
/>
</TooltipTrigger>
<TooltipContent>
Username cannot be changed
</TooltipContent>
</Tooltip>
</div>
<div>
<Label className="text-lg font-semibold mb-2 block">Email</Label>
<Tooltip>
<TooltipTrigger asChild>
<Input
value={user?.email}
disabled
className="bg-muted cursor-not-allowed"
/>
</TooltipTrigger>
<TooltipContent>
Contact support to change email
</TooltipContent>
</Tooltip>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="notifications" className="space-y-8">
<Card>
<CardHeader>
<CardTitle className="text-2xl flex items-center">
<Bell className="mr-2" /> Notification Preferences
</CardTitle>
<CardDescription>Manage how you receive notifications.</CardDescription>
</CardHeader>
<CardContent className="p-6">
<div className="flex items-center space-x-4">
<Switch
id="email-notifications"
checked={user?.emailSend || false}
onCheckedChange={(checked) => {
setUser(prev => prev ? { ...prev, emailSend: checked } : prev)
setHasUnsavedChanges(true)
}}
/>
<Label htmlFor="email-notifications" className="text-lg select-none">
Receive email notifications
</Label>
</div>
{errors.emailSend && (
<p className="text-destructive text-sm mt-1">{errors.emailSend}</p>
)}
<p className="text-sm text-muted-foreground mt-2">
You will receive email notifications when your monitored websites experience downtime or issues.
</p>
</CardContent>
</Card>
</TabsContent>
<div className="flex justify-between items-center mt-8">
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="outline"
onClick={() => setShowResetDialog(true)}
className="border-destructive text-destructive hover:bg-destructive/10"
>
Reset to Defaults
</Button>
</TooltipTrigger>
<TooltipContent>Reset all settings to default values</TooltipContent>
</Tooltip>
<div className="flex items-center gap-4">
{hasUnsavedChanges && (
<span className="text-sm text-muted-foreground">
You have unsaved changes
</span>
)}
<Tooltip>
<TooltipTrigger asChild>
<Button
type="submit"
disabled={isSaving || !hasUnsavedChanges}
className="px-8"
>
{isSaving ? (
<>
<RefreshCw className="animate-spin mr-2 h-4 w-4" />
Saving...
</>
) : (
<>
<Save className="mr-2 h-4 w-4" />
Save Changes
</>
)}
</Button>
</TooltipTrigger>
<TooltipContent>
{!hasUnsavedChanges ? 'No changes to save' : 'Save all changes'}
</TooltipContent>
</Tooltip>
</div>
</div>
</form>
</Tabs>
<Dialog open={showResetDialog} onOpenChange={setShowResetDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>Are you sure you want to reset?</DialogTitle>
<DialogDescription>
This action will reset all your settings to their default values. This cannot be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setShowResetDialog(false)}>
Cancel
</Button>
<Button variant="destructive" onClick={resetSettings}>
Reset
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</TooltipProvider>
)
}
"""
"""
save changes doesnt button is not wokring fi nad make it g oto /home after saving succesfully make it gracefull and show a loder until server response and make it good and perfect """
"""
"""
// app/settings/page.tsx
import SettingsComponent from '@/components/SettingsComponent';
export default function SettingsPage() {
return (
);
}
"""
"""
import api from './api';
import { User, AnalyticsData } from '../types/api.types';
import { authService } from './auth.service';
interface UpdateSettingsPayload {
listOfUrls: string[];
timePeriod: User['timePeriod'];
emailSend: boolean;
}
interface UpdateSettingsResponse {
message: string;
user: User;
}
interface MonitoringResponse {
message: string;
}
export const userService = {
getSettings: async (): Promise => {
const token = authService.getToken();
if (!token) {
authService.logout();
throw new Error('No token found');
}
try {
const response: any = await api.get('/user/settings', {
headers: {
Authorization: Bearer ${token},
},
});
return response.data;
} catch (error: any) {
if (error.response && (error.response.status === 403 || error.response.status === 401)) {
authService.logout();
}
throw error;
}
updateSettings: async (payload: UpdateSettingsPayload): Promise => {
const token = authService.getToken();
if (!token) {
authService.logout();
throw new Error('No token found');
}
try {
const response: any = await api.put('/user/settings', payload, {
headers: {
Authorization: Bearer ${token},
},
});
return response.data;
} catch (error: any) {
if (error.response && (error.response.status === 403 || error.response.status === 401)) {
authService.logout();
}
throw error;
}
startMonitoring: async (): Promise => {
const token = authService.getToken();
if (!token) {
authService.logout();
throw new Error('No token found');
}
try {
const response: any = await api.post('/user/monitor/start', null, {
headers: {
Authorization: Bearer ${token},
},
});
return response.data;
} catch (error: any) {
if (error.response && (error.response.status === 403 || error.response.status === 401)) {
authService.logout();
}
throw error;
}
stopMonitoring: async (): Promise => {
const token = authService.getToken();
if (!token) {
authService.logout();
throw new Error('No token found');
}
try {
const response: any = await api.post('/user/monitor/stop', null, {
headers: {
Authorization: Bearer ${token},
},
});
return response.data;
} catch (error: any) {
if (error.response && (error.response.status === 403 || error.response.status === 401)) {
authService.logout();
}
throw error;
}
},
};
"""
import { z } from 'zod';
export const userSchema = z.object({
id: z.string(),
username: z.string().min(3).max(30),
email: z.string().email().max(100),
listOfUrls: z.array(z.string().url()).min(1, "At least one URL is required"),
timePeriod: z.enum(['30s', '1m', '3m', '5m', '10m', '1h']).default('5m'),
emailSend: z.boolean().default(false),
verified: z.boolean().default(false),
});
export type User = z.infer;
export interface ApiError {
message: string;
errors?: Array<{
field: string;
message: string;
}>;
}
export interface VerificationState {
status: 'loading' | 'success' | 'error';
message: string;
}
export interface PageProps {
params: Promise<{ token: string }>;
}
// src/types/analytics.types.ts
export interface StatusCodeDistribution {
statusCode: number;
count: number;
percentage: number; // Now a number instead of a string
}
export interface UptimePerUrl {
url: string;
successCount: number;
totalCount: number;
uptimePercentage: number; // Now a number instead of a string
}
export interface ChecksOverTime {
period: string;
count: number;
averageResponseTime: number; // Now a number representing milliseconds
}
export interface ResponseTimeDistribution {
range: string;
count: number;
averageResponseTime: number; // Now a number representing milliseconds
}
export interface TopSlowestUrl {
url: string;
averageResponseTime: number; // Now a number representing milliseconds
totalChecks: number;
}
export interface RecentIssue {
url: string;
statusCode: number;
checkedAt: string; // ISO date string
screenshotUrl?: string;
responseTime: number; // Now a number representing milliseconds
}
export interface AnalyticsData {
totalChecks: number;
successfulChecks: number;
successPercentage: number;
failedChecks: number;
failurePercentage: number;
statusCodeDistribution: StatusCodeDistribution[];
uptimePerUrl: UptimePerUrl[];
checksOverTime: ChecksOverTime[];
responseTimeDistribution: ResponseTimeDistribution[];
topSlowestUrls: TopSlowestUrl[];
recentIssues: RecentIssue[];
}
export interface DateRange {
from: Date;
to: Date;
}
Certainly! Let's complete the SettingsComponent by addressing the following requirements:
Complete the Incomplete JSX Structure : Ensure all components, especially the Dialog, are properly closed.
Fix the "Save Changes" Button : Ensure it triggers the save handler correctly.
Navigate to /home After Successful Save : Redirect the user gracefully after settings are saved.
Show a Loader While Saving : Indicate to the user that the save operation is in progress.
Below is the fully completed and refined SettingsComponent incorporating all these aspects:
// components/SettingsComponent.tsx
'use client';
import React, { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { z } from 'zod';
import { motion, AnimatePresence } from 'framer-motion';
import {
Button
} from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle
} from "@/components/ui/card";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "../hooks/use-toast";
import {
AlertCircle,
CheckCircle2,
Trash2,
Plus,
Save,
RefreshCw,
Settings2,
Mail,
Globe,
Clock,
Bell
} from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger
} from "@/components/ui/tooltip";
import { userService } from '../app/services/user.service';
import { User, userSchema } from '../app/types/api.types';
export default function SettingsComponent() {
const router = useRouter();
const { toast } = useToast();
const [user, setUser] = useState<User | null>(null);
const [isMonitoring, setIsMonitoring] = useState(false);
const [monitoringStatus, setMonitoringStatus] = useState('');
const [errors, setErrors] = useState<Partial<Record<keyof User, string>>>({});
const [isSaving, setIsSaving] = useState(false);
const [showResetDialog, setShowResetDialog] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
// Load initial settings
useEffect(() => {
const fetchSettings = async () => {
try {
setIsLoading(true);
const userData = await userService.getSettings();
setUser(userData);
setIsMonitoring(userData.verified);
setHasUnsavedChanges(false);
} catch (error: any) {
console.error('Error fetching settings:', error);
toast({
title: "Error Loading Settings",
description: error.message || "Failed to load settings. Please try again.",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
};
fetchSettings();
}, [toast]);
// Form validation
const validateForm = useCallback(() => {
if (!user) return false;
try {
userSchema.parse(user);
setErrors({});
return true;
} catch (error) {
if (error instanceof z.ZodError) {
const newErrors: Partial<Record<keyof User, string>> = {};
error.errors.forEach((err) => {
if (err.path[0]) {
newErrors[err.path[0] as keyof User] = err.message;
}
});
setErrors(newErrors);
}
return false;
}
}, [user]);
// Save settings handler
const handleUpdateSettings = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
if (!validateForm()) {
toast({
title: "Validation Error",
description: "Please check the form for errors.",
variant: "destructive",
});
return;
}
setIsSaving(true);
try {
const payload = {
listOfUrls: user.listOfUrls,
timePeriod: user.timePeriod,
emailSend: user.emailSend,
};
const data = await userService.updateSettings(payload);
setUser(data.user);
setHasUnsavedChanges(false);
toast({
title: "Settings Updated",
description: "Your settings have been saved successfully.",
});
// Navigate to home after successful save
router.push('/home');
} catch (error: any) {
console.error('Error updating settings:', error);
toast({
title: "Update Failed",
description: error.message || 'Failed to update settings. Please try again.',
variant: "destructive",
});
} finally {
setIsSaving(false);
}
};
// URL management handlers
const handleUrlChange = useCallback((index: number, value: string) => {
if (!user) return;
const newUrls = [...user.listOfUrls];
newUrls[index] = value;
setUser({ ...user, listOfUrls: newUrls });
setHasUnsavedChanges(true);
}, [user]);
const addUrl = useCallback(() => {
if (!user) return;
setUser({ ...user, listOfUrls: [...user.listOfUrls, ''] });
setHasUnsavedChanges(true);
}, [user]);
const removeUrl = useCallback((index: number) => {
if (!user) return;
const newUrls = user.listOfUrls.filter((_, i) => i !== index);
setUser({ ...user, listOfUrls: newUrls });
setHasUnsavedChanges(true);
}, [user]);
// Reset settings handler
const resetSettings = useCallback(() => {
if (!user?.id) return;
setUser({
...user,
listOfUrls: [],
timePeriod: '5m',
emailSend: false,
verified: false,
});
setShowResetDialog(false);
setHasUnsavedChanges(true);
toast({
title: "Settings Reset",
description: "Settings have been reset to default values. Don't forget to save your changes.",
});
}, [user, toast]);
// Monitoring toggle handler
const handleMonitoringToggle = async () => {
if (!user) return;
try {
setMonitoringStatus('Updating monitoring status...');
setIsMonitoring(prev => !prev); // Optimistic UI update
if (isMonitoring) {
await userService.stopMonitoring();
toast({
title: "Monitoring Stopped",
description: "Website monitoring has been deactivated.",
});
} else {
await userService.startMonitoring();
toast({
title: "Monitoring Started",
description: "Website monitoring has been activated.",
});
}
} catch (error: any) {
console.error('Error toggling monitoring:', error);
toast({
title: "Error",
description: error.message || "Failed to update monitoring status",
variant: "destructive",
});
setIsMonitoring(!isMonitoring); // Revert state on error
} finally {
setMonitoringStatus('');
}
};
// Loading state
if (isLoading) {
return (
<div className="flex justify-center items-center min-h-screen">
<div className="w-full max-w-md">
<Progress value={undefined} className="w-full" />
<p className="text-center mt-4 text-muted-foreground">Loading your settings...</p>
</div>
</div>
);
}
// Error state
if (!user) {
return (
<div className="flex flex-col items-center justify-center min-h-screen">
<AlertCircle className="h-12 w-12 text-destructive mb-4" />
<h2 className="text-2xl font-bold mb-2">Failed to Load Settings</h2>
<p className="text-muted-foreground mb-4">Please refresh the page to try again.</p>
<Button onClick={() => window.location.reload()}>
<RefreshCw className="mr-2 h-4 w-4" />
Refresh Page
</Button>
</div>
);
}
return (
<TooltipProvider>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
className="container mx-auto py-8 px-4 md:px-0 max-w-4xl"
>
<div className="flex items-center justify-between mb-8">
<h1 className="text-4xl font-bold">Account Settings</h1>
<Settings2 className="h-8 w-8 text-primary" />
</div>
<Tabs defaultValue="monitoring" className="space-y-8">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="monitoring">Monitoring</TabsTrigger>
<TabsTrigger value="account">Account</TabsTrigger>
<TabsTrigger value="notifications">Notifications</TabsTrigger>
</TabsList>
<form onSubmit={handleUpdateSettings} className="space-y-8">
<TabsContent value="monitoring">
<Card>
<CardHeader>
<CardTitle className="flex items-center text-2xl">
<Globe className="mr-2" /> Monitoring Settings
</CardTitle>
<CardDescription>
Configure your website monitoring preferences
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="space-y-4">
<div>
<Label htmlFor="timePeriod">Check Interval</Label>
<Select
value={user.timePeriod}
onValueChange={(value: User['timePeriod']) => {
setUser(prev => prev ? { ...prev, timePeriod: value } : prev);
setHasUnsavedChanges(true);
}}
>
<SelectTrigger>
<SelectValue placeholder="Select interval" />
</SelectTrigger>
<SelectContent>
<SelectItem value="30s">Every 30 seconds</SelectItem>
<SelectItem value="1m">Every minute</SelectItem>
<SelectItem value="3m">Every 3 minutes</SelectItem>
<SelectItem value="5m">Every 5 minutes</SelectItem>
<SelectItem value="10m">Every 10 minutes</SelectItem>
<SelectItem value="1h">Every hour</SelectItem>
</SelectContent>
</Select>
{errors.timePeriod && (
<p className="text-destructive text-sm mt-1">{errors.timePeriod}</p>
)}
</div>
<div className="space-y-2">
<Label>URLs to Monitor</Label>
<AnimatePresence>
{user.listOfUrls.map((url, index) => (
<motion.div
key={index}
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="flex gap-2"
>
<Input
value={url}
onChange={(e) => handleUrlChange(index, e.target.value)}
placeholder="https://example.com"
className={errors.listOfUrls ? 'border-destructive' : ''}
/>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="destructive"
size="icon"
onClick={() => removeUrl(index)}
disabled={user.listOfUrls.length === 1}
>
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
{user.listOfUrls.length === 1
? "At least one URL is required"
: "Remove URL"
}
</TooltipContent>
</Tooltip>
</motion.div>
))}
</AnimatePresence>
<Button
type="button"
variant="outline"
onClick={addUrl}
className="w-full mt-2"
>
<Plus className="mr-2 h-4 w-4" />
Add URL
</Button>
{errors.listOfUrls && (
<p className="text-destructive text-sm mt-1">{errors.listOfUrls}</p>
)}
</div>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="account">
<Card>
<CardHeader>
<CardTitle className="flex items-center text-2xl">
<Mail className="mr-2" /> Account Information
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label>Username</Label>
<Tooltip>
<TooltipTrigger asChild>
<Input value={user.username} disabled className="bg-muted cursor-not-allowed" />
</TooltipTrigger>
<TooltipContent>
Username cannot be changed
</TooltipContent>
</Tooltip>
</div>
<div>
<Label>Email</Label>
<Tooltip>
<TooltipTrigger asChild>
<Input value={user.email} disabled className="bg-muted cursor-not-allowed" />
</TooltipTrigger>
<TooltipContent>
Contact support to change email
</TooltipContent>
</Tooltip>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="notifications">
<Card>
<CardHeader>
<CardTitle className="flex items-center text-2xl">
<Bell className="mr-2" /> Notification Settings
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center space-x-2">
<Switch
id="emailSend"
checked={user.emailSend}
onCheckedChange={(checked) => {
setUser(prev => prev ? { ...prev, emailSend: checked } : prev);
setHasUnsavedChanges(true);
}}
/>
<Label htmlFor="emailSend">Receive email notifications</Label>
</div>
</CardContent>
</Card>
</TabsContent>
<div className="flex justify-between pt-6">
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="outline"
onClick={() => setShowResetDialog(true)}
className="border-destructive text-destructive hover:bg-destructive/10"
>
Reset to Defaults
</Button>
</TooltipTrigger>
<TooltipContent>
Reset all settings to default values
</TooltipContent>
</Tooltip>
<div className="flex items-center gap-4">
{hasUnsavedChanges && (
<span className="text-sm text-muted-foreground">
You have unsaved changes
</span>
)}
<Tooltip>
<TooltipTrigger asChild>
<Button
type="submit"
disabled={isSaving || !hasUnsavedChanges}
className="min-w-[120px]"
>
{isSaving ? (
<>
<RefreshCw className="mr-2 h-4 w-4 animate-spin" />
Saving...
</>
) : (
<>
<Save className="mr-2 h-4 w-4" />
Save
</>
)}
</Button>
</TooltipTrigger>
<TooltipContent>
{!hasUnsavedChanges ? 'No changes to save' : 'Save all changes'}
</TooltipContent>
</Tooltip>
</div>
</div>
</form>
</Tabs>
<Dialog open={showResetDialog} onOpenChange={setShowResetDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>Reset Settings</DialogTitle>
<DialogDescription>
This will reset all settings to their default values. Are you sure you want to proceed?
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setShowResetDialog(false)}>
Cancel
</Button>
<Button variant="destructive" onClick={resetSettings}>
Reset
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Optionally, you can include a loader overlay when saving */}
{isSaving && (
<div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
<Progress className="w-1/2" />
</div>
)}
</motion.div>
</TooltipProvider>
);
}
Explanation of the Enhancements:
Completing the Dialog Component :
DialogFooter : Added to include the "Cancel" and "Reset" buttons, allowing the user to either confirm the reset action or cancel it.
Dialog Description : Provided a clearer message prompting the user to confirm the reset action.
Fixing the "Save Changes" Button :
Disabled State : The button is disabled when isSaving is true or when there are no unsaved changes (!hasUnsavedChanges).
Loader Indicator : When isSaving is true, a spinning RefreshCw icon alongside the text "Saving..." indicates that the save operation is in progress.
Handler Function : The handleUpdateSettings function now correctly handles the form submission, validation, saving, and navigation to /home upon successful save.
Navigating to /home After Successful Save :
Utilized router.push('/home') to redirect the user to the home page after the settings are successfully saved.
Showing a Loader While Saving :
Implemented an optional full-screen overlay with a Progress bar to visually indicate that a save operation is in progress. This is controlled by the isSaving state.
Tooltip Enhancements :
Added tooltips to buttons like "Remove URL", "Reset to Defaults", and the "Save" button to provide additional context to the user.
Error Handling and Validation Messages :
Displayed validation error messages beneath the respective input fields if any validation fails.
Provided user-friendly error messages via toasts for better user experience.
Optimistic UI Update for Monitoring Toggle :
Updated the monitoring toggle optimistically for a snappier UI response, reverting the state if the server operation fails.
Accessibility and UX Improvements :
Ensured that all interactive elements have appropriate labels and tooltips.
Disabled inputs and buttons where necessary to prevent unintended actions.
Additional Recommendations:
Accessibility : Ensure that all interactive elements are accessible via keyboard and screen readers. This includes proper ARIA labels where necessary.
Form Optimization : Consider debouncing form inputs or implementing auto-save features for improved user experience.
Testing : Thoroughly test the component across different devices and scenarios to ensure all functionalities work as expected.
Error Boundary : Implement an error boundary to catch and handle unexpected errors gracefully within the component tree.
With these enhancements, the SettingsComponent should function seamlessly, providing users with a smooth and intuitive interface to manage their account settings.
Copy first response
Not yet included in a published release.
Used consistent spacing and layout for better readability.