| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444 |
- 'use client';
- import './style.scss';
- import type { CSSProperties, ChangeEvent } from 'react';
- import { useCallback, useEffect, useRef, useState } from 'react';
- import Image from 'next/image';
- import { fetchApi } from '@/lib/utils/client';
- import { useStudioContext } from '@/app/studio/context';
- import Loading from '@/app/component/Loading';
- import { Plus, Pencil, Trash2, Upload, X } from 'lucide-react';
- import type { ChannelTitleItem, ChannelTitleListResponse } from '@/types/response/studio/titles';
- interface FormData {
- id: number|null;
- name: string;
- description: string;
- minAmount: string;
- color: string;
- iconUrl: string;
- isActive: boolean;
- }
- const EMPTY_FORM: FormData = {
- id: null,
- name: '',
- description: '',
- minAmount: '',
- color: '#A855F7',
- iconUrl: '',
- isActive: true
- };
- const ALLOWED_ICON_MIME = ['image/gif', 'image/jpeg', 'image/png', 'image/webp'];
- const ALLOWED_ICON_EXT = ['.gif', '.jpg', '.jpeg', '.png', '.webp'];
- const MAX_ICON_SIZE_MB = 20;
- const MAX_ICON_SIZE_BYTES = MAX_ICON_SIZE_MB * 1024 * 1024;
- export default function StudioTitlesPage() {
- const { channelID } = useStudioContext();
- const [titles, setTitles] = useState<ChannelTitleItem[]>([]);
- const [loading, setLoading] = useState(true);
- const [showForm, setShowForm] = useState(false);
- const [form, setForm] = useState<FormData>(EMPTY_FORM);
- const [submitting, setSubmitting] = useState(false);
- // 아이콘 업로드 관련 상태
- const [iconFile, setIconFile] = useState<File|null>(null);
- const [iconPreview, setIconPreview] = useState<string|null>(null);
- const [uploadingIcon, setUploadingIcon] = useState(false);
- const fileInputRef = useRef<HTMLInputElement|null>(null);
- const loadTitles = useCallback(() => {
- if (!channelID) {
- return;
- }
- setLoading(true);
- fetchApi<ChannelTitleListResponse>(`/api/channel-titles/${channelID}?includeInactive=true`, { silent: true }).then((res) => {
- setTitles(res.data?.titles ?? []);
- }).catch(() => {
- setTitles([]);
- }).finally(() => {
- setLoading(false);
- });
- }, [channelID]);
- useEffect(() => {
- loadTitles();
- }, [loadTitles]);
- // blob URL 누수 방지
- useEffect(() => {
- return () => {
- if (iconPreview && iconPreview.startsWith('blob:')) {
- URL.revokeObjectURL(iconPreview);
- }
- };
- }, [iconPreview]);
- const resetIconState = () => {
- if (iconPreview && iconPreview.startsWith('blob:')) {
- URL.revokeObjectURL(iconPreview);
- }
- setIconFile(null);
- setIconPreview(null);
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- }
- };
- const openCreateForm = () => {
- resetIconState();
- setForm(EMPTY_FORM);
- setShowForm(true);
- };
- const openEditForm = (title: ChannelTitleItem) => {
- resetIconState();
- setForm({
- id: title.id,
- name: title.name,
- description: title.description ?? '',
- minAmount: title.minAmount.toString(),
- color: title.color,
- iconUrl: title.iconUrl ?? '',
- isActive: title.isActive
- });
- setShowForm(true);
- };
- const closeForm = () => {
- resetIconState();
- setShowForm(false);
- setForm(EMPTY_FORM);
- };
- const handleFileSelect = (e: ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (!file) {
- return;
- }
- // 확장자/MIME 검증
- const lowerName = file.name.toLowerCase();
- const extMatch = ALLOWED_ICON_EXT.some((ext) => lowerName.endsWith(ext));
- const mimeMatch = ALLOWED_ICON_MIME.includes(file.type);
- if (!extMatch || !mimeMatch) {
- alert('이미지 파일(gif, jpeg, png, webp)만 업로드할 수 있습니다.');
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- }
- return;
- }
- // 크기 검증
- if (file.size > MAX_ICON_SIZE_BYTES) {
- alert(`파일 크기는 ${MAX_ICON_SIZE_MB}MB 이하여야 합니다.`);
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- }
- return;
- }
- // 기존 blob 정리 후 새 미리보기 생성
- if (iconPreview && iconPreview.startsWith('blob:')) {
- URL.revokeObjectURL(iconPreview);
- }
- const previewUrl = URL.createObjectURL(file);
- setIconFile(file);
- setIconPreview(previewUrl);
- };
- const handleRemoveIcon = () => {
- resetIconState();
- setForm({ ...form, iconUrl: '' });
- };
- const uploadIcon = async (): Promise<string> => {
- if (!iconFile || !channelID) {
- throw new Error('업로드할 파일이 없습니다.');
- }
- const formData = new FormData();
- formData.append('file', iconFile);
- formData.append('channelID', channelID.toString());
- const res = await fetchApi<{ url: string }>('/api/channel-titles/icon/upload', {
- method: 'POST',
- body: formData
- });
- if (!res.data?.url) {
- throw new Error('아이콘 업로드 응답이 비어 있습니다.');
- }
- return res.data.url;
- };
- const handleSubmit = async () => {
- if (!channelID) {
- return;
- }
- if (!form.name.trim()) {
- alert('칭호 이름을 입력해 주세요.');
- return;
- }
- const amount = parseInt(form.minAmount || '0', 10);
- if (Number.isNaN(amount) || amount < 0) {
- alert('최소 금액을 올바르게 입력해 주세요.');
- return;
- }
- setSubmitting(true);
- try {
- let iconUrl = form.iconUrl.trim();
- // 새 파일이 있으면 먼저 업로드
- if (iconFile) {
- setUploadingIcon(true);
- try {
- iconUrl = await uploadIcon();
- } finally {
- setUploadingIcon(false);
- }
- }
- const payload = {
- ChannelID: channelID,
- Name: form.name.trim(),
- Description: form.description.trim() || null,
- MinAmount: amount,
- Color: form.color,
- IconUrl: iconUrl || null,
- IsActive: form.isActive
- };
- if (form.id) {
- await fetchApi(`/api/channel-titles/${form.id}`, { method: 'PUT', body: payload });
- } else {
- await fetchApi(`/api/channel-titles`, { method: 'POST', body: payload });
- }
- alert(form.id ? '칭호가 수정되었습니다.' : '칭호가 추가되었습니다.');
- closeForm();
- loadTitles();
- } catch (err) {
- alert(err instanceof Error ? err.message : '저장에 실패했습니다.');
- } finally {
- setSubmitting(false);
- }
- };
- const handleDelete = (title: ChannelTitleItem) => {
- if (!confirm(`"${title.name}" 칭호를 삭제하시겠습니까?`)) {
- return;
- }
- fetchApi(`/api/channel-titles/${title.id}`, { method: 'DELETE' }).then(() => {
- alert('삭제되었습니다.');
- loadTitles();
- }).catch((err) => {
- alert(err instanceof Error ? err.message : '삭제에 실패했습니다.');
- });
- };
- if (!channelID) {
- return (
- <div className="studio-page">
- <p className="studio-page__empty">채널을 먼저 연동해 주세요.</p>
- </div>
- );
- }
- // 미리보기 표시용: 새 파일(blob) 우선, 없으면 기존 서버 URL
- const previewSrc = iconPreview ?? (form.iconUrl.trim() || null);
- return (
- <div id="studioTitlesPage">
- <header className="studio-titles__header">
- <h1>채널 칭호 설정</h1>
- <button type="button" className="studio-titles__add-btn" onClick={openCreateForm}>
- <Plus size={16} />
- 칭호 추가
- </button>
- </header>
- <p className="studio-titles__hint">
- 후원자가 누적 후원 금액을 달성하면 자동으로 칭호를 획득합니다. 최대 30개까지 등록할 수 있습니다.
- </p>
- {loading ? <Loading type={2} /> : (
- <div className="studio-titles__list">
- {titles.length === 0 ? (
- <p className="studio-titles__empty">등록된 칭호가 없습니다.</p>
- ) : (
- titles.map((title) => (
- <article key={title.id} className={`studio-titles__card ${!title.isActive ? 'studio-titles__card--inactive' : ''}`}>
- <div className="studio-titles__card-badge" style={{ '--badge-color': title.color } as CSSProperties}>
- {title.iconUrl ? (
- <Image
- src={title.iconUrl}
- alt={title.name}
- width={20}
- height={20}
- className="studio-titles__card-badge-icon"
- unoptimized
- />
- ) : null}
- <span>{title.name}</span>
- </div>
- <div className="studio-titles__card-info">
- <strong>{title.name}</strong>
- <span>누적 {title.minAmount.toLocaleString('ko-KR')}원 이상</span>
- {title.description ? <em>{title.description}</em> : null}
- </div>
- <div className="studio-titles__card-actions">
- <button type="button" className="studio-titles__icon-btn" onClick={() => openEditForm(title)} title="편집">
- <Pencil size={16} />
- </button>
- <button type="button" className="studio-titles__icon-btn studio-titles__icon-btn--danger" onClick={() => handleDelete(title)} title="삭제">
- <Trash2 size={16} />
- </button>
- </div>
- </article>
- ))
- )}
- </div>
- )}
- {showForm && (
- <div className="studio-titles__form-overlay" role="dialog">
- <div className="studio-titles__form">
- <h2>{form.id ? '칭호 수정' : '칭호 추가'}</h2>
- <label>
- 이름
- <input
- type="text"
- value={form.name}
- onChange={(e) => setForm({ ...form, name: e.target.value })}
- maxLength={20}
- placeholder="예) VIP 팬"
- />
- </label>
- <label>
- 설명
- <input
- type="text"
- value={form.description}
- onChange={(e) => setForm({ ...form, description: e.target.value })}
- maxLength={100}
- placeholder="설명 (선택)"
- />
- </label>
- <label>
- 최소 누적 금액 (원)
- <input
- type="number"
- value={form.minAmount}
- onChange={(e) => setForm({ ...form, minAmount: e.target.value })}
- min="0"
- placeholder="예) 100000"
- />
- </label>
- <label>
- 색상
- <input
- type="color"
- value={form.color}
- onChange={(e) => setForm({ ...form, color: e.target.value })}
- />
- </label>
- <div className="studio-titles__form-icon">
- <span className="studio-titles__form-icon-label">아이콘 (gif, jpeg, png, webp · 최대 {MAX_ICON_SIZE_MB}MB)</span>
- <div className="studio-titles__form-icon-row">
- <button
- type="button"
- className="studio-titles__form-icon-btn"
- onClick={() => fileInputRef.current?.click()}
- disabled={uploadingIcon}
- >
- <Upload size={14} />
- {previewSrc ? '아이콘 변경' : '아이콘 선택'}
- </button>
- <input
- ref={fileInputRef}
- type="file"
- accept={ALLOWED_ICON_MIME.join(',')}
- onChange={handleFileSelect}
- className="studio-titles__form-icon-input"
- />
- {previewSrc ? (
- <button
- type="button"
- className="studio-titles__form-icon-remove"
- onClick={handleRemoveIcon}
- disabled={uploadingIcon}
- title="아이콘 제거"
- >
- <X size={14} />
- 제거
- </button>
- ) : null}
- </div>
- {previewSrc ? (
- <div className="studio-titles__form-icon-preview">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img src={previewSrc} alt="아이콘 미리보기" />
- {iconFile ? (
- <small>
- {iconFile.name} ({(iconFile.size / 1024).toFixed(1)} KB)
- </small>
- ) : (
- <small>저장된 아이콘</small>
- )}
- </div>
- ) : null}
- </div>
- <label className="studio-titles__form-checkbox">
- <input
- type="checkbox"
- checked={form.isActive}
- onChange={(e) => setForm({ ...form, isActive: e.target.checked })}
- />
- 활성화
- </label>
- <div className="studio-titles__form-preview">
- <span style={{ '--badge-color': form.color } as CSSProperties}>
- {previewSrc ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img src={previewSrc} alt="" className="studio-titles__form-preview-icon" />
- ) : null}
- {form.name || '미리보기'}
- </span>
- 님이 10,000원 후원!
- </div>
- <div className="studio-titles__form-actions">
- <button type="button" onClick={closeForm} disabled={submitting || uploadingIcon}>취소</button>
- <button type="button" className="studio-titles__form-save" onClick={handleSubmit} disabled={submitting || uploadingIcon}>
- {uploadingIcon
- ? '아이콘 업로드 중...'
- : submitting
- ? (form.id ? '수정 중...' : '등록 중...')
- : (form.id ? '수정' : '등록')}
- </button>
- </div>
- </div>
- </div>
- )}
- </div>
- );
- }
|