fix upload image trip
This commit is contained in:
@@ -12,7 +12,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { DateRangeField, TimeField } from "@/components/shared/date-picker";
|
||||
import { createTripAction } from "@/features/trip/actions";
|
||||
import { ImageUrlInput } from "@/features/trip/components/image-url-input";
|
||||
import { TripImageUpload } from "@/features/trip/components/trip-image-upload";
|
||||
import { formatLocalCalendarYmd } from "@/lib/trip-dates";
|
||||
import { ACTIVITY_CATEGORIES, categoryMeta } from "@/lib/activity-category";
|
||||
import { VIBES, vibeMeta } from "@/lib/vibe";
|
||||
@@ -61,7 +61,7 @@ const INITIAL_STATE: FormState = {
|
||||
itineraryDays: [],
|
||||
whatsIncluded: "",
|
||||
whatsExcluded: "",
|
||||
imageUrls: [""],
|
||||
imageUrls: [],
|
||||
maxParticipants: "",
|
||||
priceDisplay: "",
|
||||
};
|
||||
@@ -152,18 +152,11 @@ export function CreateTripForm({ isVerifiedOrganizer }: CreateTripFormProps) {
|
||||
return null;
|
||||
}
|
||||
if (target === 3) {
|
||||
const hasInvalidUrl = state.imageUrls
|
||||
.map((u) => u.trim())
|
||||
.filter(Boolean)
|
||||
.some((u) => {
|
||||
try {
|
||||
const parsed = new URL(u);
|
||||
return parsed.protocol !== "http:" && parsed.protocol !== "https:";
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
if (hasInvalidUrl) return "Ada URL foto yang tidak valid (harus http/https)";
|
||||
// Foto divalidasi saat upload (route + komponen). Di sini cukup cek
|
||||
// batas jumlah supaya tidak melampaui kapasitas.
|
||||
if (state.imageUrls.length > LIMITS.MAX_IMAGE_URLS) {
|
||||
return `Maksimal ${LIMITS.MAX_IMAGE_URLS} foto`;
|
||||
}
|
||||
|
||||
for (let d = 0; d < state.itineraryDays.length; d++) {
|
||||
const dayItems = state.itineraryDays[d];
|
||||
@@ -338,6 +331,7 @@ export function CreateTripForm({ isVerifiedOrganizer }: CreateTripFormProps) {
|
||||
whatsExcluded={state.whatsExcluded}
|
||||
imageUrls={state.imageUrls}
|
||||
onChange={update}
|
||||
onError={setStepError}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -698,6 +692,7 @@ function StepDetail({
|
||||
whatsExcluded,
|
||||
imageUrls,
|
||||
onChange,
|
||||
onError,
|
||||
}: {
|
||||
meetingPoint: string;
|
||||
itineraryDays: ItineraryDays;
|
||||
@@ -705,6 +700,7 @@ function StepDetail({
|
||||
whatsExcluded: string;
|
||||
imageUrls: string[];
|
||||
onChange: <K extends keyof FormState>(key: K, value: FormState[K]) => void;
|
||||
onError: (msg: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
@@ -777,9 +773,10 @@ function StepDetail({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ImageUrlInput
|
||||
<TripImageUpload
|
||||
value={imageUrls}
|
||||
onChange={(urls) => onChange("imageUrls", urls)}
|
||||
onError={onError}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import { useState } from "react";
|
||||
import { Mountain } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Mountain, Maximize2, X, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
|
||||
interface TripImage {
|
||||
id: string;
|
||||
@@ -12,6 +12,38 @@ interface TripImage {
|
||||
|
||||
export function ImageGallery({ images }: { images: TripImage[] }) {
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const [lightboxOpen, setLightboxOpen] = useState(false);
|
||||
const hasMultiple = images.length > 1;
|
||||
|
||||
function showPrev() {
|
||||
setActiveIndex((i) => (i - 1 + images.length) % images.length);
|
||||
}
|
||||
function showNext() {
|
||||
setActiveIndex((i) => (i + 1) % images.length);
|
||||
}
|
||||
|
||||
// Saat lightbox terbuka: kunci scroll body + dukung keyboard (Esc tutup,
|
||||
// panah kiri/kanan untuk ganti foto).
|
||||
useEffect(() => {
|
||||
if (!lightboxOpen) return;
|
||||
function onKey(e: KeyboardEvent) {
|
||||
// Logika prev/next di-inline (bukan panggil showPrev/showNext) supaya
|
||||
// effect tidak bergantung pada fungsi yang dibuat ulang tiap render.
|
||||
if (e.key === "Escape") setLightboxOpen(false);
|
||||
else if (e.key === "ArrowLeft") {
|
||||
setActiveIndex((i) => (i - 1 + images.length) % images.length);
|
||||
} else if (e.key === "ArrowRight") {
|
||||
setActiveIndex((i) => (i + 1) % images.length);
|
||||
}
|
||||
}
|
||||
document.addEventListener("keydown", onKey);
|
||||
const prevOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = "hidden";
|
||||
return () => {
|
||||
document.removeEventListener("keydown", onKey);
|
||||
document.body.style.overflow = prevOverflow;
|
||||
};
|
||||
}, [lightboxOpen, images.length]);
|
||||
|
||||
if (images.length === 0) {
|
||||
return (
|
||||
@@ -30,18 +62,25 @@ export function ImageGallery({ images }: { images: TripImage[] }) {
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Main Image */}
|
||||
<div className="relative h-44 bg-neutral-900 sm:h-56 lg:h-72">
|
||||
{/* Main Image — klik untuk lihat ukuran penuh */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLightboxOpen(true)}
|
||||
aria-label="Lihat foto ukuran penuh"
|
||||
className="group relative block h-44 w-full cursor-zoom-in bg-neutral-900 sm:h-56 lg:h-72"
|
||||
>
|
||||
<Image
|
||||
src={activeImage.url}
|
||||
alt={activeImage.caption || "Foto trip"}
|
||||
fill
|
||||
className="object-cover"
|
||||
// `object-contain` — tampilkan gambar utuh tanpa terpotong; rasio
|
||||
// foto bebas, sisi yang tak terisi jadi bar gelap (bg-neutral-900).
|
||||
className="object-contain"
|
||||
sizes="(max-width: 768px) 100vw, 768px"
|
||||
priority
|
||||
/>
|
||||
{activeImage.caption && (
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-linear-to-t from-black/60 to-transparent px-3 pb-2.5 pt-6 sm:px-4 sm:pb-3 sm:pt-8">
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-linear-to-t from-black/60 to-transparent px-3 pb-2.5 pt-6 text-left sm:px-4 sm:pb-3 sm:pt-8">
|
||||
<p className="text-xs font-medium text-white sm:text-sm">
|
||||
{activeImage.caption}
|
||||
</p>
|
||||
@@ -51,14 +90,20 @@ export function ImageGallery({ images }: { images: TripImage[] }) {
|
||||
<div className="absolute right-2 top-2 rounded-full bg-black/50 px-2 py-0.5 text-[10px] font-medium text-white backdrop-blur-sm sm:right-3 sm:top-3 sm:px-2.5 sm:py-1 sm:text-xs">
|
||||
{activeIndex + 1} / {images.length}
|
||||
</div>
|
||||
</div>
|
||||
{/* Petunjuk perbesar */}
|
||||
<span className="absolute left-2 top-2 inline-flex items-center gap-1 rounded-full bg-black/50 px-2 py-0.5 text-[10px] font-medium text-white backdrop-blur-sm transition-colors group-hover:bg-black/70 sm:left-3 sm:top-3 sm:px-2.5 sm:py-1 sm:text-xs">
|
||||
<Maximize2 size={11} strokeWidth={2} aria-hidden />
|
||||
Lihat penuh
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{/* Thumbnails */}
|
||||
{images.length > 1 && (
|
||||
{hasMultiple && (
|
||||
<div className="flex gap-1 overflow-x-auto bg-neutral-100 p-1.5 sm:gap-1.5 sm:p-2">
|
||||
{images.map((img, i) => (
|
||||
<button
|
||||
key={img.id}
|
||||
type="button"
|
||||
onClick={() => setActiveIndex(i)}
|
||||
className={`relative h-11 w-16 shrink-0 overflow-hidden rounded-md transition-all sm:h-14 sm:w-20 sm:rounded-lg ${
|
||||
i === activeIndex
|
||||
@@ -77,6 +122,111 @@ export function ImageGallery({ images }: { images: TripImage[] }) {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Lightbox — penampil foto ukuran penuh */}
|
||||
{lightboxOpen && (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Penampil foto trip"
|
||||
className="fixed inset-0 z-50 flex flex-col bg-black/95"
|
||||
>
|
||||
{/* Top bar */}
|
||||
<div className="flex items-center justify-between px-4 py-3 text-white">
|
||||
<span className="text-sm font-medium tabular-nums">
|
||||
{activeIndex + 1} / {images.length}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLightboxOpen(false)}
|
||||
aria-label="Tutup"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-white/10 transition-colors hover:bg-white/20"
|
||||
>
|
||||
<X size={20} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Area gambar — klik latar untuk menutup */}
|
||||
<div
|
||||
className="relative flex-1"
|
||||
onClick={() => setLightboxOpen(false)}
|
||||
>
|
||||
<div
|
||||
className="relative h-full w-full"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Image
|
||||
src={activeImage.url}
|
||||
alt={activeImage.caption || "Foto trip"}
|
||||
fill
|
||||
className="object-contain"
|
||||
sizes="100vw"
|
||||
quality={90}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{hasMultiple && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
showPrev();
|
||||
}}
|
||||
aria-label="Foto sebelumnya"
|
||||
className="absolute left-2 top-1/2 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/25 sm:left-4"
|
||||
>
|
||||
<ChevronLeft size={24} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
showNext();
|
||||
}}
|
||||
aria-label="Foto berikutnya"
|
||||
className="absolute right-2 top-1/2 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/25 sm:right-4"
|
||||
>
|
||||
<ChevronRight size={24} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{activeImage.caption && (
|
||||
<p className="px-4 py-3 text-center text-sm text-white/80">
|
||||
{activeImage.caption}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Thumbnail strip di dalam lightbox */}
|
||||
{hasMultiple && (
|
||||
<div className="flex justify-center gap-1.5 overflow-x-auto px-4 pb-4">
|
||||
{images.map((img, i) => (
|
||||
<button
|
||||
key={img.id}
|
||||
type="button"
|
||||
onClick={() => setActiveIndex(i)}
|
||||
aria-label={`Lihat foto ${i + 1}`}
|
||||
className={`relative h-12 w-16 shrink-0 overflow-hidden rounded-md transition-all ${
|
||||
i === activeIndex
|
||||
? "ring-2 ring-primary-400 ring-offset-1 ring-offset-black"
|
||||
: "opacity-50 hover:opacity-100"
|
||||
}`}
|
||||
>
|
||||
<Image
|
||||
src={img.url}
|
||||
alt=""
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="64px"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Plus, X } from "lucide-react";
|
||||
import { LIMITS } from "@/lib/limits";
|
||||
|
||||
interface ImageUrlInputProps {
|
||||
value: string[];
|
||||
onChange: (urls: string[]) => void;
|
||||
}
|
||||
|
||||
export function ImageUrlInput({ value, onChange }: ImageUrlInputProps) {
|
||||
const urls = value.length > 0 ? value : [""];
|
||||
const max = LIMITS.MAX_IMAGE_URLS;
|
||||
|
||||
function addField() {
|
||||
if (urls.length < max) {
|
||||
onChange([...urls, ""]);
|
||||
}
|
||||
}
|
||||
|
||||
function removeField(index: number) {
|
||||
const next = urls.filter((_, i) => i !== index);
|
||||
onChange(next.length > 0 ? next : [""]);
|
||||
}
|
||||
|
||||
function updateField(index: number, next: string) {
|
||||
const updated = [...urls];
|
||||
updated[index] = next;
|
||||
onChange(updated);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label className="mb-2 flex items-center justify-between">
|
||||
<span className="text-sm font-semibold text-neutral-700">
|
||||
Foto Trip (URL)
|
||||
</span>
|
||||
<span className="text-xs text-neutral-400">
|
||||
{urls.length}/{max}
|
||||
</span>
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
{urls.map((url, i) => (
|
||||
<div key={i} className="flex gap-2">
|
||||
<input
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={(e) => updateField(i, e.target.value)}
|
||||
className="flex-1 rounded-xl border border-neutral-200 bg-neutral-50 px-4 py-2.5 text-sm text-neutral-800 placeholder:text-neutral-400 focus:bg-white"
|
||||
placeholder={
|
||||
i === 0
|
||||
? "URL foto utama (cover)"
|
||||
: `URL foto ${i + 1} (opsional)`
|
||||
}
|
||||
/>
|
||||
{urls.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeField(i)}
|
||||
aria-label={`Hapus foto ${i + 1}`}
|
||||
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-neutral-200 text-neutral-400 hover:bg-red-50 hover:text-red-500"
|
||||
>
|
||||
<X size={16} strokeWidth={2} aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{urls.length < max && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={addField}
|
||||
className="mt-2 flex items-center gap-1 rounded-lg px-2 py-1 text-sm font-medium text-secondary-600 hover:bg-secondary-50"
|
||||
>
|
||||
<Plus size={15} strokeWidth={2} aria-hidden />
|
||||
Tambah foto
|
||||
</button>
|
||||
)}
|
||||
<p className="mt-1.5 text-xs text-neutral-400">
|
||||
Upload foto ke hosting (imgur, imgbb, dll) lalu paste URL-nya di sini.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import Image from "next/image";
|
||||
import { ImagePlus, X, Loader2 } from "lucide-react";
|
||||
import { LIMITS } from "@/lib/limits";
|
||||
|
||||
interface TripImageUploadProps {
|
||||
/** URL gambar yang sudah terunggah (path `/api/trip-images/...`). */
|
||||
value: string[];
|
||||
onChange: (urls: string[]) => void;
|
||||
/** Lapor error ke form (mis. file terlalu besar / gagal upload). */
|
||||
onError?: (msg: string) => void;
|
||||
}
|
||||
|
||||
const ACCEPT_MIME = "image/jpeg,image/png,image/webp";
|
||||
/** Sinkron dengan MAX_TRIP_IMAGE_UPLOAD_BYTES di lib/trip-image-storage.ts. */
|
||||
const MAX_BYTES = 12 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Pengganti input URL foto: user memilih file dari perangkatnya, tiap file
|
||||
* langsung di-upload & dikompres server-side. Form hanya menyimpan URL hasil.
|
||||
*/
|
||||
export function TripImageUpload({
|
||||
value,
|
||||
onChange,
|
||||
onError,
|
||||
}: TripImageUploadProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [uploadingCount, setUploadingCount] = useState(0);
|
||||
const max = LIMITS.MAX_IMAGE_URLS;
|
||||
const usedSlots = value.length + uploadingCount;
|
||||
const remaining = max - usedSlots;
|
||||
|
||||
async function uploadOne(file: File): Promise<string | null> {
|
||||
if (!ACCEPT_MIME.split(",").includes(file.type)) {
|
||||
onError?.(`"${file.name}" harus JPG, PNG, atau WebP`);
|
||||
return null;
|
||||
}
|
||||
if (file.size > MAX_BYTES) {
|
||||
onError?.(`"${file.name}" melebihi 12MB`);
|
||||
return null;
|
||||
}
|
||||
const fd = new FormData();
|
||||
fd.set("file", file);
|
||||
try {
|
||||
const res = await fetch("/api/upload/trip-image", {
|
||||
method: "POST",
|
||||
body: fd,
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok) {
|
||||
onError?.(json.error ?? `Gagal mengunggah "${file.name}"`);
|
||||
return null;
|
||||
}
|
||||
return json.url as string;
|
||||
} catch {
|
||||
onError?.(`Gagal mengunggah "${file.name}"`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePick(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const files = Array.from(e.target.files ?? []);
|
||||
e.target.value = "";
|
||||
if (files.length === 0) return;
|
||||
|
||||
if (remaining <= 0) {
|
||||
onError?.(`Maksimal ${max} foto`);
|
||||
return;
|
||||
}
|
||||
const picked = files.slice(0, remaining);
|
||||
if (files.length > remaining) {
|
||||
onError?.(`Hanya ${remaining} foto pertama diunggah (maks ${max})`);
|
||||
}
|
||||
|
||||
setUploadingCount((c) => c + picked.length);
|
||||
// `value` di-snapshot saat handler dibuat; upload sekuensial supaya urutan
|
||||
// foto stabil, lalu hasil yang berhasil ditambahkan sekali di akhir.
|
||||
const uploaded: string[] = [];
|
||||
for (const file of picked) {
|
||||
const url = await uploadOne(file);
|
||||
setUploadingCount((c) => c - 1);
|
||||
if (url) uploaded.push(url);
|
||||
}
|
||||
if (uploaded.length > 0) onChange([...value, ...uploaded]);
|
||||
}
|
||||
|
||||
function removeAt(index: number) {
|
||||
onChange(value.filter((_, i) => i !== index));
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label className="mb-2 flex items-center justify-between">
|
||||
<span className="text-sm font-semibold text-neutral-700">
|
||||
Foto Trip
|
||||
</span>
|
||||
<span className="text-xs text-neutral-400">
|
||||
{value.length}/{max}
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
|
||||
{value.map((url, i) => (
|
||||
<div
|
||||
key={url}
|
||||
className="group relative aspect-square overflow-hidden rounded-xl border border-neutral-200 bg-neutral-100"
|
||||
>
|
||||
<Image
|
||||
src={url}
|
||||
alt={i === 0 ? "Foto cover" : `Foto ${i + 1}`}
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="(max-width: 640px) 33vw, 160px"
|
||||
/>
|
||||
{i === 0 && (
|
||||
<span className="absolute left-1 top-1 rounded-md bg-primary-600/90 px-1.5 py-0.5 text-[10px] font-bold text-white">
|
||||
Cover
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeAt(i)}
|
||||
aria-label={`Hapus foto ${i + 1}`}
|
||||
className="absolute right-1 top-1 flex h-6 w-6 items-center justify-center rounded-full bg-black/55 text-white transition-colors hover:bg-red-600"
|
||||
>
|
||||
<X size={13} strokeWidth={2.5} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{Array.from({ length: uploadingCount }).map((_, i) => (
|
||||
<div
|
||||
key={`uploading-${i}`}
|
||||
className="flex aspect-square items-center justify-center rounded-xl border border-dashed border-neutral-300 bg-neutral-50"
|
||||
>
|
||||
<Loader2
|
||||
size={20}
|
||||
strokeWidth={2}
|
||||
aria-hidden
|
||||
className="animate-spin text-neutral-400"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{remaining > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className="flex aspect-square flex-col items-center justify-center gap-1 rounded-xl border border-dashed border-neutral-300 bg-neutral-50/60 text-neutral-500 transition-colors hover:border-primary-400 hover:text-primary-600"
|
||||
>
|
||||
<ImagePlus size={20} strokeWidth={1.75} aria-hidden />
|
||||
<span className="text-[11px] font-semibold">Tambah</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={ACCEPT_MIME}
|
||||
multiple
|
||||
onChange={handlePick}
|
||||
className="sr-only"
|
||||
/>
|
||||
|
||||
<p className="mt-1.5 text-xs text-neutral-400">
|
||||
Unggah langsung dari galeri/kamera — JPG, PNG, atau WebP, maks 12MB per
|
||||
foto. Foto pertama jadi cover. Gambar besar otomatis dikompres tanpa
|
||||
mengorbankan kualitas.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user