Compare commits

..

2 Commits

Author SHA1 Message Date
bagas 190486fad0 feat: add toast
Docker Build and Push / build-and-push (push) Successful in 6m54s
2026-03-01 23:03:46 +07:00
bagas d339f41ced feat: add modal for editing and deleting form
Docker Build and Push / build-and-push (push) Successful in 6m55s
2026-03-01 20:54:34 +07:00
8 changed files with 293 additions and 28 deletions
+133
View File
@@ -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
View File
@@ -8,6 +8,7 @@ import {
} from "react-router";
import type { Route } from "./+types/root";
import { AuthProvider } from "@/app/context/auth-context";
import { ToastProvider } from "@/app/context/toast-context";
import "./app.css";
export const links: Route.LinksFunction = () => [
@@ -44,7 +45,9 @@ export function Layout({ children }: { children: React.ReactNode }) {
export default function App() {
return (
<AuthProvider>
<Outlet />
<ToastProvider>
<Outlet />
</ToastProvider>
</AuthProvider>
);
}
+6 -1
View File
@@ -8,6 +8,7 @@ import { FormInput } from "@/components/shared/form-input"
import { FormButton } from "@/components/shared/form-button"
import { QuestionEditor } from "@/components/forms/question-editor"
import { useAuth } from "@/app/context/auth-context"
import { useToast } from "@/app/context/toast-context"
import { createForm } from "@/lib/api"
import type { CreateQuestion } from "@/lib/types"
@@ -15,6 +16,7 @@ const TYPES_WITH_OPTIONS = ["multiple_choice", "checkbox", "dropdown"]
export default function CreateFormPage() {
const { user, loading: authLoading } = useAuth()
const { success, error: showError } = useToast()
const navigate = useNavigate()
const [title, setTitle] = useState("")
@@ -65,9 +67,12 @@ export default function CreateFormPage() {
description: description.trim(),
questions,
})
success("Form created successfully!")
navigate(`/form/${result.id}`)
} 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 {
setSubmitting(false)
}
+6 -1
View File
@@ -7,6 +7,7 @@ import { FormInput } from "@/components/shared/form-input"
import { FormButton } from "@/components/shared/form-button"
import { QuestionEditor } from "@/components/forms/question-editor"
import { useAuth } from "@/app/context/auth-context"
import { useToast } from "@/app/context/toast-context"
import { getFormById, updateForm } from "@/lib/api"
import type { CreateQuestion } from "@/lib/types"
@@ -15,6 +16,7 @@ const TYPES_WITH_OPTIONS = ["multiple_choice", "checkbox", "dropdown"]
export default function EditFormPage() {
const { id } = useParams()
const { user, loading: authLoading } = useAuth()
const { success, error: showError } = useToast()
const navigate = useNavigate()
const [title, setTitle] = useState("")
@@ -101,9 +103,12 @@ export default function EditFormPage() {
description: description.trim(),
questions,
})
success("Form updated successfully!")
navigate(`/form/${id}`)
} 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 {
setSubmitting(false)
}
+126 -22
View File
@@ -1,6 +1,7 @@
import { useState, useEffect } from "react"
import { Link, useParams, useNavigate } from "react-router"
import {
AlertTriangle,
ArrowLeft,
BarChart3,
Calendar,
@@ -16,17 +17,23 @@ import { FormButton } from "@/components/shared/form-button"
import { QuestionPreview } from "@/components/forms/question-preview"
import { getFormById, deleteForm } from "@/lib/api"
import { useAuth } from "@/app/context/auth-context"
import { useToast } from "@/app/context/toast-context"
import type { FormDetail } from "@/lib/types"
export default function FormPreviewPage() {
const { id } = useParams()
const navigate = useNavigate()
const { user } = useAuth()
const { success, error: showError } = useToast()
const [form, setForm] = useState<FormDetail | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
const [deleting, setDeleting] = useState(false)
const [confirmText, setConfirmText] = useState("")
const [showEditWarning, setShowEditWarning] = useState(false)
const CONFIRM_PHRASE = "Aku suka femboy jadi hapus form ini"
useEffect(() => {
if (!id) return
@@ -52,9 +59,10 @@ export default function FormPreviewPage() {
setDeleting(true)
try {
await deleteForm(id)
success("Form deleted successfully.")
navigate("/forms")
} catch {
setError("Failed to delete form.")
showError("Failed to delete form.")
setShowDeleteConfirm(false)
} finally {
setDeleting(false)
@@ -149,17 +157,32 @@ export default function FormPreviewPage() {
Responses
</FormButton>
</Link>
<Link to={`/form/${id}/edit`}>
<FormButton type="button" variant="ghost" size="sm">
{form.response_count > 0 ? (
<FormButton
type="button"
variant="ghost"
size="sm"
onClick={() => setShowEditWarning(true)}
>
<Pencil className="h-4 w-4" />
Edit
</FormButton>
</Link>
) : (
<Link to={`/form/${id}/edit`}>
<FormButton type="button" variant="ghost" size="sm">
<Pencil className="h-4 w-4" />
Edit
</FormButton>
</Link>
)}
<FormButton
type="button"
variant="ghost"
size="sm"
onClick={() => setShowDeleteConfirm(true)}
onClick={() => {
setConfirmText("")
setShowDeleteConfirm(true)
}}
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
@@ -206,29 +229,110 @@ export default function FormPreviewPage() {
{showDeleteConfirm && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div className="mx-4 w-full max-w-sm rounded-xl border border-border bg-card p-6 shadow-lg">
<h2 className="text-lg font-semibold text-card-foreground">Delete Form</h2>
<p className="mt-2 text-sm text-muted-foreground">
Are you sure you want to delete this form? This action cannot be
undone.
{form.response_count > 0 ? (
<>
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30">
<AlertTriangle className="h-6 w-6 text-amber-600 dark:text-amber-400" />
</div>
<h2 className="text-center text-lg font-semibold text-card-foreground">Delete Form with Responses</h2>
<p className="mt-2 text-center text-sm text-muted-foreground">
This form has <span className="font-semibold text-foreground">{form.response_count} response{form.response_count > 1 ? "s" : ""}</span>. Deleting it will permanently remove all responses. This action cannot be undone.
</p>
<p className="mt-4 text-sm text-muted-foreground">
To confirm, type <span className="font-mono font-semibold text-foreground">{CONFIRM_PHRASE}</span> below:
</p>
<input
type="text"
value={confirmText}
onChange={(e) => setConfirmText(e.target.value)}
placeholder="Type the phrase above"
className="mt-2 w-full rounded-lg border border-input bg-background px-3.5 py-2.5 text-sm text-foreground placeholder:text-muted-foreground outline-none transition-colors focus:border-primary focus:ring-2 focus:ring-primary/20"
autoFocus
/>
<div className="mt-5 flex items-center justify-end gap-3">
<FormButton
type="button"
variant="ghost"
size="sm"
onClick={() => setShowDeleteConfirm(false)}
disabled={deleting}
>
Cancel
</FormButton>
<FormButton
type="button"
size="sm"
onClick={handleDelete}
disabled={deleting || confirmText !== CONFIRM_PHRASE}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleting ? "Deleting..." : "Delete Forever"}
</FormButton>
</div>
</>
) : (
<>
<h2 className="text-lg font-semibold text-card-foreground">Delete Form</h2>
<p className="mt-2 text-sm text-muted-foreground">
Are you sure you want to delete this form? This action cannot be
undone.
</p>
<div className="mt-6 flex items-center justify-end gap-3">
<FormButton
type="button"
variant="ghost"
size="sm"
onClick={() => setShowDeleteConfirm(false)}
disabled={deleting}
>
Cancel
</FormButton>
<FormButton
type="button"
size="sm"
onClick={handleDelete}
disabled={deleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleting ? "Deleting..." : "Delete"}
</FormButton>
</div>
</>
)}
</div>
</div>
)}
{showEditWarning && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div className="mx-4 w-full max-w-sm rounded-xl border border-border bg-card p-6 shadow-lg">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30">
<AlertTriangle className="h-6 w-6 text-amber-600 dark:text-amber-400" />
</div>
<h2 className="text-center text-lg font-semibold text-card-foreground">Cannot Edit Form</h2>
<p className="mt-2 text-center text-sm text-muted-foreground">
This form already has <span className="font-semibold text-foreground">{form.response_count} response{form.response_count > 1 ? "s" : ""}</span>. Editing a form with existing responses is not allowed to preserve data integrity.
</p>
<div className="mt-6 flex items-center justify-end gap-3">
<div className="mt-5 flex flex-col gap-2">
<Link to={`/form/${id}/responses`}>
<FormButton
type="button"
variant="outline"
size="sm"
className="w-full"
>
<BarChart3 className="h-4 w-4" />
View Responses
</FormButton>
</Link>
<FormButton
type="button"
variant="ghost"
size="sm"
onClick={() => setShowDeleteConfirm(false)}
disabled={deleting}
className="w-full"
onClick={() => setShowEditWarning(false)}
>
Cancel
</FormButton>
<FormButton
type="button"
size="sm"
onClick={handleDelete}
disabled={deleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleting ? "Deleting..." : "Delete"}
Close
</FormButton>
</div>
</div>
+6 -1
View File
@@ -3,12 +3,14 @@ import { Link, useNavigate } from "react-router"
import { FormInput } from "@/components/shared/form-input"
import { FormButton } from "@/components/shared/form-button"
import { useAuth } from "@/app/context/auth-context"
import { useToast } from "@/app/context/toast-context"
import { setTokens } from "@/lib/auth"
import { login } from "@/lib/api"
export default function LoginPage() {
const navigate = useNavigate()
const { user, loading: authLoading, refreshUser } = useAuth()
const { success, error: showError } = useToast()
useEffect(() => {
if (!authLoading && user) {
@@ -46,9 +48,12 @@ export default function LoginPage() {
const data = await login(form.email, form.password)
setTokens(data.access_token, data.refresh_token, rememberMe)
refreshUser()
success("Welcome back!")
navigate("/forms")
} 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 {
setLoading(false)
}
+6 -1
View File
@@ -3,11 +3,13 @@ import { Link, useNavigate } from "react-router"
import { FormInput } from "@/components/shared/form-input"
import { FormButton } from "@/components/shared/form-button"
import { useAuth } from "@/app/context/auth-context"
import { useToast } from "@/app/context/toast-context"
import { register } from "@/lib/api"
export default function RegisterPage() {
const navigate = useNavigate()
const { user, loading: authLoading } = useAuth()
const { success, error: showError } = useToast()
useEffect(() => {
if (!authLoading && user) {
@@ -50,9 +52,12 @@ export default function RegisterPage() {
try {
await register(form.email, form.password)
success("Account created successfully! Please sign in.")
navigate("/login")
} 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 })
}
}
+6 -1
View File
@@ -12,6 +12,7 @@ import {
import { Navbar } from "@/components/shared/navbar"
import { Footer } from "@/components/shared/footer"
import { FormButton } from "@/components/shared/form-button"
import { useToast } from "@/app/context/toast-context"
import { getFormById, submitFormResponse } from "@/lib/api"
import type { FormDetail, Question } from "@/lib/types"
@@ -24,6 +25,7 @@ export default function SubmitFormPage() {
const [submitting, setSubmitting] = useState(false)
const [submitted, setSubmitted] = useState(false)
const [validationErrors, setValidationErrors] = useState<Record<string, string>>({})
const { success, error: showError } = useToast()
useEffect(() => {
if (!id) return
@@ -98,9 +100,12 @@ export default function SubmitFormPage() {
answer: answers[q.id].trim(),
})),
})
success("Response submitted successfully!")
setSubmitted(true)
} 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 {
setSubmitting(false)
}