feat: add Discord profile dropdown menu with role display and integrate with admin and form layouts via AdminShellServer.

This commit is contained in:
2026-07-03 23:02:15 +07:00 Unverified
parent 6cb28421e6
commit ac6c35598c
12 changed files with 413 additions and 83 deletions
+55
View File
@@ -61,3 +61,58 @@ export async function getGuildMemberRoles(discordId: string): Promise<string[]>
return [];
}
}
export async function getDiscordMemberProfile(discordId: string) {
const token = process.env.DISCORD_BOT_TOKEN;
const guildId = process.env.DISCORD_GUILD_ID;
if (!token || !guildId || !discordId) return null;
try {
const [memberRes, allRoles] = await Promise.all([
fetch(`https://discord.com/api/v10/guilds/${guildId}/members/${discordId}`, {
headers: { Authorization: `Bot ${token}` },
cache: "no-store",
}),
getGuildRoles()
]);
if (!memberRes.ok) return null;
const member = await memberRes.json();
// Map member role IDs to actual role objects
const memberRoleIds = member.roles || [];
const roles = memberRoleIds
.map((id: string) => allRoles.find(r => r.id === id))
.filter(Boolean);
// Sort roles by position (descending)
roles.sort((a: any, b: any) => (b?.position || 0) - (a?.position || 0));
const user = member.user;
let avatarUrl = null;
if (user.avatar) {
const ext = user.avatar.startsWith("a_") ? "gif" : "png";
avatarUrl = `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.${ext}?size=128`;
}
let bannerUrl = null;
if (user.banner) {
const ext = user.banner.startsWith("a_") ? "gif" : "png";
bannerUrl = `https://cdn.discordapp.com/banners/${user.id}/${user.banner}.${ext}?size=512`;
}
return {
id: user.id,
username: user.username,
globalName: user.global_name || null,
avatarUrl,
bannerUrl,
accentColor: user.accent_color || null,
roles,
};
} catch (e) {
console.error("Failed to fetch member profile", e);
return null;
}
}
+3 -3
View File
@@ -1,4 +1,4 @@
import { AdminShell } from "@/components/admin-shell";
import { AdminShellServer } from "@/components/admin-shell-server";
import { readdirSync } from "fs";
import { join } from "path";
import { BackendClient } from "./client";
@@ -31,7 +31,7 @@ export default async function BackendPage() {
}));
return (
<AdminShell>
<AdminShellServer>
<div className="p-6 space-y-6 max-w-6xl mx-auto w-full">
<div>
<h1 className="text-3xl font-bold tracking-tight">Backend</h1>
@@ -41,6 +41,6 @@ export default async function BackendPage() {
</div>
<BackendClient platforms={platformData} />
</div>
</AdminShell>
</AdminShellServer>
);
}
+23 -2
View File
@@ -38,6 +38,7 @@ import Image from 'next/image';
import { RichTextEditor } from "@/components/rich-text-editor";
import { FormattedText } from "@/components/formatted-text";
import { ThemeToggle } from "@/components/theme-toggle";
import { DropdownMenuAvatar, DiscordMemberProfile } from "@/components/dropdown-menu-avatar";
interface Question {
id: string;
@@ -609,7 +610,17 @@ function AnswerPreview({ question }: { question: Question }) {
);
}
export function AdminSidebar({ formId }: { formId: string }) {
export function AdminSidebar({
formId,
userName,
userImage,
profile,
}: {
formId: string;
userName?: string;
userImage?: string;
profile?: DiscordMemberProfile | null;
}) {
const pathname = usePathname();
return (
@@ -618,7 +629,17 @@ export function AdminSidebar({ formId }: { formId: string }) {
<span className="font-bold tracking-wider text-primary text-sm uppercase">
Form Admin
</span>
<ThemeToggle />
<div className="flex items-center gap-1">
{(userName || profile) && (
<DropdownMenuAvatar
userName={userName || ""}
userImage={userImage || ""}
profile={profile || null}
showName={false}
/>
)}
<ThemeToggle />
</div>
</SidebarHeader>
<SidebarContent>
+16 -1
View File
@@ -1,6 +1,9 @@
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { AdminSidebar } from "./client";
import { Metadata } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { getDiscordMemberProfile } from "@/app/actions/discord";
export const metadata: Metadata = {
title: {
@@ -16,11 +19,23 @@ export default async function AdminFormLayout(
}
) {
const params = await props.params;
const session = await getServerSession(authOptions);
let profile = null;
const discordId = (session?.user as any)?.discordId;
if (discordId) {
profile = await getDiscordMemberProfile(discordId);
}
return (
<SidebarProvider>
<div className="flex w-full bg-background text-foreground">
<AdminSidebar formId={params.id} />
<AdminSidebar
formId={params.id}
userName={session?.user?.name || ""}
userImage={session?.user?.image || ""}
profile={profile}
/>
<div className="flex-1 overflow-hidden">
<div className="md:hidden p-2">
<SidebarTrigger />
+3 -3
View File
@@ -13,7 +13,7 @@ import { Badge } from "@/components/ui/badge";
import { Plus } from "lucide-react";
import { redirect } from "next/navigation";
import { DeleteFormButton } from "@/components/delete-buttons";
import { AdminShell } from "@/components/admin-shell";
import { AdminShellServer } from "@/components/admin-shell-server";
export const dynamic = "force-dynamic";
@@ -23,7 +23,7 @@ export default async function AdminFormsPage() {
});
return (
<AdminShell>
<AdminShellServer>
<div className="space-y-6 p-4 md:p-6 pb-12 w-full">
<div className="flex items-center justify-between">
<div>
@@ -100,6 +100,6 @@ export default async function AdminFormsPage() {
</Table>
</div>
</div>
</AdminShell>
</AdminShellServer>
);
}
+3 -3
View File
@@ -1,4 +1,4 @@
import { AdminShell } from "@/components/admin-shell";
import { AdminShellServer } from "@/components/admin-shell-server";
import Link from "next/link";
import {
Card,
@@ -10,7 +10,7 @@ import { ClipboardList, Server } from "lucide-react";
export default function AdminPage() {
return (
<AdminShell>
<AdminShellServer>
<div className="p-6 space-y-6 max-w-6xl mx-auto w-full">
<div>
<h1 className="text-3xl font-bold tracking-tight">Dashboard</h1>
@@ -51,6 +51,6 @@ export default function AdminPage() {
</Link>
</div>
</div>
</AdminShell>
</AdminShellServer>
);
}
+8 -26
View File
@@ -27,43 +27,25 @@ import {
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { DropdownMenuAvatar, DiscordMemberProfile } from "@/components/dropdown-menu-avatar";
export function FormLayoutClient({
userName,
userImage,
profile,
}: {
userName: string;
userImage: string;
profile?: DiscordMemberProfile | null;
}) {
const [imgError, setImgError] = useState(false);
return (
<div className="flex items-center gap-3">
{userImage && !imgError && (
<Image
src={userImage}
alt={userName}
width={28}
height={28}
className="rounded-full object-cover"
onError={() => setImgError(true)}
unoptimized
/>
)}
<span className="text-sm text-muted-foreground">{userName}</span>
<Button
variant="ghost"
size="sm"
onClick={() => signOut()}
>
<LogOut className="w-4 h-4" />
</Button>
</div>
<DropdownMenuAvatar
userName={userName}
userImage={userImage}
profile={profile || null}
/>
);
}
+8
View File
@@ -4,6 +4,7 @@ import { FormLayoutClient } from "./client";
import LoginDialog from "@/components/login-dialog";
import { Metadata } from "next";
import { ThemeToggle } from "@/components/theme-toggle";
import { getDiscordMemberProfile } from "@/app/actions/discord";
import Link from 'next/link';
const siteUrl = process.env.BASE_URL;
@@ -35,6 +36,12 @@ export default async function FormLayout({
children: React.ReactNode;
}) {
const session = await getServerSession(authOptions);
const discordId = (session?.user as any)?.discordId;
let profile = null;
if (discordId) {
profile = await getDiscordMemberProfile(discordId);
}
return (
<div className="flex min-h-screen flex-col flex-1 w-full bg-background text-foreground">
@@ -49,6 +56,7 @@ export default async function FormLayout({
<FormLayoutClient
userName={session.user.name ?? ""}
userImage={session.user.image ?? ""}
profile={profile}
/>
)}
<ThemeToggle />
+39 -2
View File
@@ -7,6 +7,9 @@ import {
CardDescription,
} from "@/components/ui/card";
import { HtmlDisplay } from "@/components/html-display";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { getGuildMemberRoles } from "@/app/actions/discord";
export const dynamic = "force-dynamic";
@@ -16,14 +19,48 @@ export default async function FormsListingPage() {
orderBy: (f, { desc }) => [desc(f.createdAt)],
});
const session = await getServerSession(authOptions);
const discordId = (session?.user as { discordId?: string })?.discordId;
let userRoles: string[] = [];
if (discordId) {
try {
userRoles = await getGuildMemberRoles(discordId);
} catch (e) {
console.error(e);
}
}
const visibleForms = formsList.filter((form) => {
const allowedRoles = form.allowedRoles || [];
const deniedRoles = form.deniedRoles || [];
if (allowedRoles.length === 0 && deniedRoles.length === 0) return true;
// If user is not logged in but there are role restrictions, hide it.
if (!discordId) return false;
let isAllowed = allowedRoles.length === 0;
if (allowedRoles.length > 0) {
isAllowed = userRoles.some(r => allowedRoles.includes(r));
}
let isDenied = false;
if (deniedRoles.length > 0) {
isDenied = userRoles.some(r => deniedRoles.includes(r));
}
return isAllowed && !isDenied;
});
return (
<div className="max-w-4xl mx-auto p-4 md:p-6 space-y-6">
<h1 className="text-3xl font-bold tracking-tight">Form ทั้งหมด</h1>
{formsList.length === 0 ? (
{visibleForms.length === 0 ? (
<p className="text-muted-foreground">ตอนนี้ยังไม่เปิดรับสัก Form</p>
) : (
<div className="flex flex-col gap-4">
{formsList.map((form) => (
{visibleForms.map((form) => (
<Link key={form.id} href={`/form/${form.id}`}>
<Card className="hover:bg-muted/50 transition-colors h-full flex flex-col">
<CardHeader>
+24
View File
@@ -0,0 +1,24 @@
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { getDiscordMemberProfile } from "@/app/actions/discord";
import { AdminShell } from "@/components/admin-shell";
export async function AdminShellServer({ children }: { children: React.ReactNode }) {
const session = await getServerSession(authOptions);
const discordId = (session?.user as any)?.discordId;
let profile = null;
if (discordId) {
profile = await getDiscordMemberProfile(discordId);
}
return (
<AdminShell
userName={session?.user?.name ?? ""}
userImage={session?.user?.image ?? ""}
profile={profile}
>
{children}
</AdminShell>
);
}
+67 -43
View File
@@ -16,21 +16,70 @@ import {
SidebarInset,
SidebarTrigger,
} from "@/components/ui/sidebar";
import { ClipboardList, Server, LayoutDashboard } from "lucide-react";
import { ClipboardList, Server, LayoutDashboard, LucideIcon } from "lucide-react";
import { ThemeToggle } from "@/components/theme-toggle";
import { DropdownMenuAvatar, DiscordMemberProfile } from "@/components/dropdown-menu-avatar";
export function AdminShell({ children }: { children: React.ReactNode }) {
interface NavItem {
href: string;
label: string;
icon: LucideIcon;
isActive: (pathname: string) => boolean;
}
const NAV_ITEMS: NavItem[] = [
{
href: "/admin",
label: "Dashboard",
icon: LayoutDashboard,
isActive: (pathname) => pathname === "/admin",
},
{
href: "/admin/form",
label: "Form",
icon: ClipboardList,
isActive: (pathname) => pathname === "/admin/form",
},
{
href: "/admin/backend",
label: "Backend",
icon: Server,
isActive: (pathname) => pathname.startsWith("/admin/backend"),
},
];
export function AdminShell({
children,
userName,
userImage,
profile,
}: {
children: React.ReactNode;
userName?: string;
userImage?: string;
profile?: DiscordMemberProfile | null;
}) {
const pathname = usePathname();
return (
<SidebarProvider>
<div className="flex w-full min-h-screen bg-background text-foreground">
<Sidebar variant="sidebar" collapsible="icon">
<SidebarHeader className="border-b border-border py-4 px-4 flex flex-row items-center justify-between">
<span className="font-bold tracking-wider text-primary text-sm uppercase">
Admin
</span>
<ThemeToggle />
<SidebarHeader className="border-b border-border py-4 px-4">
<div className="flex flex-row items-center justify-between">
<span className="font-bold text-primary text-lg">Admin</span>
<div className="flex items-center gap-1">
{(userName || profile) && (
<DropdownMenuAvatar
userName={userName || ""}
userImage={userImage || ""}
profile={profile || null}
showName={false}
/>
)}
<ThemeToggle />
</div>
</div>
</SidebarHeader>
<SidebarContent>
@@ -38,41 +87,16 @@ export function AdminShell({ children }: { children: React.ReactNode }) {
<SidebarGroupLabel>Navigation</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
asChild
isActive={pathname === "/admin"}
>
<Link href="/admin">
<LayoutDashboard className="w-4 h-4" />
<span>Dashboard</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton
asChild
isActive={pathname === "/admin/form"}
>
<Link href="/admin/form">
<ClipboardList className="w-4 h-4" />
<span>Form</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton
asChild
isActive={pathname.startsWith("/admin/backend")}
>
<Link href="/admin/backend">
<Server className="w-4 h-4" />
<span>Backend</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
{NAV_ITEMS.map(({ href, label, icon: Icon, isActive }) => (
<SidebarMenuItem key={href}>
<SidebarMenuButton asChild isActive={isActive(pathname)}>
<Link href={href}>
<Icon className="w-4 h-4" />
<span>{label}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
@@ -88,4 +112,4 @@ export function AdminShell({ children }: { children: React.ReactNode }) {
</div>
</SidebarProvider>
);
}
}
+164
View File
@@ -0,0 +1,164 @@
"use client";
import React, { useState, useMemo } from "react";
import Image from "next/image";
import { LogOut } from "lucide-react";
import { signOut } from "next-auth/react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { DiscordRole } from "@/app/actions/discord";
export interface DiscordMemberProfile {
id: string;
username: string;
globalName: string | null;
avatarUrl: string | null;
bannerUrl: string | null;
accentColor: number | null;
roles: DiscordRole[];
}
const toHex = (n: number) => `#${n.toString(16).padStart(6, "0")}`;
const DEFAULT_ROLE_COLOR = "#99aab5";
function RolePill({ role }: { role: DiscordRole }) {
const colorHex = role.color === 0 ? DEFAULT_ROLE_COLOR : toHex(role.color);
return (
<div className="inline-flex items-center gap-1 rounded-sm px-2 py-1 text-xs font-medium bg-muted/50 border border-border">
<div
className="w-2 h-2 rounded-full shrink-0"
style={{ backgroundColor: colorHex }}
/>
<span className="text-foreground max-w-40 truncate">
{role.name}
</span>
</div>
);
}
export function DropdownMenuAvatar({
userName,
userImage,
profile,
showName = true,
}: {
userName: string;
userImage: string;
profile: DiscordMemberProfile | null;
showName?: boolean;
}) {
const [imgError, setImgError] = useState(false);
const displayAvatar = profile?.avatarUrl || userImage;
const displayName = profile?.globalName || userName;
const username = profile?.username || userName;
const bannerStyle = useMemo(
() => ({
height: 100,
backgroundColor: profile?.accentColor
? toHex(profile.accentColor)
: "hsl(var(--muted))",
backgroundImage: profile?.bannerUrl
? `url(${profile.bannerUrl})`
: "none",
backgroundSize: "cover" as const,
backgroundPosition: "center" as const,
}),
[profile?.accentColor, profile?.bannerUrl]
);
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className={showName ? "pl-1 pr-2 flex items-center gap-2" : "h-9 w-9 rounded-full p-0 flex items-center justify-center"}>
{!imgError && displayAvatar ? (
<Image
src={displayAvatar}
alt={displayName}
width={32}
height={32}
className="rounded-full object-cover shrink-0"
onError={() => setImgError(true)}
unoptimized
/>
) : (
<div className="w-8 h-8 rounded-full bg-muted shrink-0" />
)}
{showName && <span className="text-sm font-medium">{displayName}</span>}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="p-0" style={{ width: 280 }}>
{/* Banner Section */}
<div className="w-full relative" style={bannerStyle} />
{/* Body Area */}
<div className="relative px-3 pb-3">
{/* Avatar - Absolute Positioned to overlap banner and body */}
<div className="absolute" style={{ top: -56, left: 12 }}>
<div className="relative">
<div className="rounded-full bg-popover" style={{ padding: 5 }}>
<div
className="rounded-full overflow-hidden bg-muted"
style={{ width: 76, height: 76 }}
>
{!imgError && displayAvatar && (
<Image
src={displayAvatar}
alt={displayName}
width={76}
height={76}
className="object-cover w-full h-full"
onError={() => setImgError(true)}
unoptimized
/>
)}
</div>
</div>
</div>
</div>
{/* Profile Info Section */}
<div style={{ paddingTop: 36 }}>
<div className="font-bold text-lg leading-tight text-foreground">
{displayName}
</div>
<div className="text-xs text-muted-foreground mt-1">
{username}
</div>
{/* Roles Section */}
{profile && profile.roles.length > 0 && (
<div className="mt-2">
<div className="text-xs font-bold text-muted-foreground uppercase tracking-wider mb-2">
Roles / บทบาท
</div>
<div className="flex flex-wrap gap-1">
{profile.roles.map((role) => (
<RolePill key={role.id} role={role} />
))}
</div>
</div>
)}
</div>
</div>
{/* Footer / Sign Out */}
<div className="p-2 border-t">
<DropdownMenuItem
onClick={() => signOut({ callbackUrl: "/" })}
className="text-destructive"
>
<LogOut className="w-4 h-4 mr-2" />
ออกจากระบบ
</DropdownMenuItem>
</div>
</DropdownMenuContent>
</DropdownMenu>
);
}