Add favicon upload option in admin panel
This commit is contained in:
1 parent
befa4ec282
commit
25c3040949
7 files changed
+257
No files matched your search
@@ -0,0 +1,84 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { mkdir, writeFile, unlink } from "fs/promises";
|
||||
import path from "path";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
const FAVICON_DIR = "public/assets/images/media/favicon";
|
||||
const MAX_SIZE = 2 * 1024 * 1024; // 2MB
|
||||
const ALLOWED = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/x-icon", "image/svg+xml"];
|
||||
|
||||
export async function saveFavicon(formData: FormData): Promise<{ success: boolean; url?: string; error?: string }> {
|
||||
try {
|
||||
const file = formData.get("file") as File | null;
|
||||
if (!file || file.size === 0) return { success: false, error: "No file provided" };
|
||||
if (file.size > MAX_SIZE) return { success: false, error: "File too large (max 2MB)" };
|
||||
if (!ALLOWED.includes(file.type)) return { success: false, error: "Invalid file type. Allowed: PNG, JPEG, GIF, WebP, ICO, SVG" };
|
||||
|
||||
const mimeExt: Record<string, string> = {
|
||||
"image/png": "png", "image/jpeg": "jpg", "image/gif": "gif",
|
||||
"image/webp": "webp", "image/x-icon": "ico", "image/svg+xml": "svg",
|
||||
};
|
||||
const ext = mimeExt[file.type] ?? "png";
|
||||
const filename = `favicon-${Date.now()}.${ext}`;
|
||||
const dir = path.join(process.cwd(), FAVICON_DIR);
|
||||
const filePath = path.join(dir, filename);
|
||||
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
await mkdir(dir, { recursive: true });
|
||||
await writeFile(filePath, buffer);
|
||||
|
||||
const url = `/api/media/favicon/${filename}`;
|
||||
|
||||
// Remove old favicon file if it exists
|
||||
const oldUrl = await siteSettings.get("cms_favicon");
|
||||
if (oldUrl && oldUrl.startsWith("/api/media/favicon/")) {
|
||||
const oldName = oldUrl.replace("/api/media/favicon/", "");
|
||||
if (!oldName.includes("..") && !oldName.includes("/")) {
|
||||
try {
|
||||
await unlink(path.join(dir, oldName));
|
||||
} catch { /* ignore if file doesn't exist */ }
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.websiteSetting.upsert({
|
||||
where: { key: "cms_favicon" },
|
||||
update: { value: url },
|
||||
create: { key: "cms_favicon", value: url, comment: "Favicon URL" },
|
||||
});
|
||||
|
||||
siteSettings.reload();
|
||||
revalidatePath("/", "layout");
|
||||
revalidatePath("/admin/favicon");
|
||||
|
||||
return { success: true, url };
|
||||
} catch (e) {
|
||||
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteFavicon(): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const oldUrl = await siteSettings.get("cms_favicon");
|
||||
if (oldUrl && oldUrl.startsWith("/api/media/favicon/")) {
|
||||
const dir = path.join(process.cwd(), FAVICON_DIR);
|
||||
const oldName = oldUrl.replace("/api/media/favicon/", "");
|
||||
if (!oldName.includes("..") && !oldName.includes("/")) {
|
||||
try {
|
||||
await unlink(path.join(dir, oldName));
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.websiteSetting.delete({ where: { key: "cms_favicon" } }).catch(() => {});
|
||||
siteSettings.reload();
|
||||
revalidatePath("/", "layout");
|
||||
revalidatePath("/admin/favicon");
|
||||
|
||||
return { success: true };
|
||||
} catch (e) {
|
||||
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { saveFavicon, deleteFavicon } from "@/actions/save-favicon";
|
||||
|
||||
export function FaviconForm({ currentUrl }: { currentUrl: string | null }) {
|
||||
const t = useTranslations("pages.admin.favicon");
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [preview, setPreview] = useState<string | null>(currentUrl);
|
||||
const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
async function handleUpload(formData: FormData) {
|
||||
setUploading(true);
|
||||
setMessage(null);
|
||||
const result = await saveFavicon(formData);
|
||||
setUploading(false);
|
||||
|
||||
if (result.success && result.url) {
|
||||
setPreview(result.url);
|
||||
setMessage({ type: "success", text: t("saved") });
|
||||
formRef.current?.reset();
|
||||
} else {
|
||||
setMessage({ type: "error", text: result.error ?? t("error") });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
if (!confirm(t("confirmDelete"))) return;
|
||||
setDeleting(true);
|
||||
setMessage(null);
|
||||
const result = await deleteFavicon();
|
||||
setDeleting(false);
|
||||
|
||||
if (result.success) {
|
||||
setPreview(null);
|
||||
setMessage({ type: "success", text: t("deleted") });
|
||||
} else {
|
||||
setMessage({ type: "error", text: result.error ?? t("error") });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-card max-w-lg">
|
||||
{preview && (
|
||||
<div className="mb-6">
|
||||
<label className="block text-xs font-bold text-[var(--color-text-muted)] uppercase tracking-wider mb-2">
|
||||
{t("current")}
|
||||
</label>
|
||||
<div className="flex items-center gap-4">
|
||||
<img
|
||||
src={preview}
|
||||
alt="Favicon preview"
|
||||
className="w-16 h-16 rounded-lg border-2 border-[var(--border)] object-contain bg-white"
|
||||
/>
|
||||
<div className="text-xs text-[var(--color-text-muted)] break-all">{preview}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form action={handleUpload} ref={formRef}>
|
||||
<div className="mb-4">
|
||||
<label className="block text-xs font-bold text-[var(--color-text-muted)] uppercase tracking-wider mb-2">
|
||||
{t("uploadLabel")}
|
||||
</label>
|
||||
<input
|
||||
type="file"
|
||||
name="file"
|
||||
accept=".png,.jpg,.jpeg,.gif,.webp,.ico,.svg"
|
||||
required
|
||||
className="block w-full text-sm text-[var(--color-text)] file:mr-3 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-[var(--color-primary)] file:text-white hover:file:bg-[var(--color-primary-hover)] cursor-pointer"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-[var(--color-text-muted)]">{t("uploadHint")}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" disabled={uploading} className="btn btn-primary">
|
||||
{uploading ? t("uploading") : t("upload")}
|
||||
</button>
|
||||
{preview && (
|
||||
<button type="button" onClick={handleDelete} disabled={deleting} className="btn btn-danger">
|
||||
{deleting ? t("deleting") : t("delete")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{message && (
|
||||
<div
|
||||
className={`mt-4 p-3 rounded-lg text-sm ${
|
||||
message.type === "success"
|
||||
? "bg-green-500/10 text-green-600 dark:text-green-400"
|
||||
: "bg-red-500/10 text-red-600 dark:text-red-400"
|
||||
}`}
|
||||
>
|
||||
{message.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { Image } from "lucide-react";
|
||||
import { FaviconForm } from "./favicon-form";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function AdminFaviconPage() {
|
||||
const t = await getTranslations("pages.admin.favicon");
|
||||
|
||||
let faviconUrl: string | null = null;
|
||||
try {
|
||||
const setting = await prisma.websiteSetting.findUnique({ where: { key: "cms_favicon" } });
|
||||
faviconUrl = setting?.value ?? null;
|
||||
} catch {
|
||||
faviconUrl = null;
|
||||
}
|
||||
|
||||
return (
|
||||
<main>
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-10 h-10 rounded-xl bg-gradient-to-br from-[var(--color-primary)]/20 to-[var(--color-primary)]/5 grid place-items-center">
|
||||
<Image size={20} className="text-[var(--color-primary)]" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="m-0 text-xl font-extrabold text-[var(--color-text)]">{t("title")}</h1>
|
||||
<p className="m-0 text-xs text-[var(--color-text-muted)] mt-0.5">{t("subtitle")}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FaviconForm currentUrl={faviconUrl} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -81,6 +81,7 @@ function getNavGroups(t: (key: string) => string) {
|
||||
{ href: "/admin/email-templates", label: t("emailTemplates"), icon: <Mail size={16} /> },
|
||||
{ href: "/admin/theme", label: t("theme"), icon: <Palette size={16} /> },
|
||||
{ href: "/admin/media", label: t("media"), icon: <Image size={16} /> },
|
||||
{ href: "/admin/favicon", label: t("favicon"), icon: <Image size={16} /> },
|
||||
{ href: "/admin/settings", label: t("settings"), icon: <Cog size={16} /> },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -32,11 +32,14 @@ const pixelFont = Pixelify_Sans({
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const appUrl = process.env.APP_URL ?? "http://localhost:3000";
|
||||
const hotel = (await siteSettings.get("hotel_name", "Atom")) ?? "Atom";
|
||||
const favicon = await siteSettings.get("cms_favicon");
|
||||
const icons = favicon ? [{ rel: "icon", url: favicon }, { rel: "shortcut icon", url: favicon }] : [];
|
||||
return {
|
||||
title: { default: `${hotel} - Hotel`, template: `%s · ${hotel}` },
|
||||
description: `${hotel} — a Habbo retro hotel. Hang out, collect furni and meet friends.`,
|
||||
metadataBase: new URL(appUrl),
|
||||
alternates: { canonical: appUrl },
|
||||
icons,
|
||||
openGraph: {
|
||||
title: `${hotel} - Hotel`,
|
||||
description: `${hotel} — a Habbo retro hotel. Hang out, collect furni and meet friends.`,
|
||||
|
||||
@@ -731,6 +731,7 @@
|
||||
"emailTemplates": "Email templates",
|
||||
"theme": "Theme",
|
||||
"media": "Media",
|
||||
"favicon": "Favicon",
|
||||
"settings": "Settings",
|
||||
"backToSite": "Back to site",
|
||||
"housekeeping": "Housekeeping",
|
||||
@@ -1973,6 +1974,21 @@
|
||||
"copyUrl": "Copy URL",
|
||||
"urlCopied": "URL copied to clipboard"
|
||||
},
|
||||
"favicon": {
|
||||
"title": "Favicon",
|
||||
"subtitle": "Upload and manage the site favicon",
|
||||
"current": "Current favicon",
|
||||
"uploadLabel": "Upload favicon",
|
||||
"uploadHint": "PNG, JPEG, GIF, WebP, ICO or SVG. Max 2MB.",
|
||||
"upload": "Upload",
|
||||
"uploading": "Uploading…",
|
||||
"delete": "Remove",
|
||||
"deleting": "Removing…",
|
||||
"saved": "Favicon saved successfully!",
|
||||
"deleted": "Favicon removed successfully!",
|
||||
"error": "Something went wrong",
|
||||
"confirmDelete": "Remove the favicon? The site will no longer show a custom favicon."
|
||||
},
|
||||
"settings": {
|
||||
"title": "CMS Settings",
|
||||
"subtitle": "Manage key/value CMS configuration",
|
||||
|
||||
@@ -729,6 +729,7 @@
|
||||
"emailTemplates": "E-mailsjablonen",
|
||||
"theme": "Thema",
|
||||
"media": "Media",
|
||||
"favicon": "Favicon",
|
||||
"settings": "Instellingen",
|
||||
"backToSite": "Terug naar site",
|
||||
"hotelManagementPanel": "Hotelbeheerpaneel",
|
||||
@@ -1970,6 +1971,21 @@
|
||||
"copyUrl": "URL kopiëren",
|
||||
"urlCopied": "URL naar klembord gekopieerd"
|
||||
},
|
||||
"favicon": {
|
||||
"title": "Favicon",
|
||||
"subtitle": "Upload en beheer de favicon van de site",
|
||||
"current": "Huidige favicon",
|
||||
"uploadLabel": "Favicon uploaden",
|
||||
"uploadHint": "PNG, JPEG, GIF, WebP, ICO of SVG. Max 2MB.",
|
||||
"upload": "Uploaden",
|
||||
"uploading": "Bezig met uploaden…",
|
||||
"delete": "Verwijderen",
|
||||
"deleting": "Bezig met verwijderen…",
|
||||
"saved": "Favicon succesvol opgeslagen!",
|
||||
"deleted": "Favicon succesvol verwijderd!",
|
||||
"error": "Er is iets misgegaan",
|
||||
"confirmDelete": "Favicon verwijderen? De site zal geen aangepaste favicon meer tonen."
|
||||
},
|
||||
"settings": {
|
||||
"title": "CMS-instellingen",
|
||||
"subtitle": "Beheer sleutel/waarde CMS-configuratie",
|
||||
|
||||
Reference in new issue
Block a user