This commit is contained in:
@@ -0,0 +1,133 @@
|
|||||||
|
import { createContext, useContext, useState, useCallback, useRef, useEffect, type ReactNode } from "react"
|
||||||
|
import { X, CheckCircle2, AlertCircle, AlertTriangle, Info } from "lucide-react"
|
||||||
|
|
||||||
|
type ToastVariant = "success" | "error" | "warning" | "info"
|
||||||
|
|
||||||
|
type ToastPhase = "enter" | "visible" | "exit"
|
||||||
|
|
||||||
|
interface Toast {
|
||||||
|
id: string
|
||||||
|
message: string
|
||||||
|
variant: ToastVariant
|
||||||
|
phase: ToastPhase
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ToastContextType {
|
||||||
|
toast: (message: string, variant?: ToastVariant) => void
|
||||||
|
success: (message: string) => void
|
||||||
|
error: (message: string) => void
|
||||||
|
warning: (message: string) => void
|
||||||
|
info: (message: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const ToastContext = createContext<ToastContextType | null>(null)
|
||||||
|
|
||||||
|
const TOAST_DURATION = 4000
|
||||||
|
const EXIT_DURATION = 300
|
||||||
|
|
||||||
|
const variantStyles: Record<ToastVariant, string> = {
|
||||||
|
success: "border-green-200 bg-green-50 text-green-800 dark:border-green-800 dark:bg-green-950 dark:text-green-200",
|
||||||
|
error: "border-red-200 bg-red-50 text-red-800 dark:border-red-800 dark:bg-red-950 dark:text-red-200",
|
||||||
|
warning: "border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-200",
|
||||||
|
info: "border-blue-200 bg-blue-50 text-blue-800 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-200",
|
||||||
|
}
|
||||||
|
|
||||||
|
const variantIcons: Record<ToastVariant, typeof CheckCircle2> = {
|
||||||
|
success: CheckCircle2,
|
||||||
|
error: AlertCircle,
|
||||||
|
warning: AlertTriangle,
|
||||||
|
info: Info,
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [toasts, setToasts] = useState<Toast[]>([])
|
||||||
|
const timersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map())
|
||||||
|
|
||||||
|
const removeToast = useCallback((id: string) => {
|
||||||
|
timersRef.current.delete(id)
|
||||||
|
setToasts((prev) => prev.filter((t) => t.id !== id))
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const startExit = useCallback((id: string) => {
|
||||||
|
setToasts((prev) =>
|
||||||
|
prev.map((t) => (t.id === id ? { ...t, phase: "exit" as ToastPhase } : t))
|
||||||
|
)
|
||||||
|
setTimeout(() => removeToast(id), EXIT_DURATION)
|
||||||
|
}, [removeToast])
|
||||||
|
|
||||||
|
const addToast = useCallback(
|
||||||
|
(message: string, variant: ToastVariant = "info") => {
|
||||||
|
const id = Math.random().toString(36).slice(2) + Date.now().toString(36)
|
||||||
|
setToasts((prev) => [...prev, { id, message, variant, phase: "enter" }])
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
setToasts((prev) =>
|
||||||
|
prev.map((t) => (t.id === id ? { ...t, phase: "visible" } : t))
|
||||||
|
)
|
||||||
|
})
|
||||||
|
const timer = setTimeout(() => startExit(id), TOAST_DURATION)
|
||||||
|
timersRef.current.set(id, timer)
|
||||||
|
},
|
||||||
|
[startExit]
|
||||||
|
)
|
||||||
|
|
||||||
|
const dismissToast = useCallback((id: string) => {
|
||||||
|
const existing = timersRef.current.get(id)
|
||||||
|
if (existing) clearTimeout(existing)
|
||||||
|
timersRef.current.delete(id)
|
||||||
|
startExit(id)
|
||||||
|
}, [startExit])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
timersRef.current.forEach((timer) => clearTimeout(timer))
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const contextValue: ToastContextType = {
|
||||||
|
toast: addToast,
|
||||||
|
success: useCallback((msg: string) => addToast(msg, "success"), [addToast]),
|
||||||
|
error: useCallback((msg: string) => addToast(msg, "error"), [addToast]),
|
||||||
|
warning: useCallback((msg: string) => addToast(msg, "warning"), [addToast]),
|
||||||
|
info: useCallback((msg: string) => addToast(msg, "info"), [addToast]),
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToastContext.Provider value={contextValue}>
|
||||||
|
{children}
|
||||||
|
|
||||||
|
<div className="fixed top-16 left-4 right-4 sm:left-auto sm:right-4 z-[100] flex flex-col gap-2 max-w-sm w-auto sm:w-full pointer-events-none">
|
||||||
|
{toasts.map((t) => {
|
||||||
|
const Icon = variantIcons[t.variant]
|
||||||
|
const phaseClass =
|
||||||
|
t.phase === "exit"
|
||||||
|
? "translate-x-[120%] opacity-0"
|
||||||
|
: "translate-x-0 opacity-100"
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={t.id}
|
||||||
|
className={`pointer-events-auto flex items-start gap-3 rounded-lg border px-4 py-3 shadow-lg transition-all duration-300 ease-in-out ${phaseClass} ${variantStyles[t.variant]}`}
|
||||||
|
style={t.phase === "enter" ? { transform: "translateX(120%)", opacity: 0 } : undefined}
|
||||||
|
>
|
||||||
|
<Icon className="h-5 w-5 shrink-0 mt-0.5" />
|
||||||
|
<p className="text-sm font-medium flex-1">{t.message}</p>
|
||||||
|
<button
|
||||||
|
onClick={() => dismissToast(t.id)}
|
||||||
|
className="shrink-0 rounded-md p-0.5 opacity-70 hover:opacity-100 transition-opacity"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</ToastContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useToast() {
|
||||||
|
const context = useContext(ToastContext)
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("useToast must be used within a ToastProvider")
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
+4
-1
@@ -8,6 +8,7 @@ import {
|
|||||||
} from "react-router";
|
} from "react-router";
|
||||||
import type { Route } from "./+types/root";
|
import type { Route } from "./+types/root";
|
||||||
import { AuthProvider } from "@/app/context/auth-context";
|
import { AuthProvider } from "@/app/context/auth-context";
|
||||||
|
import { ToastProvider } from "@/app/context/toast-context";
|
||||||
import "./app.css";
|
import "./app.css";
|
||||||
|
|
||||||
export const links: Route.LinksFunction = () => [
|
export const links: Route.LinksFunction = () => [
|
||||||
@@ -44,7 +45,9 @@ export function Layout({ children }: { children: React.ReactNode }) {
|
|||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<Outlet />
|
<ToastProvider>
|
||||||
|
<Outlet />
|
||||||
|
</ToastProvider>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { FormInput } from "@/components/shared/form-input"
|
|||||||
import { FormButton } from "@/components/shared/form-button"
|
import { FormButton } from "@/components/shared/form-button"
|
||||||
import { QuestionEditor } from "@/components/forms/question-editor"
|
import { QuestionEditor } from "@/components/forms/question-editor"
|
||||||
import { useAuth } from "@/app/context/auth-context"
|
import { useAuth } from "@/app/context/auth-context"
|
||||||
|
import { useToast } from "@/app/context/toast-context"
|
||||||
import { createForm } from "@/lib/api"
|
import { createForm } from "@/lib/api"
|
||||||
import type { CreateQuestion } from "@/lib/types"
|
import type { CreateQuestion } from "@/lib/types"
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ const TYPES_WITH_OPTIONS = ["multiple_choice", "checkbox", "dropdown"]
|
|||||||
|
|
||||||
export default function CreateFormPage() {
|
export default function CreateFormPage() {
|
||||||
const { user, loading: authLoading } = useAuth()
|
const { user, loading: authLoading } = useAuth()
|
||||||
|
const { success, error: showError } = useToast()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const [title, setTitle] = useState("")
|
const [title, setTitle] = useState("")
|
||||||
@@ -65,9 +67,12 @@ export default function CreateFormPage() {
|
|||||||
description: description.trim(),
|
description: description.trim(),
|
||||||
questions,
|
questions,
|
||||||
})
|
})
|
||||||
|
success("Form created successfully!")
|
||||||
navigate(`/form/${result.id}`)
|
navigate(`/form/${result.id}`)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : "Failed to create form.")
|
const msg = err instanceof Error ? err.message : "Failed to create form."
|
||||||
|
showError(msg)
|
||||||
|
setError(msg)
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false)
|
setSubmitting(false)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { FormInput } from "@/components/shared/form-input"
|
|||||||
import { FormButton } from "@/components/shared/form-button"
|
import { FormButton } from "@/components/shared/form-button"
|
||||||
import { QuestionEditor } from "@/components/forms/question-editor"
|
import { QuestionEditor } from "@/components/forms/question-editor"
|
||||||
import { useAuth } from "@/app/context/auth-context"
|
import { useAuth } from "@/app/context/auth-context"
|
||||||
|
import { useToast } from "@/app/context/toast-context"
|
||||||
import { getFormById, updateForm } from "@/lib/api"
|
import { getFormById, updateForm } from "@/lib/api"
|
||||||
import type { CreateQuestion } from "@/lib/types"
|
import type { CreateQuestion } from "@/lib/types"
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ const TYPES_WITH_OPTIONS = ["multiple_choice", "checkbox", "dropdown"]
|
|||||||
export default function EditFormPage() {
|
export default function EditFormPage() {
|
||||||
const { id } = useParams()
|
const { id } = useParams()
|
||||||
const { user, loading: authLoading } = useAuth()
|
const { user, loading: authLoading } = useAuth()
|
||||||
|
const { success, error: showError } = useToast()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const [title, setTitle] = useState("")
|
const [title, setTitle] = useState("")
|
||||||
@@ -101,9 +103,12 @@ export default function EditFormPage() {
|
|||||||
description: description.trim(),
|
description: description.trim(),
|
||||||
questions,
|
questions,
|
||||||
})
|
})
|
||||||
|
success("Form updated successfully!")
|
||||||
navigate(`/form/${id}`)
|
navigate(`/form/${id}`)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : "Failed to update form.")
|
const msg = err instanceof Error ? err.message : "Failed to update form."
|
||||||
|
showError(msg)
|
||||||
|
setError(msg)
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false)
|
setSubmitting(false)
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-1
@@ -17,12 +17,14 @@ import { FormButton } from "@/components/shared/form-button"
|
|||||||
import { QuestionPreview } from "@/components/forms/question-preview"
|
import { QuestionPreview } from "@/components/forms/question-preview"
|
||||||
import { getFormById, deleteForm } from "@/lib/api"
|
import { getFormById, deleteForm } from "@/lib/api"
|
||||||
import { useAuth } from "@/app/context/auth-context"
|
import { useAuth } from "@/app/context/auth-context"
|
||||||
|
import { useToast } from "@/app/context/toast-context"
|
||||||
import type { FormDetail } from "@/lib/types"
|
import type { FormDetail } from "@/lib/types"
|
||||||
|
|
||||||
export default function FormPreviewPage() {
|
export default function FormPreviewPage() {
|
||||||
const { id } = useParams()
|
const { id } = useParams()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const { user } = useAuth()
|
const { user } = useAuth()
|
||||||
|
const { success, error: showError } = useToast()
|
||||||
const [form, setForm] = useState<FormDetail | null>(null)
|
const [form, setForm] = useState<FormDetail | null>(null)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
@@ -57,9 +59,10 @@ export default function FormPreviewPage() {
|
|||||||
setDeleting(true)
|
setDeleting(true)
|
||||||
try {
|
try {
|
||||||
await deleteForm(id)
|
await deleteForm(id)
|
||||||
|
success("Form deleted successfully.")
|
||||||
navigate("/forms")
|
navigate("/forms")
|
||||||
} catch {
|
} catch {
|
||||||
setError("Failed to delete form.")
|
showError("Failed to delete form.")
|
||||||
setShowDeleteConfirm(false)
|
setShowDeleteConfirm(false)
|
||||||
} finally {
|
} finally {
|
||||||
setDeleting(false)
|
setDeleting(false)
|
||||||
|
|||||||
@@ -3,12 +3,14 @@ import { Link, useNavigate } from "react-router"
|
|||||||
import { FormInput } from "@/components/shared/form-input"
|
import { FormInput } from "@/components/shared/form-input"
|
||||||
import { FormButton } from "@/components/shared/form-button"
|
import { FormButton } from "@/components/shared/form-button"
|
||||||
import { useAuth } from "@/app/context/auth-context"
|
import { useAuth } from "@/app/context/auth-context"
|
||||||
|
import { useToast } from "@/app/context/toast-context"
|
||||||
import { setTokens } from "@/lib/auth"
|
import { setTokens } from "@/lib/auth"
|
||||||
import { login } from "@/lib/api"
|
import { login } from "@/lib/api"
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const { user, loading: authLoading, refreshUser } = useAuth()
|
const { user, loading: authLoading, refreshUser } = useAuth()
|
||||||
|
const { success, error: showError } = useToast()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!authLoading && user) {
|
if (!authLoading && user) {
|
||||||
@@ -46,9 +48,12 @@ export default function LoginPage() {
|
|||||||
const data = await login(form.email, form.password)
|
const data = await login(form.email, form.password)
|
||||||
setTokens(data.access_token, data.refresh_token, rememberMe)
|
setTokens(data.access_token, data.refresh_token, rememberMe)
|
||||||
refreshUser()
|
refreshUser()
|
||||||
|
success("Welcome back!")
|
||||||
navigate("/forms")
|
navigate("/forms")
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setErrors({ general: err instanceof Error ? err.message : "Something went wrong. Please try again." })
|
const msg = err instanceof Error ? err.message : "Something went wrong. Please try again."
|
||||||
|
showError(msg)
|
||||||
|
setErrors({ general: msg })
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,13 @@ import { Link, useNavigate } from "react-router"
|
|||||||
import { FormInput } from "@/components/shared/form-input"
|
import { FormInput } from "@/components/shared/form-input"
|
||||||
import { FormButton } from "@/components/shared/form-button"
|
import { FormButton } from "@/components/shared/form-button"
|
||||||
import { useAuth } from "@/app/context/auth-context"
|
import { useAuth } from "@/app/context/auth-context"
|
||||||
|
import { useToast } from "@/app/context/toast-context"
|
||||||
import { register } from "@/lib/api"
|
import { register } from "@/lib/api"
|
||||||
|
|
||||||
export default function RegisterPage() {
|
export default function RegisterPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const { user, loading: authLoading } = useAuth()
|
const { user, loading: authLoading } = useAuth()
|
||||||
|
const { success, error: showError } = useToast()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!authLoading && user) {
|
if (!authLoading && user) {
|
||||||
@@ -50,9 +52,12 @@ export default function RegisterPage() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await register(form.email, form.password)
|
await register(form.email, form.password)
|
||||||
|
success("Account created successfully! Please sign in.")
|
||||||
navigate("/login")
|
navigate("/login")
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setErrors({ email: err instanceof Error ? err.message : "Something went wrong. Please try again." })
|
const msg = err instanceof Error ? err.message : "Something went wrong. Please try again."
|
||||||
|
showError(msg)
|
||||||
|
setErrors({ email: msg })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
import { Navbar } from "@/components/shared/navbar"
|
import { Navbar } from "@/components/shared/navbar"
|
||||||
import { Footer } from "@/components/shared/footer"
|
import { Footer } from "@/components/shared/footer"
|
||||||
import { FormButton } from "@/components/shared/form-button"
|
import { FormButton } from "@/components/shared/form-button"
|
||||||
|
import { useToast } from "@/app/context/toast-context"
|
||||||
import { getFormById, submitFormResponse } from "@/lib/api"
|
import { getFormById, submitFormResponse } from "@/lib/api"
|
||||||
import type { FormDetail, Question } from "@/lib/types"
|
import type { FormDetail, Question } from "@/lib/types"
|
||||||
|
|
||||||
@@ -24,6 +25,7 @@ export default function SubmitFormPage() {
|
|||||||
const [submitting, setSubmitting] = useState(false)
|
const [submitting, setSubmitting] = useState(false)
|
||||||
const [submitted, setSubmitted] = useState(false)
|
const [submitted, setSubmitted] = useState(false)
|
||||||
const [validationErrors, setValidationErrors] = useState<Record<string, string>>({})
|
const [validationErrors, setValidationErrors] = useState<Record<string, string>>({})
|
||||||
|
const { success, error: showError } = useToast()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!id) return
|
if (!id) return
|
||||||
@@ -98,9 +100,12 @@ export default function SubmitFormPage() {
|
|||||||
answer: answers[q.id].trim(),
|
answer: answers[q.id].trim(),
|
||||||
})),
|
})),
|
||||||
})
|
})
|
||||||
|
success("Response submitted successfully!")
|
||||||
setSubmitted(true)
|
setSubmitted(true)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : "Failed to submit response")
|
const msg = err instanceof Error ? err.message : "Failed to submit response"
|
||||||
|
showError(msg)
|
||||||
|
setError(msg)
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false)
|
setSubmitting(false)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user