page.tsx 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. 'use client';
  2. import { useState, useEffect, useRef } from 'react';
  3. import { useRouter } from 'next/navigation';
  4. import Link from 'next/link';
  5. import { fetchApi } from '@/lib/utils/client';
  6. import { useStudioContext } from '@/app/studio/context';
  7. import { useAlertConfigContext } from '../context';
  8. import { Separator } from '@/components/ui/separator';
  9. import Loading from '@/app/component/Loading';
  10. import AlertPreviewPanel from '../_components/AlertPreviewPanel';
  11. import AlertFormPanel from '../_components/AlertFormPanel';
  12. import { createEmptyForm } from '../types';
  13. import type { FormState, PendingFiles } from '../types';
  14. export default function AlertAddPage()
  15. {
  16. const router = useRouter();
  17. const { channelID, memberID } = useStudioContext();
  18. const { setSaving, fetchList } = useAlertConfigContext();
  19. const [form, setForm] = useState<FormState>(createEmptyForm());
  20. const [pendingFiles, setPendingFiles] = useState<PendingFiles>({ image: null, sound: null });
  21. const [localSaving, setLocalSaving] = useState(false);
  22. const formRef = useRef<FormState>(form);
  23. formRef.current = form;
  24. // ── blob URL cleanup ─────────────────────────────
  25. const cleanupBlobUrls = (f: FormState) => {
  26. if (f.imageUrl?.startsWith('blob:')) {
  27. URL.revokeObjectURL(f.imageUrl);
  28. }
  29. if (f.soundUrl?.startsWith('blob:')) {
  30. URL.revokeObjectURL(f.soundUrl);
  31. }
  32. };
  33. // unmount 시 cleanup
  34. useEffect(() => {
  35. return () => {
  36. cleanupBlobUrls(formRef.current);
  37. };
  38. }, []);
  39. // ── 폼 필드 변경 ────────────────────────────────
  40. const handleFormChange = <K extends keyof FormState>(field: K, value: FormState[K]) => {
  41. setForm(prev => {
  42. if ((field === 'imageUrl' || field === 'soundUrl') && typeof prev[field] === 'string' && (prev[field] as string).startsWith('blob:')) {
  43. URL.revokeObjectURL(prev[field] as string);
  44. }
  45. return { ...prev, [field]: value };
  46. });
  47. if (field === 'imageUrl' && value === null) {
  48. setPendingFiles(prev => ({ ...prev, image: null }));
  49. }
  50. if (field === 'soundUrl' && value === null) {
  51. setPendingFiles(prev => ({ ...prev, sound: null }));
  52. }
  53. };
  54. // ── 파일 업로드 헬퍼 ─────────────────────────────
  55. const uploadFile = async (file: File, type: 'image'|'sound'): Promise<string> => {
  56. const formData = new FormData();
  57. formData.append('file', file);
  58. formData.append('type', type);
  59. formData.append('channelID', channelID!.toString());
  60. const res = await fetchApi<{ url: string }>('/api/studio/donation/alert/config/upload', {
  61. method: 'POST',
  62. body: formData,
  63. });
  64. return res.data?.url ?? '';
  65. };
  66. // ── 저장 ─────────────────────────────────────────
  67. const handleSave = async () => {
  68. if (!channelID) {
  69. return;
  70. }
  71. if (!form.message.trim()) {
  72. alert('메시지를 입력해 주세요.');
  73. return;
  74. }
  75. if (form.amount < 1) {
  76. alert('금액은 1원 이상이어야 합니다.');
  77. return;
  78. }
  79. if (form.displayDurationSec < 1) {
  80. alert('노출 시간은 1초 이상이어야 합니다.');
  81. return;
  82. }
  83. setLocalSaving(true);
  84. setSaving(true);
  85. try {
  86. let finalImageUrl = form.imageUrl;
  87. let finalSoundUrl = form.soundUrl;
  88. if (pendingFiles.image) {
  89. finalImageUrl = await uploadFile(pendingFiles.image, 'image');
  90. }
  91. if (pendingFiles.sound) {
  92. finalSoundUrl = await uploadFile(pendingFiles.sound, 'sound');
  93. }
  94. const item = {
  95. id: null,
  96. ...form,
  97. imageUrl: finalImageUrl,
  98. soundUrl: finalSoundUrl,
  99. popupEffect: form.popupEffect || null,
  100. textEffect: form.textEffect || null,
  101. nicknameFontFamily: form.nicknameFontFamily || null,
  102. amountFontFamily: form.amountFontFamily || null,
  103. messageFontFamily: form.messageFontFamily || null,
  104. };
  105. await fetchApi('/api/studio/donation/alert/config/batch', {
  106. method: 'POST',
  107. body: { channelID, memberID, items: [item], deleteIDs: [] },
  108. });
  109. cleanupBlobUrls(form);
  110. alert('등록되었습니다.');
  111. fetchList();
  112. router.push('/studio/donation/alert/list');
  113. } catch (err) {
  114. alert(err instanceof Error ? err.message : '저장에 실패했습니다.');
  115. } finally {
  116. setLocalSaving(false);
  117. setSaving(false);
  118. }
  119. };
  120. // ── 취소 ─────────────────────────────────────────
  121. const handleCancel = () => {
  122. cleanupBlobUrls(form);
  123. router.push('/studio/donation/alert/list');
  124. };
  125. return (
  126. <>
  127. {localSaving && <Loading type={1} fullscreen />}
  128. <div className="studio-page__title-row">
  129. <h1 className="studio-page__title">후원 알림 추가</h1>
  130. <Link href="/studio/donation/alert/list" className="alert-config__btn alert-config__btn--sm">< 목록으로</Link>
  131. </div>
  132. <div className='pt-5 pb-5'>
  133. <Separator orientation="horizontal" />
  134. </div>
  135. <div className="alert-config__layout">
  136. <AlertPreviewPanel form={form} />
  137. <Separator orientation="vertical" />
  138. <AlertFormPanel
  139. form={form}
  140. editingItem={null}
  141. saving={localSaving}
  142. pendingFiles={pendingFiles}
  143. onFileSelect={(file, type) => {
  144. const previewUrl = URL.createObjectURL(file);
  145. if (type === 'image') {
  146. setPendingFiles(prev => ({ ...prev, image: file }));
  147. handleFormChange('imageUrl', previewUrl);
  148. } else {
  149. setPendingFiles(prev => ({ ...prev, sound: file }));
  150. handleFormChange('soundUrl', previewUrl);
  151. }
  152. }}
  153. onFormChange={handleFormChange}
  154. onSave={handleSave}
  155. onCancel={handleCancel}
  156. />
  157. </div>
  158. </>
  159. );
  160. }