İmage upload,sıkıştırma

This commit is contained in:
2026-01-13 23:36:40 +03:00
parent 6bbae0de21
commit 70f61a76b0
11 changed files with 795 additions and 0 deletions

View File

@@ -0,0 +1,219 @@
"use client"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { toast } from "sonner"
import { Loader2 } from "lucide-react"
import { ImageUpload } from "@/components/ui/image-upload"
import { createSlider, updateSlider } from "@/app/(dashboard)/dashboard/sliders/actions"
const sliderSchema = z.object({
title: z.string().min(2, "Başlık en az 2 karakter olmalıdır"),
description: z.string().optional(),
image_url: z.string().min(1, "Görsel yüklemek zorunludur"),
link: z.string().optional(),
order: z.coerce.number().default(0),
is_active: z.boolean().default(true),
})
type SliderFormValues = z.infer<typeof sliderSchema>
interface Slider {
id: string
title: string
description: string | null
image_url: string
link: string | null
order: number | null
is_active: boolean | null
}
interface SliderFormProps {
initialData?: Slider
}
export function SliderForm({ initialData }: SliderFormProps) {
const router = useRouter()
const [loading, setLoading] = useState(false)
const form = useForm<SliderFormValues>({
resolver: zodResolver(sliderSchema),
defaultValues: initialData ? {
title: initialData.title,
description: initialData.description || "",
image_url: initialData.image_url,
link: initialData.link || "",
order: initialData.order || 0,
is_active: initialData.is_active ?? true,
} : {
title: "",
description: "",
image_url: "",
link: "",
order: 0,
is_active: true,
},
})
async function onSubmit(data: SliderFormValues) {
setLoading(true)
try {
let result
if (initialData) {
result = await updateSlider(initialData.id, data)
} else {
result = await createSlider(data)
}
if (result.error) {
toast.error(result.error)
return
}
toast.success(initialData ? "Slider güncellendi" : "Slider oluşturuldu")
router.push("/dashboard/sliders")
router.refresh()
} catch {
toast.error("Bir sorun oluştu.")
} finally {
setLoading(false)
}
}
return (
<Card>
<CardHeader>
<CardTitle>{initialData ? "Slider Düzenle" : "Yeni Slider Ekle"}</CardTitle>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="image_url"
render={({ field }) => (
<FormItem>
<FormLabel>Görsel</FormLabel>
<FormControl>
<ImageUpload
value={field.value}
onChange={field.onChange}
onRemove={() => field.onChange("")}
disabled={loading}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>Başlık</FormLabel>
<FormControl>
<Input placeholder="Örn: Yeni Sezon Modelleri" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="order"
render={({ field }) => (
<FormItem>
<FormLabel>Sıralama</FormLabel>
<FormControl>
<Input type="number" {...field} />
</FormControl>
<FormDescription>Düşük numara önce gösterilir (0, 1, 2...)</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>ıklama</FormLabel>
<FormControl>
<Textarea placeholder="Kısa açıklama metni..." {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="link"
render={({ field }) => (
<FormItem>
<FormLabel>Yönlendirme Linki (Opsiyonel)</FormLabel>
<FormControl>
<Input placeholder="/kategori/ev-tipi" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="is_active"
render={({ field }) => (
<FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel>
Aktif
</FormLabel>
<FormDescription>
Bu slider ana sayfada gösterilsin mi?
</FormDescription>
</div>
</FormItem>
)}
/>
<Button type="submit" disabled={loading} className="w-full sm:w-auto">
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{initialData ? "Kaydet" : "Oluştur"}
</Button>
</form>
</Form>
</CardContent>
</Card>
)
}

View File

@@ -0,0 +1,32 @@
"use client"
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { CheckIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@@ -0,0 +1,142 @@
"use client"
import { useState, useRef } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Loader2, Upload, X, Image as ImageIcon } from "lucide-react"
import imageCompression from "browser-image-compression"
import { createClient } from "@/lib/supabase-browser"
import { toast } from "sonner"
import Image from "next/image"
interface ImageUploadProps {
value?: string
onChange: (url: string) => void
onRemove: () => void
disabled?: boolean
}
export function ImageUpload({ value, onChange, onRemove, disabled }: ImageUploadProps) {
const [loading, setLoading] = useState(false)
const fileInputRef = useRef<HTMLInputElement>(null)
const supabase = createClient()
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (!file) return
setLoading(true)
try {
// 1. Client-side Compression
const options = {
maxSizeMB: 1, // Max 1MB
maxWidthOrHeight: 1920, // Max 1920px width/height
useWebWorker: true,
fileType: "image/webp" // Convert to WebP if possible
}
// Note: browser-image-compression might return Blob instead of File
const compressedFile = await imageCompression(file, options)
// Create a unique file name
// folder structure: sliders/[timestamp]-[random].webp
const fileExt = "webp" // we are forcing conversion to webp usually, or use compressedFile.type
const fileName = `${Date.now()}-${Math.floor(Math.random() * 1000)}.${fileExt}`
const filePath = `uploads/${fileName}`
// 2. Upload to Supabase
const { error: uploadError } = await supabase.storage
.from("images")
.upload(filePath, compressedFile)
if (uploadError) {
throw uploadError
}
// 3. Get Public URL
const { data: { publicUrl } } = supabase.storage
.from("images")
.getPublicUrl(filePath)
onChange(publicUrl)
toast.success("Resim yüklendi ve optimize edildi.")
} catch (error: any) {
console.error("Upload error:", error)
toast.error("Resim yüklenirken hata oluştu: " + error.message)
} finally {
setLoading(false)
if (fileInputRef.current) {
fileInputRef.current.value = ""
}
}
}
return (
<div className="space-y-4 w-full">
<Label>Görsel</Label>
{value ? (
<div className="relative aspect-video w-full max-w-md rounded-lg overflow-hidden border bg-slate-100 dark:bg-slate-800">
<Image
src={value}
alt="Upload preview"
fill
className="object-cover"
/>
<Button
type="button"
onClick={onRemove}
variant="destructive"
size="icon"
className="absolute top-2 right-2 h-8 w-8"
disabled={disabled}
>
<X className="h-4 w-4" />
</Button>
</div>
) : (
<div
onClick={() => fileInputRef.current?.click()}
className="
border-2 border-dashed border-slate-300 dark:border-slate-700
rounded-lg p-12
flex flex-col items-center justify-center
text-slate-500 dark:text-slate-400
hover:bg-slate-50 dark:hover:bg-slate-900/50
transition cursor-pointer
w-full max-w-md
"
>
<input
type="file"
accept="image/*"
className="hidden"
ref={fileInputRef}
onChange={handleFileChange}
disabled={loading || disabled}
/>
{loading ? (
<div className="flex flex-col items-center gap-2">
<Loader2 className="h-10 w-10 animate-spin text-primary" />
<p className="text-sm font-medium">Optimize ediliyor ve yükleniyor...</p>
</div>
) : (
<div className="flex flex-col items-center gap-2">
<div className="p-4 bg-slate-100 dark:bg-slate-800 rounded-full">
<Upload className="h-6 w-6" />
</div>
<p className="text-sm font-medium">Resim Yükle</p>
<p className="text-xs text-muted-foreground text-center">
Tıklayın veya sürükleyin.<br />
(Otomatik sıkıştırma: Max 1MB, WebP)
</p>
</div>
)}
</div>
)}
</div>
)
}