it worked
This commit is contained in:
86
frontend/app/api/upload-image/route.ts
Normal file
86
frontend/app/api/upload-image/route.ts
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
|
||||||
|
const R2_WORKER = process.env.UPLOAD_R2_WORKER_API;
|
||||||
|
const R2_API_KEY = process.env.R2_UPLOAD_API_KEY;
|
||||||
|
|
||||||
|
export interface UploadImageResponse {
|
||||||
|
success: true;
|
||||||
|
url: string;
|
||||||
|
key: string;
|
||||||
|
contentType: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/upload-image
|
||||||
|
*
|
||||||
|
* Accepts a multipart/form-data body with a single "file" field.
|
||||||
|
* Proxies the binary to the Cloudflare R2 worker using the server-side API key
|
||||||
|
* (the key is never exposed to the browser).
|
||||||
|
*
|
||||||
|
* Returns: { success, url, key, contentType }
|
||||||
|
*/
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
console.log(R2_WORKER);
|
||||||
|
console.log(R2_API_KEY);
|
||||||
|
if (!R2_WORKER || !R2_API_KEY) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "R2 upload is not configured. Set UPLOAD_R2_WORKER_API and R2_UPLOAD_API_KEY." },
|
||||||
|
{ status: 503 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const formData = await req.formData();
|
||||||
|
const file = formData.get("file");
|
||||||
|
|
||||||
|
if (!file || !(file instanceof File)) {
|
||||||
|
return NextResponse.json({ error: "No file provided" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file type
|
||||||
|
const allowedTypes = ["image/jpeg", "image/png", "image/gif", "image/webp", "image/svg+xml", "image/avif"];
|
||||||
|
if (!allowedTypes.includes(file.type)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Unsupported file type: ${file.type}. Allowed: JPEG, PNG, GIF, WebP, SVG, AVIF.` },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file size (max 10 MB)
|
||||||
|
const MAX_BYTES = 10 * 1024 * 1024;
|
||||||
|
if (file.size > MAX_BYTES) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `File is too large (${(file.size / 1024 / 1024).toFixed(1)} MB). Maximum is 10 MB.` },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send binary to R2 worker
|
||||||
|
const arrayBuffer = await file.arrayBuffer();
|
||||||
|
const r2Res = await fetch(`${R2_WORKER}/upload`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"X-Api-Key": R2_API_KEY,
|
||||||
|
"Content-Type": file.type,
|
||||||
|
},
|
||||||
|
body: arrayBuffer,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!r2Res.ok) {
|
||||||
|
let errMsg = `R2 worker error ${r2Res.status}`;
|
||||||
|
try {
|
||||||
|
const body = await r2Res.json();
|
||||||
|
errMsg = body?.error || body?.message || errMsg;
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return NextResponse.json({ error: errMsg }, { status: 502 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = (await r2Res.json()) as UploadImageResponse;
|
||||||
|
return NextResponse.json(data);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[upload-image] Unexpected error:", err);
|
||||||
|
return NextResponse.json({ error: "Upload failed" }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
|
import { ImageUploader } from "@/components/dashboard/image-uploader";
|
||||||
import { Loader2, PlusCircle } from "lucide-react";
|
import { Loader2, PlusCircle } from "lucide-react";
|
||||||
import { PostStatus, ContentFormat, UserRole } from "@/lib/types";
|
import { PostStatus, ContentFormat, UserRole } from "@/lib/types";
|
||||||
|
|
||||||
@@ -30,6 +31,10 @@ export function CreatePostForm({ userRole, onCreated }: Props) {
|
|||||||
);
|
);
|
||||||
const [isFeatured, setIsFeatured] = useState("false");
|
const [isFeatured, setIsFeatured] = useState("false");
|
||||||
|
|
||||||
|
// Controlled image state (ImageUploader is not a native input element)
|
||||||
|
const [featuredImageUrl, setFeaturedImageUrl] = useState("");
|
||||||
|
const [featuredImageAlt, setFeaturedImageAlt] = useState("");
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const fd = new FormData(e.currentTarget);
|
const fd = new FormData(e.currentTarget);
|
||||||
@@ -43,8 +48,9 @@ export function CreatePostForm({ userRole, onCreated }: Props) {
|
|||||||
isFeatured: isFeatured === "true",
|
isFeatured: isFeatured === "true",
|
||||||
categories: fd.get("categories") || undefined,
|
categories: fd.get("categories") || undefined,
|
||||||
tags: fd.get("tags") || undefined,
|
tags: fd.get("tags") || undefined,
|
||||||
featuredImageUrl: fd.get("featuredImageUrl") || undefined,
|
// image values come from controlled state, not FormData
|
||||||
featuredImageAlt: fd.get("featuredImageAlt") || undefined,
|
featuredImageUrl: featuredImageUrl || undefined,
|
||||||
|
featuredImageAlt: featuredImageAlt || undefined,
|
||||||
};
|
};
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -55,6 +61,9 @@ export function CreatePostForm({ userRole, onCreated }: Props) {
|
|||||||
});
|
});
|
||||||
toast.success("Post created!");
|
toast.success("Post created!");
|
||||||
(e.target as HTMLFormElement).reset();
|
(e.target as HTMLFormElement).reset();
|
||||||
|
// Reset controlled image state
|
||||||
|
setFeaturedImageUrl("");
|
||||||
|
setFeaturedImageAlt("");
|
||||||
onCreated();
|
onCreated();
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
toast.error(err instanceof Error ? err.message : "Failed to create post");
|
toast.error(err instanceof Error ? err.message : "Failed to create post");
|
||||||
@@ -174,20 +183,14 @@ export function CreatePostForm({ userRole, onCreated }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-3 sm:grid-cols-2">
|
{/* ── Featured image upload ─────────────────────────────────────────── */}
|
||||||
<div className="space-y-1">
|
<ImageUploader
|
||||||
<Label htmlFor="cp-imgurl">Featured Image URL</Label>
|
value={featuredImageUrl}
|
||||||
<Input
|
onChange={setFeaturedImageUrl}
|
||||||
id="cp-imgurl"
|
altValue={featuredImageAlt}
|
||||||
name="featuredImageUrl"
|
onAltChange={setFeaturedImageAlt}
|
||||||
placeholder="https://…"
|
label="Featured Image"
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
<div className="space-y-1">
|
|
||||||
<Label htmlFor="cp-imgalt">Image Alt Text</Label>
|
|
||||||
<Input id="cp-imgalt" name="featuredImageAlt" placeholder="Alt text" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end">
|
<div className="flex justify-end">
|
||||||
<Button type="submit" disabled={loading}>
|
<Button type="submit" disabled={loading}>
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import { CreatePostForm } from "./create-post-form";
|
|||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
@@ -28,6 +27,7 @@ import {
|
|||||||
AlertDialogTitle,
|
AlertDialogTitle,
|
||||||
AlertDialogTrigger,
|
AlertDialogTrigger,
|
||||||
} from "@/components/ui/alert-dialog";
|
} from "@/components/ui/alert-dialog";
|
||||||
|
import { ImageUploader } from "@/components/dashboard/image-uploader";
|
||||||
import { Eye, Loader2, Pencil, Trash2, X, Check, ExternalLink } from "lucide-react";
|
import { Eye, Loader2, Pencil, Trash2, X, Check, ExternalLink } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
|
||||||
@@ -36,9 +36,16 @@ interface Props {
|
|||||||
userRole: UserRole;
|
userRole: UserRole;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Per-post edit image state so each inline form has its own uploader values. */
|
||||||
|
interface EditImageState {
|
||||||
|
url: string;
|
||||||
|
alt: string;
|
||||||
|
}
|
||||||
|
|
||||||
export function PostsTable({ initialPosts, userRole }: Props) {
|
export function PostsTable({ initialPosts, userRole }: Props) {
|
||||||
const [posts, setPosts] = useState<BlogPost[]>(initialPosts);
|
const [posts, setPosts] = useState<BlogPost[]>(initialPosts);
|
||||||
const [editingId, setEditingId] = useState<string | null>(null);
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
|
const [editImage, setEditImage] = useState<EditImageState>({ url: "", alt: "" });
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
const refreshPosts = useCallback(async () => {
|
const refreshPosts = useCallback(async () => {
|
||||||
@@ -52,6 +59,14 @@ export function PostsTable({ initialPosts, userRole }: Props) {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const startEditing = (post: BlogPost) => {
|
||||||
|
setEditingId(post.id);
|
||||||
|
setEditImage({
|
||||||
|
url: post.featuredImageUrl || "",
|
||||||
|
alt: post.featuredImageAlt || "",
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const handleDelete = async (id: string) => {
|
const handleDelete = async (id: string) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
@@ -81,8 +96,9 @@ export function PostsTable({ initialPosts, userRole }: Props) {
|
|||||||
isFeatured: fd.get("isFeatured") === "true",
|
isFeatured: fd.get("isFeatured") === "true",
|
||||||
categories: fd.get("categories") || undefined,
|
categories: fd.get("categories") || undefined,
|
||||||
tags: fd.get("tags") || undefined,
|
tags: fd.get("tags") || undefined,
|
||||||
featuredImageUrl: fd.get("featuredImageUrl") || undefined,
|
// Image comes from controlled ImageUploader state
|
||||||
featuredImageAlt: fd.get("featuredImageAlt") || undefined,
|
featuredImageUrl: editImage.url || undefined,
|
||||||
|
featuredImageAlt: editImage.alt || undefined,
|
||||||
};
|
};
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
@@ -179,10 +195,15 @@ export function PostsTable({ initialPosts, userRole }: Props) {
|
|||||||
<Input name="categories" defaultValue={post.categories.join(",")} placeholder="Categories" />
|
<Input name="categories" defaultValue={post.categories.join(",")} placeholder="Categories" />
|
||||||
<Input name="tags" defaultValue={post.tags.join(",")} placeholder="Tags" />
|
<Input name="tags" defaultValue={post.tags.join(",")} placeholder="Tags" />
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-2 sm:grid-cols-2">
|
|
||||||
<Input name="featuredImageUrl" defaultValue={post.featuredImageUrl || ""} placeholder="Image URL" />
|
{/* ── Image upload (replaces the old URL text inputs) ── */}
|
||||||
<Input name="featuredImageAlt" defaultValue={post.featuredImageAlt || ""} placeholder="Image Alt" />
|
<ImageUploader
|
||||||
</div>
|
value={editImage.url}
|
||||||
|
onChange={(url) => setEditImage((prev) => ({ ...prev, url }))}
|
||||||
|
altValue={editImage.alt}
|
||||||
|
onAltChange={(alt) => setEditImage((prev) => ({ ...prev, alt }))}
|
||||||
|
label="Featured Image"
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="flex gap-2 justify-end">
|
<div className="flex gap-2 justify-end">
|
||||||
<Button type="button" variant="ghost" onClick={() => setEditingId(null)}>
|
<Button type="button" variant="ghost" onClick={() => setEditingId(null)}>
|
||||||
@@ -197,7 +218,7 @@ export function PostsTable({ initialPosts, userRole }: Props) {
|
|||||||
) : (
|
) : (
|
||||||
/* ── Post card view ─────────────────────────────────────── */
|
/* ── Post card view ─────────────────────────────────────── */
|
||||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||||
<div className="space-y-1 min-w-0">
|
<div className="space-y-1 min-w-0 flex-1">
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
<Link
|
<Link
|
||||||
href={`/blog/${post.slug}`}
|
href={`/blog/${post.slug}`}
|
||||||
@@ -240,6 +261,16 @@ export function PostsTable({ initialPosts, userRole }: Props) {
|
|||||||
<Badge key={t} variant="outline" className="text-xs">#{t}</Badge>
|
<Badge key={t} variant="outline" className="text-xs">#{t}</Badge>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Thumbnail if image exists */}
|
||||||
|
{post.featuredImageUrl && (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<img
|
||||||
|
src={post.featuredImageUrl}
|
||||||
|
alt={post.featuredImageAlt || ""}
|
||||||
|
className="mt-2 h-16 w-28 rounded-md object-cover border"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Actions */}
|
{/* Actions */}
|
||||||
@@ -249,7 +280,7 @@ export function PostsTable({ initialPosts, userRole }: Props) {
|
|||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setEditingId(post.id)}
|
onClick={() => startEditing(post)}
|
||||||
>
|
>
|
||||||
<Pencil className="h-4 w-4" />
|
<Pencil className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
203
frontend/components/dashboard/image-uploader.tsx
Normal file
203
frontend/components/dashboard/image-uploader.tsx
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useRef, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Loader2, Upload, X, ImageIcon } from "lucide-react";
|
||||||
|
import type { UploadImageResponse } from "@/app/api/upload-image/route";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
/** Current image URL (controlled) */
|
||||||
|
value?: string;
|
||||||
|
/** Called when a new image URL is ready (after upload) or cleared (empty string) */
|
||||||
|
onChange: (url: string) => void;
|
||||||
|
/** Alt text value */
|
||||||
|
altValue?: string;
|
||||||
|
/** Called when alt text changes */
|
||||||
|
onAltChange?: (alt: string) => void;
|
||||||
|
/** Label shown above the dropzone */
|
||||||
|
label?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ACCEPTED = "image/jpeg,image/png,image/gif,image/webp,image/svg+xml,image/avif";
|
||||||
|
|
||||||
|
export function ImageUploader({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
altValue = "",
|
||||||
|
onAltChange,
|
||||||
|
label = "Featured Image",
|
||||||
|
}: Props) {
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [dragOver, setDragOver] = useState(false);
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const uploadFile = useCallback(
|
||||||
|
async (file: File) => {
|
||||||
|
setUploading(true);
|
||||||
|
try {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append("file", file);
|
||||||
|
|
||||||
|
const res = await fetch("/api/upload-image", {
|
||||||
|
method: "POST",
|
||||||
|
body: fd,
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = (await res.json()) as UploadImageResponse & { error?: string };
|
||||||
|
|
||||||
|
if (!res.ok || !data.success) {
|
||||||
|
throw new Error(data.error || "Upload failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
onChange(data.url);
|
||||||
|
toast.success("Image uploaded successfully!");
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "Upload failed");
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[onChange]
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── Drag & Drop handlers ───────────────────────────────────────────────────
|
||||||
|
const handleDragOver = (e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDragLeave = () => setDragOver(false);
|
||||||
|
|
||||||
|
const handleDrop = (e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(false);
|
||||||
|
const file = e.dataTransfer.files[0];
|
||||||
|
if (file) uploadFile(file);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── File input change ──────────────────────────────────────────────────────
|
||||||
|
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (file) {
|
||||||
|
uploadFile(file);
|
||||||
|
// Reset so the same file can be re-selected if removed
|
||||||
|
e.target.value = "";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemove = () => {
|
||||||
|
onChange("");
|
||||||
|
onAltChange?.("");
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>{label}</Label>
|
||||||
|
|
||||||
|
{value ? (
|
||||||
|
/* ── Preview ──────────────────────────────────────────────────────── */
|
||||||
|
<div className="relative rounded-xl overflow-hidden border bg-muted">
|
||||||
|
{/* Plain <img> — domain is dynamic (R2/custom), avoids next/image remotePatterns config */}
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img
|
||||||
|
src={value}
|
||||||
|
alt={altValue || "Featured image preview"}
|
||||||
|
className="aspect-video w-full object-cover"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Overlay — Replace / Remove actions */}
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center gap-2 bg-black/40 opacity-0 hover:opacity-100 transition-opacity">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="secondary"
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
disabled={uploading}
|
||||||
|
>
|
||||||
|
{uploading ? (
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Upload className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
<span className="ml-1.5">Replace</span>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="destructive"
|
||||||
|
onClick={handleRemove}
|
||||||
|
disabled={uploading}
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
<span className="ml-1.5">Remove</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{uploading && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center bg-black/50">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-white" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
/* ── Dropzone ─────────────────────────────────────────────────────── */
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
onDragOver={handleDragOver}
|
||||||
|
onDragLeave={handleDragLeave}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
disabled={uploading}
|
||||||
|
className={`
|
||||||
|
w-full rounded-xl border-2 border-dashed p-8
|
||||||
|
flex flex-col items-center justify-center gap-2
|
||||||
|
text-sm text-muted-foreground transition-colors cursor-pointer
|
||||||
|
hover:border-primary/50 hover:bg-muted/40
|
||||||
|
focus:outline-none focus-visible:ring-2 focus-visible:ring-ring
|
||||||
|
disabled:cursor-not-allowed disabled:opacity-60
|
||||||
|
${dragOver ? "border-primary bg-primary/5" : "border-border"}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
{uploading ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||||
|
<span>Uploading…</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<ImageIcon className="h-8 w-8 opacity-40" />
|
||||||
|
<span className="font-medium">
|
||||||
|
{dragOver ? "Drop to upload" : "Click or drag an image here"}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs opacity-70">
|
||||||
|
JPEG · PNG · GIF · WebP · SVG · AVIF — max 10 MB
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Hidden file input */}
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept={ACCEPTED}
|
||||||
|
className="hidden"
|
||||||
|
onChange={handleFileChange}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Alt text field — always shown */}
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label className="text-xs text-muted-foreground">Image alt text</Label>
|
||||||
|
<Input
|
||||||
|
placeholder="Describe the image for accessibility…"
|
||||||
|
value={altValue}
|
||||||
|
onChange={(e) => onAltChange?.(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,6 +4,15 @@
|
|||||||
|
|
||||||
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
|
||||||
|
|
||||||
|
const STATE_CHANGING_METHODS = ["POST", "PATCH", "PUT", "DELETE"];
|
||||||
|
|
||||||
|
// ─── Read csrfToken cookie in the browser ─────────────────────────────────────
|
||||||
|
function getClientCsrfToken(): string {
|
||||||
|
if (typeof document === "undefined") return "";
|
||||||
|
const match = document.cookie.match(/(?:^|;\s*)csrfToken=([^;]+)/);
|
||||||
|
return match ? decodeURIComponent(match[1]) : "";
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Server-side fetch (use in Server Components / Route Handlers) ─────────────
|
// ─── Server-side fetch (use in Server Components / Route Handlers) ─────────────
|
||||||
|
|
||||||
export async function apiFetch<T = unknown>(
|
export async function apiFetch<T = unknown>(
|
||||||
@@ -13,6 +22,7 @@ export async function apiFetch<T = unknown>(
|
|||||||
// Dynamic import so this module can also be imported in client components
|
// Dynamic import so this module can also be imported in client components
|
||||||
// The `cookies` call only runs on the server side
|
// The `cookies` call only runs on the server side
|
||||||
let cookieHeader = "";
|
let cookieHeader = "";
|
||||||
|
let csrfToken = "";
|
||||||
try {
|
try {
|
||||||
const { cookies } = await import("next/headers");
|
const { cookies } = await import("next/headers");
|
||||||
const store = await cookies();
|
const store = await cookies();
|
||||||
@@ -20,16 +30,22 @@ export async function apiFetch<T = unknown>(
|
|||||||
.getAll()
|
.getAll()
|
||||||
.map((c) => `${c.name}=${c.value}`)
|
.map((c) => `${c.name}=${c.value}`)
|
||||||
.join("; ");
|
.join("; ");
|
||||||
|
// Forward the CSRF token from the cookie store for mutating server-side calls
|
||||||
|
csrfToken = store.get("csrfToken")?.value ?? "";
|
||||||
} catch {
|
} catch {
|
||||||
// We're on the client — skip cookie forwarding
|
// We're on the client — skip cookie forwarding
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const method = (init?.method ?? "GET").toUpperCase();
|
||||||
|
const needsCsrf = STATE_CHANGING_METHODS.includes(method);
|
||||||
|
|
||||||
const res = await fetch(`${API_URL}${path}`, {
|
const res = await fetch(`${API_URL}${path}`, {
|
||||||
...init,
|
...init,
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
...(cookieHeader ? { Cookie: cookieHeader } : {}),
|
...(cookieHeader ? { Cookie: cookieHeader } : {}),
|
||||||
|
...(needsCsrf && csrfToken ? { "x-csrf-token": csrfToken } : {}),
|
||||||
...(init?.headers as Record<string, string> | undefined),
|
...(init?.headers as Record<string, string> | undefined),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -57,11 +73,16 @@ export async function clientFetch<T = unknown>(
|
|||||||
path: string,
|
path: string,
|
||||||
init?: RequestInit
|
init?: RequestInit
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
|
const method = (init?.method ?? "GET").toUpperCase();
|
||||||
|
const needsCsrf = STATE_CHANGING_METHODS.includes(method);
|
||||||
|
const csrfToken = needsCsrf ? getClientCsrfToken() : "";
|
||||||
|
|
||||||
const res = await fetch(`${API_URL}${path}`, {
|
const res = await fetch(`${API_URL}${path}`, {
|
||||||
...init,
|
...init,
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
|
...(needsCsrf && csrfToken ? { "x-csrf-token": csrfToken } : {}),
|
||||||
...(init?.headers as Record<string, string> | undefined),
|
...(init?.headers as Record<string, string> | undefined),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,16 +6,7 @@ const nextConfig: NextConfig = {
|
|||||||
root: path.resolve(__dirname),
|
root: path.resolve(__dirname),
|
||||||
},
|
},
|
||||||
images: {
|
images: {
|
||||||
remotePatterns: [
|
unoptimized: true,
|
||||||
{
|
|
||||||
protocol: "https",
|
|
||||||
hostname: "images.unsplash.com",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
protocol: "https",
|
|
||||||
hostname: "**.unsplash.com",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user