@farmzone/fz-template-react 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +102 -102
  2. package/bin/create.js +108 -108
  3. package/package.json +24 -24
  4. package/template/.env.example +5 -5
  5. package/template/.prettierrc +9 -9
  6. package/template/eslint.config.js +26 -26
  7. package/template/index.css +32 -32
  8. package/template/index.html +19 -19
  9. package/template/package.json +54 -54
  10. package/template/pnpm-lock.yaml +4214 -4214
  11. package/template/public/mockServiceWorker.js +349 -349
  12. package/template/src/app/App.tsx +26 -26
  13. package/template/src/app/api/api.ts +178 -178
  14. package/template/src/app/api/queries.ts +335 -335
  15. package/template/src/app/api/queryKey.ts +7 -7
  16. package/template/src/app/api/token.ts +8 -7
  17. package/template/src/app/layout/Layout.tsx +33 -33
  18. package/template/src/app/layout/ListContents.tsx +9 -9
  19. package/template/src/app/layout/ListHeader.tsx +41 -41
  20. package/template/src/app/layout/MultiTabNav.tsx +106 -101
  21. package/template/src/app/layout/Sidebar.tsx +33 -33
  22. package/template/src/app/layout/UserInfo.tsx +95 -94
  23. package/template/src/app/layout/menu.ts +79 -55
  24. package/template/src/app/layout/tabSwitchStore.ts +11 -11
  25. package/template/src/app/router/Router.tsx +56 -56
  26. package/template/src/app/store/index.ts +26 -26
  27. package/template/src/index.tsx +21 -21
  28. package/template/src/mocks/browser.ts +17 -17
  29. package/template/src/mocks/handlers.ts +43 -43
  30. package/template/src/mocks/scenarios.ts +57 -57
  31. package/template/src/pages/dashboard/index.tsx +541 -541
  32. package/template/src/pages/error/Error.tsx +29 -29
  33. package/template/src/pages/error/NotFound.tsx +27 -27
  34. package/template/src/pages/login/index.tsx +317 -317
  35. package/template/src/pages/post/PostFormModal.tsx +128 -128
  36. package/template/src/pages/post/detail/index.tsx +545 -545
  37. package/template/src/pages/post/index.tsx +266 -266
  38. package/template/src/pages/sample/SampleFormModal.tsx +188 -188
  39. package/template/src/pages/sample/detail/index.tsx +551 -517
  40. package/template/src/pages/sample/index.tsx +298 -298
  41. package/template/src/pages/sample/modal/index.tsx +308 -308
  42. package/template/src/pages/system/log/index.tsx +173 -173
  43. package/template/src/pages/user/config/columns.tsx +102 -102
  44. package/template/src/pages/user/config/schema.ts +54 -54
  45. package/template/src/pages/user/index.tsx +704 -650
  46. package/template/src/shared/components/CommentInput.tsx +243 -243
  47. package/template/src/shared/components/FilePreviewCard.tsx +71 -71
  48. package/template/src/shared/config/text.ts +27 -27
  49. package/template/src/shared/config/type.ts +40 -40
  50. package/template/src/shared/utils/format.ts +11 -11
  51. package/template/src/types/auth.ts +10 -10
  52. package/template/src/types/comment.ts +33 -33
  53. package/template/src/types/common.ts +19 -19
  54. package/template/src/types/dashboard.ts +53 -53
  55. package/template/src/types/index.ts +16 -16
  56. package/template/src/types/log.ts +21 -21
  57. package/template/src/types/post.ts +32 -32
  58. package/template/src/types/sample.ts +33 -33
  59. package/template/src/types/user.ts +51 -51
  60. package/template/src/vite-env.d.ts +10 -10
  61. package/template/tsconfig.app.json +32 -32
  62. package/template/tsconfig.json +7 -7
  63. package/template/tsconfig.node.json +26 -26
  64. package/template/vite.config.ts +13 -13
@@ -1,545 +1,545 @@
1
- import { useEffect, useState } from "react";
2
- import { useNavigate, useParams } from "react-router";
3
- import { useQueryClient } from "@tanstack/react-query";
4
-
5
- import { useUserStore } from "@/app/store";
6
- import {
7
- Badge,
8
- Button,
9
- confirmModal,
10
- FilePreviewViewer,
11
- toast,
12
- useFilePreviewViewer,
13
- } from "@farmzone/fz-react-ui";
14
- import { CornerDownRight, Pencil, Trash2 } from "lucide-react";
15
-
16
- import {
17
- useDeleteComment,
18
- useDeletePost,
19
- useGetComments,
20
- useGetPost,
21
- usePutComment,
22
- } from "@/app/api/queries";
23
- import type { Comment, FileResponse } from "@/types";
24
- import { apiFileInstance, apiFormDataInstance } from "@/app/api/api";
25
- import { POST_QUERY_KEY } from "@/app/api/queryKey";
26
- import ListHeader from "@/app/layout/ListHeader";
27
- import CommentInput from "@/shared/components/CommentInput";
28
- import { COMMON_MESSAGES } from "@/shared/config/text";
29
- import { formatDateTime } from "@/shared/utils/format";
30
- import { PostFormModal } from "../PostFormModal";
31
- import type { PostFormData } from "../PostFormModal";
32
- import FilePreviewCard from "@/shared/components/FilePreviewCard";
33
-
34
- function countComments(list: Array<Comment>): number {
35
- return list.reduce((sum, c) => {
36
- const depth2 = c.replies ?? [];
37
- const depth3Count = depth2.reduce((s, r) => s + (r.replies?.length ?? 0), 0);
38
- return sum + 1 + depth2.length + depth3Count;
39
- }, 0);
40
- }
41
-
42
- function toPreviewFileType(mimeType: string): "image" | "pdf" | "unsupported" {
43
- if (mimeType?.startsWith("image/")) return "image";
44
- if (mimeType === "application/pdf") return "pdf";
45
- return "unsupported";
46
- }
47
-
48
- export default function PostDetailPage() {
49
- const { id } = useParams<{ id: string }>();
50
- const postId = Number(id);
51
- const navigate = useNavigate();
52
- const queryClient = useQueryClient();
53
- const currentUser = useUserStore((s) => s.user);
54
-
55
- const [isEditOpen, setIsEditOpen] = useState(false);
56
- const [replyingToId, setReplyingToId] = useState<number | null>(null);
57
- const [editingCommentId, setEditingCommentId] = useState<number | null>(null);
58
-
59
- // 상세 화면 파일 미리보기용 blob URL 상태
60
- const [blobUrls, setBlobUrls] = useState<Array<string>>([]);
61
- const [previewFileNames, setPreviewFileNames] = useState<Array<string>>([]);
62
- const [previewFileTypes, setPreviewFileTypes] = useState<Array<"image" | "pdf" | "unsupported">>([]);
63
-
64
- // 수정 모달 파일 상태
65
- const [pendingFiles, setPendingFiles] = useState<Array<File>>([]);
66
- const [existingFiles, setExistingFiles] = useState<Array<FileResponse>>([]);
67
- const [deleteFileIds, setDeleteFileIds] = useState<Array<number>>([]);
68
- const [isEditUploading, setIsEditUploading] = useState(false);
69
-
70
- const { data: post, isLoading } = useGetPost(postId);
71
- const { data: comments = [] } = useGetComments("POST", postId);
72
- const { mutateAsync: deletePost } = useDeletePost();
73
- const { mutateAsync: deleteComment } = useDeleteComment();
74
- const { mutateAsync: putComment, isPending: isCommentUpdating } = usePutComment();
75
-
76
- const postFiles = post?.files ?? [];
77
- const topComments = comments.filter((c) => c.parentCommentId === null);
78
- const totalCommentCount = countComments(topComments);
79
-
80
- // 첨부파일 blob URL 생성 (FormFile.tsx의 getFiles 패턴)
81
- useEffect(() => {
82
- if (postFiles.length === 0) {
83
- setBlobUrls([]);
84
- setPreviewFileNames([]);
85
- setPreviewFileTypes([]);
86
- return;
87
- }
88
-
89
- let cancelled = false;
90
- const createdUrls: Array<string> = [];
91
-
92
- (async () => {
93
- const results = await Promise.all(
94
- postFiles.map(async (file) => {
95
- try {
96
- const { data: blob } = await apiFileInstance.get(file.filePath, {
97
- responseType: "blob",
98
- });
99
- const url = URL.createObjectURL(blob);
100
- createdUrls.push(url);
101
- return { url, name: file.fileName, type: toPreviewFileType(file.fileType) };
102
- } catch {
103
- return { url: "", name: file.fileName, type: "unsupported" as const };
104
- }
105
- }),
106
- );
107
-
108
- if (!cancelled) {
109
- setBlobUrls(results.map((r) => r.url));
110
- setPreviewFileNames(results.map((r) => r.name));
111
- setPreviewFileTypes(results.map((r) => r.type));
112
- }
113
- })();
114
-
115
- return () => {
116
- cancelled = true;
117
- createdUrls.forEach((url) => url && URL.revokeObjectURL(url));
118
- };
119
- // postFiles 참조가 바뀔 때만 재실행 (길이 + 첫 id로 비교)
120
- // eslint-disable-next-line react-hooks/exhaustive-deps
121
- }, [postFiles.length, postFiles[0]?.id]);
122
-
123
- const filePreview = useFilePreviewViewer(blobUrls);
124
-
125
- const openEditModal = () => {
126
- setPendingFiles([]);
127
- setExistingFiles(post?.files ?? []);
128
- setDeleteFileIds([]);
129
- setIsEditOpen(true);
130
- };
131
-
132
- const closeEditModal = () => {
133
- setIsEditOpen(false);
134
- setPendingFiles([]);
135
- setExistingFiles([]);
136
- setDeleteFileIds([]);
137
- };
138
-
139
- const handleDeleteExistingFile = (fileId: number) => {
140
- setExistingFiles((prev) => prev.filter((f) => f.id !== fileId));
141
- setDeleteFileIds((prev) => [...prev, fileId]);
142
- };
143
-
144
- const handleEdit = async (data: PostFormData) => {
145
- setIsEditUploading(true);
146
- try {
147
- const request = {
148
- title: data.title,
149
- content: data.content,
150
- noticeCategory: data.noticeCategory,
151
- visible: data.visible,
152
- writer: currentUser?.userId ?? "",
153
- deleteFileIds,
154
- };
155
- const formData = new FormData();
156
- formData.append("request", JSON.stringify(request));
157
- pendingFiles.forEach((f) => formData.append("files", f));
158
- await apiFormDataInstance.put(`/posts/${postId}`, formData);
159
- toast.success(COMMON_MESSAGES.UPDATE_SUCCESS);
160
- void queryClient.invalidateQueries({ queryKey: [POST_QUERY_KEY] });
161
- closeEditModal();
162
- } finally {
163
- setIsEditUploading(false);
164
- }
165
- };
166
-
167
- const handleDelete = () => {
168
- if (!post) return;
169
- confirmModal({
170
- content: `"${post.title}" 게시글을 삭제하시겠습니까?`,
171
- onOk: async () => {
172
- await deletePost(postId);
173
- navigate("/post");
174
- },
175
- onCancel: () => {},
176
- className: "max-w-100",
177
- });
178
- };
179
-
180
- const isCommentOwner = (commentUserId: number | null) =>
181
- commentUserId !== null && String(commentUserId) === String(currentUser?.id);
182
-
183
- const handleCommentEditStart = (comment: Comment) => {
184
- if (!isCommentOwner(comment.userId)) {
185
- toast.error("본인의 댓글만 수정할 수 있습니다.");
186
- return;
187
- }
188
- setEditingCommentId(comment.id);
189
- };
190
-
191
- const handleCommentDelete = (commentId: number, commentUserId: number | null) => {
192
- if (!isCommentOwner(commentUserId)) {
193
- toast.error("본인의 댓글만 삭제할 수 있습니다.");
194
- return;
195
- }
196
- confirmModal({
197
- content: "댓글을 삭제하시겠습니까?",
198
- onOk: async () => {
199
- await deleteComment(commentId);
200
- },
201
- onCancel: () => {},
202
- className: "max-w-100",
203
- });
204
- };
205
-
206
- const handleCommentSave = async (commentId: number, content: string, mentionUserIds: Array<number>) => {
207
- await putComment({
208
- commentId,
209
- data: { content, mentionUserIds: mentionUserIds.length > 0 ? mentionUserIds : undefined },
210
- });
211
- setEditingCommentId(null);
212
- };
213
-
214
- const editDefaultValues: PostFormData | undefined = post
215
- ? {
216
- title: post.title,
217
- content: post.content,
218
- noticeCategory: post.noticeCategory,
219
- visible: post.visible ?? true,
220
- }
221
- : undefined;
222
-
223
- const renderCommentActions = (comment: Comment) => {
224
- if (!isCommentOwner(comment.userId)) return null;
225
- return (
226
- <div className="flex shrink-0 items-center gap-0.5">
227
- <Button
228
- type="button"
229
- variant="ghost"
230
- size="icon-sm"
231
- onClick={() => handleCommentEditStart(comment)}
232
- className="cursor-pointer rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-blue-500"
233
- aria-label="댓글 수정"
234
- >
235
- <Pencil size={14} />
236
- </Button>
237
- <Button
238
- type="button"
239
- variant="ghost"
240
- size="icon-sm"
241
- onClick={() => handleCommentDelete(comment.id, comment.userId)}
242
- className="cursor-pointer rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-red-500"
243
- aria-label="댓글 삭제"
244
- >
245
- <Trash2 size={14} />
246
- </Button>
247
- </div>
248
- );
249
- };
250
-
251
- return (
252
- <div className="p-6">
253
- <ListHeader
254
- title="게시글 상세"
255
- rightArea={
256
- <div className="flex items-center gap-2">
257
- <Button variant="outline" onClick={() => navigate("/post")}>
258
- 목록
259
- </Button>
260
- {post && (
261
- <>
262
- <Button variant="save" onClick={openEditModal}>
263
- 수정
264
- </Button>
265
- <Button variant="delete" onClick={handleDelete}>
266
- 삭제
267
- </Button>
268
- </>
269
- )}
270
- </div>
271
- }
272
- />
273
-
274
- <div className="mt-6 space-y-6">
275
- {/* 게시글 - 공지사항 스타일 */}
276
- <div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
277
- {isLoading ? (
278
- <div className="p-8 text-center text-sm text-gray-400">불러오는 중...</div>
279
- ) : post ? (
280
- <>
281
- {/* 제목 + 메타 정보 */}
282
- <div className="border-b border-gray-100 bg-gray-50/50 px-6 py-5">
283
- <h2 className="mb-3 text-xl font-bold leading-tight text-gray-900">{post.title}</h2>
284
- <div className="flex items-center gap-3 text-xs text-gray-500">
285
- <Badge
286
- text={post.visible ? "노출" : "미노출"}
287
- className={`scale-90 ${post.visible ? "bg-green-100 text-green-700 border-green-100" : "bg-gray-100 text-gray-500 border-gray-200"}`}
288
- />
289
- <span className="text-gray-300">|</span>
290
- <span>작성자: {post.writer}</span>
291
- <span className="text-gray-300">|</span>
292
- <span>등록일: {formatDateTime(post.createdAt)}</span>
293
- <span className="text-gray-300">|</span>
294
- <span>수정일: {formatDateTime(post.updatedAt)}</span>
295
- </div>
296
- </div>
297
-
298
- {/* 본문 */}
299
- <div className="min-h-44 px-6 py-6">
300
- <p className="whitespace-pre-wrap text-sm leading-7 text-gray-800">{post.content}</p>
301
- </div>
302
-
303
- {/* 첨부파일 미리보기 뷰어 */}
304
- {postFiles.length > 0 && (
305
- <>
306
- <div className="m-4 grid grid-cols-8 gap-2 w-full">
307
- {postFiles.map((postFile, idx) => (
308
- <FilePreviewCard
309
- key={idx}
310
- src={blobUrls[idx] ?? ""}
311
- fileName={previewFileNames[idx] ?? postFile.fileName}
312
- fileType={previewFileTypes[idx]}
313
- onClick={() => filePreview.open(idx)}
314
- />
315
- ))}
316
- </div>
317
- <FilePreviewViewer
318
- {...filePreview.viewerProps}
319
- fileNames={previewFileNames}
320
- fileTypes={previewFileTypes}
321
- />
322
- </>
323
- )}
324
- </>
325
- ) : (
326
- <div className="p-8 text-center text-sm text-gray-400">게시글을 찾을 수 없습니다.</div>
327
- )}
328
- </div>
329
-
330
- {/* 댓글 섹션 */}
331
- <div className="rounded-xl border border-gray-200 bg-white">
332
- <div className="border-b border-gray-100 px-5 py-3">
333
- <h3 className="text-sm font-semibold text-gray-700">댓글 {totalCommentCount}개</h3>
334
- </div>
335
-
336
- {topComments.length > 0 ? (
337
- <ul className="divide-y divide-gray-100">
338
- {topComments.map((comment) => {
339
- const depth2Replies = comment.replies ?? [];
340
- const isReplying = replyingToId === comment.id;
341
- const isEditing = editingCommentId === comment.id;
342
-
343
- return (
344
- <li key={comment.id}>
345
- {/* depth 1: 원댓글 */}
346
- <div className="flex items-start gap-3 px-5 py-4">
347
- <div className="flex-1 space-y-1">
348
- <div className="flex items-center gap-2">
349
- <span className="text-sm font-semibold text-gray-800">
350
- {comment.userName || "알수없음"}
351
- </span>
352
- <span className="text-xs text-gray-400">{formatDateTime(comment.createdAt)}</span>
353
- </div>
354
- {isEditing ? (
355
- <CommentInput
356
- initialContent={comment.content}
357
- initialMentionUserIds={comment.mentionUserIds ?? []}
358
- onSave={(content, mentionUserIds) =>
359
- handleCommentSave(comment.id, content, mentionUserIds)
360
- }
361
- isSaving={isCommentUpdating}
362
- saveLabel="저장"
363
- onCancel={() => setEditingCommentId(null)}
364
- />
365
- ) : (
366
- <>
367
- <p className="whitespace-pre-wrap text-sm text-gray-700">{comment.content}</p>
368
- {!comment.deletedAt && (
369
- <button
370
- type="button"
371
- onClick={() => setReplyingToId(isReplying ? null : comment.id)}
372
- className="mt-0.5 flex items-center gap-1 text-xs text-gray-400 transition-colors hover:text-blue-500"
373
- >
374
- <CornerDownRight size={11} />
375
- {isReplying ? "취소" : "답글"}
376
- </button>
377
- )}
378
- </>
379
- )}
380
- </div>
381
- {!isEditing && renderCommentActions(comment)}
382
- </div>
383
-
384
- {/* depth 2: 대댓글 목록 */}
385
- {depth2Replies.length > 0 && (
386
- <ul className="border-t border-gray-50 bg-gray-50/60">
387
- {depth2Replies.map((reply) => {
388
- const depth3Replies = reply.replies ?? [];
389
- const isReplyingToReply = replyingToId === reply.id;
390
- const isEditingReply = editingCommentId === reply.id;
391
-
392
- return (
393
- <li key={reply.id} className="border-b border-gray-100 last:border-0">
394
- <div className="flex items-start gap-2.5 py-3 pl-10 pr-5">
395
- <CornerDownRight size={13} className="mt-0.5 shrink-0 text-gray-300" />
396
- <div className="flex-1 space-y-0.5">
397
- <div className="flex items-center gap-2">
398
- <span className="text-sm font-semibold text-gray-800">
399
- {reply.userName || "알수없음"}
400
- </span>
401
- <span className="text-xs text-gray-400">
402
- {formatDateTime(reply.createdAt)}
403
- </span>
404
- </div>
405
- {isEditingReply ? (
406
- <CommentInput
407
- initialContent={reply.content}
408
- initialMentionUserIds={reply.mentionUserIds ?? []}
409
- onSave={(content, mentionUserIds) =>
410
- handleCommentSave(reply.id, content, mentionUserIds)
411
- }
412
- isSaving={isCommentUpdating}
413
- saveLabel="저장"
414
- onCancel={() => setEditingCommentId(null)}
415
- />
416
- ) : (
417
- <>
418
- <p className="whitespace-pre-wrap text-sm text-gray-600">
419
- {reply.content}
420
- </p>
421
- {reply.content !== "삭제된 댓글입니다." && (
422
- <button
423
- type="button"
424
- onClick={() => setReplyingToId(isReplyingToReply ? null : reply.id)}
425
- className="mt-0.5 flex items-center gap-1 text-xs text-gray-400 transition-colors hover:text-blue-500"
426
- >
427
- <CornerDownRight size={11} />
428
- {isReplyingToReply ? "취소" : "답글"}
429
- </button>
430
- )}
431
- </>
432
- )}
433
- </div>
434
- {!isEditingReply && renderCommentActions(reply)}
435
- </div>
436
-
437
- {/* depth 3: 대대댓글 목록 (답글 버튼 없음) */}
438
- {depth3Replies.length > 0 && (
439
- <ul className="bg-gray-100/50">
440
- {depth3Replies.map((deepReply) => {
441
- const isEditingDeepReply = editingCommentId === deepReply.id;
442
- return (
443
- <li
444
- key={deepReply.id}
445
- className="flex items-start gap-2.5 border-b border-gray-100 py-3 pl-16 pr-5 last:border-0"
446
- >
447
- <CornerDownRight
448
- size={13}
449
- className="mt-0.5 shrink-0 text-gray-200"
450
- />
451
- <div className="flex-1 space-y-0.5">
452
- <div className="flex items-center gap-2">
453
- <span className="text-sm font-semibold text-gray-800">
454
- {deepReply.userName || "알수없음"}
455
- </span>
456
- <span className="text-xs text-gray-400">
457
- {formatDateTime(deepReply.createdAt)}
458
- </span>
459
- </div>
460
- {isEditingDeepReply ? (
461
- <CommentInput
462
- initialContent={deepReply.content}
463
- initialMentionUserIds={deepReply.mentionUserIds ?? []}
464
- onSave={(content, mentionUserIds) =>
465
- handleCommentSave(deepReply.id, content, mentionUserIds)
466
- }
467
- isSaving={isCommentUpdating}
468
- saveLabel="저장"
469
- onCancel={() => setEditingCommentId(null)}
470
- />
471
- ) : (
472
- <p className="whitespace-pre-wrap text-sm text-gray-600">
473
- {deepReply.content}
474
- </p>
475
- )}
476
- </div>
477
- {!isEditingDeepReply && renderCommentActions(deepReply)}
478
- </li>
479
- );
480
- })}
481
- </ul>
482
- )}
483
-
484
- {/* depth 2 답글 입력창 */}
485
- {isReplyingToReply && !isEditingReply && (
486
- <div className="border-t border-blue-50 bg-blue-50/30 py-3 pl-10 pr-5">
487
- <CommentInput
488
- targetType="POST"
489
- targetId={postId}
490
- parentCommentId={reply.id}
491
- placeholder="답글을 입력하세요. @를 입력하면 사용자를 멘션할 수 있습니다."
492
- onSuccess={() => setReplyingToId(null)}
493
- />
494
- </div>
495
- )}
496
- </li>
497
- );
498
- })}
499
- </ul>
500
- )}
501
-
502
- {/* depth 1 답글 입력창 */}
503
- {isReplying && !isEditing && (
504
- <div className="border-t border-blue-50 bg-blue-50/30 py-3 pl-10 pr-5">
505
- <CommentInput
506
- targetType="POST"
507
- targetId={postId}
508
- parentCommentId={comment.id}
509
- placeholder="답글을 입력하세요. @를 입력하면 사용자를 멘션할 수 있습니다."
510
- onSuccess={() => setReplyingToId(null)}
511
- />
512
- </div>
513
- )}
514
- </li>
515
- );
516
- })}
517
- </ul>
518
- ) : (
519
- <div className="px-5 py-6 text-center text-sm text-gray-400">등록된 댓글이 없습니다.</div>
520
- )}
521
-
522
- {/* 최상위 댓글 입력창 */}
523
- <div className="border-t border-gray-100 px-5 py-4">
524
- <CommentInput targetType="POST" targetId={postId} parentCommentId={null} />
525
- </div>
526
- </div>
527
- </div>
528
-
529
- {/* 수정 모달 */}
530
- <PostFormModal
531
- mode="edit"
532
- isOpen={isEditOpen}
533
- onClose={closeEditModal}
534
- defaultValues={editDefaultValues}
535
- onSubmit={handleEdit}
536
- isPending={isEditUploading}
537
- pendingFiles={pendingFiles}
538
- onPendingFilesChange={setPendingFiles}
539
- existingFiles={existingFiles}
540
- onDeleteExistingFile={handleDeleteExistingFile}
541
- formKey={postId}
542
- />
543
- </div>
544
- );
545
- }
1
+ import { useEffect, useState } from "react";
2
+ import { useNavigate, useParams } from "react-router";
3
+ import { useQueryClient } from "@tanstack/react-query";
4
+
5
+ import { useUserStore } from "@/app/store";
6
+ import {
7
+ Badge,
8
+ Button,
9
+ confirmModal,
10
+ FilePreviewViewer,
11
+ toast,
12
+ useFilePreviewViewer,
13
+ } from "@farmzone/fz-react-ui";
14
+ import { CornerDownRight, Pencil, Trash2 } from "lucide-react";
15
+
16
+ import {
17
+ useDeleteComment,
18
+ useDeletePost,
19
+ useGetComments,
20
+ useGetPost,
21
+ usePutComment,
22
+ } from "@/app/api/queries";
23
+ import type { Comment, FileResponse } from "@/types";
24
+ import { apiFileInstance, apiFormDataInstance } from "@/app/api/api";
25
+ import { POST_QUERY_KEY } from "@/app/api/queryKey";
26
+ import ListHeader from "@/app/layout/ListHeader";
27
+ import CommentInput from "@/shared/components/CommentInput";
28
+ import { COMMON_MESSAGES } from "@/shared/config/text";
29
+ import { formatDateTime } from "@/shared/utils/format";
30
+ import { PostFormModal } from "../PostFormModal";
31
+ import type { PostFormData } from "../PostFormModal";
32
+ import FilePreviewCard from "@/shared/components/FilePreviewCard";
33
+
34
+ function countComments(list: Array<Comment>): number {
35
+ return list.reduce((sum, c) => {
36
+ const depth2 = c.replies ?? [];
37
+ const depth3Count = depth2.reduce((s, r) => s + (r.replies?.length ?? 0), 0);
38
+ return sum + 1 + depth2.length + depth3Count;
39
+ }, 0);
40
+ }
41
+
42
+ function toPreviewFileType(mimeType: string): "image" | "pdf" | "unsupported" {
43
+ if (mimeType?.startsWith("image/")) return "image";
44
+ if (mimeType === "application/pdf") return "pdf";
45
+ return "unsupported";
46
+ }
47
+
48
+ export default function PostDetailPage() {
49
+ const { id } = useParams<{ id: string }>();
50
+ const postId = Number(id);
51
+ const navigate = useNavigate();
52
+ const queryClient = useQueryClient();
53
+ const currentUser = useUserStore((s) => s.user);
54
+
55
+ const [isEditOpen, setIsEditOpen] = useState(false);
56
+ const [replyingToId, setReplyingToId] = useState<number | null>(null);
57
+ const [editingCommentId, setEditingCommentId] = useState<number | null>(null);
58
+
59
+ // 상세 화면 파일 미리보기용 blob URL 상태
60
+ const [blobUrls, setBlobUrls] = useState<Array<string>>([]);
61
+ const [previewFileNames, setPreviewFileNames] = useState<Array<string>>([]);
62
+ const [previewFileTypes, setPreviewFileTypes] = useState<Array<"image" | "pdf" | "unsupported">>([]);
63
+
64
+ // 수정 모달 파일 상태
65
+ const [pendingFiles, setPendingFiles] = useState<Array<File>>([]);
66
+ const [existingFiles, setExistingFiles] = useState<Array<FileResponse>>([]);
67
+ const [deleteFileIds, setDeleteFileIds] = useState<Array<number>>([]);
68
+ const [isEditUploading, setIsEditUploading] = useState(false);
69
+
70
+ const { data: post, isLoading } = useGetPost(postId);
71
+ const { data: comments = [] } = useGetComments("POST", postId);
72
+ const { mutateAsync: deletePost } = useDeletePost();
73
+ const { mutateAsync: deleteComment } = useDeleteComment();
74
+ const { mutateAsync: putComment, isPending: isCommentUpdating } = usePutComment();
75
+
76
+ const postFiles = post?.files ?? [];
77
+ const topComments = comments.filter((c) => c.parentCommentId === null);
78
+ const totalCommentCount = countComments(topComments);
79
+
80
+ // 첨부파일 blob URL 생성 (FormFile.tsx의 getFiles 패턴)
81
+ useEffect(() => {
82
+ if (postFiles.length === 0) {
83
+ setBlobUrls([]);
84
+ setPreviewFileNames([]);
85
+ setPreviewFileTypes([]);
86
+ return;
87
+ }
88
+
89
+ let cancelled = false;
90
+ const createdUrls: Array<string> = [];
91
+
92
+ (async () => {
93
+ const results = await Promise.all(
94
+ postFiles.map(async (file) => {
95
+ try {
96
+ const { data: blob } = await apiFileInstance.get(file.filePath, {
97
+ responseType: "blob",
98
+ });
99
+ const url = URL.createObjectURL(blob);
100
+ createdUrls.push(url);
101
+ return { url, name: file.fileName, type: toPreviewFileType(file.fileType) };
102
+ } catch {
103
+ return { url: "", name: file.fileName, type: "unsupported" as const };
104
+ }
105
+ }),
106
+ );
107
+
108
+ if (!cancelled) {
109
+ setBlobUrls(results.map((r) => r.url));
110
+ setPreviewFileNames(results.map((r) => r.name));
111
+ setPreviewFileTypes(results.map((r) => r.type));
112
+ }
113
+ })();
114
+
115
+ return () => {
116
+ cancelled = true;
117
+ createdUrls.forEach((url) => url && URL.revokeObjectURL(url));
118
+ };
119
+ // postFiles 참조가 바뀔 때만 재실행 (길이 + 첫 id로 비교)
120
+ // eslint-disable-next-line react-hooks/exhaustive-deps
121
+ }, [postFiles.length, postFiles[0]?.id]);
122
+
123
+ const filePreview = useFilePreviewViewer(blobUrls);
124
+
125
+ const openEditModal = () => {
126
+ setPendingFiles([]);
127
+ setExistingFiles(post?.files ?? []);
128
+ setDeleteFileIds([]);
129
+ setIsEditOpen(true);
130
+ };
131
+
132
+ const closeEditModal = () => {
133
+ setIsEditOpen(false);
134
+ setPendingFiles([]);
135
+ setExistingFiles([]);
136
+ setDeleteFileIds([]);
137
+ };
138
+
139
+ const handleDeleteExistingFile = (fileId: number) => {
140
+ setExistingFiles((prev) => prev.filter((f) => f.id !== fileId));
141
+ setDeleteFileIds((prev) => [...prev, fileId]);
142
+ };
143
+
144
+ const handleEdit = async (data: PostFormData) => {
145
+ setIsEditUploading(true);
146
+ try {
147
+ const request = {
148
+ title: data.title,
149
+ content: data.content,
150
+ noticeCategory: data.noticeCategory,
151
+ visible: data.visible,
152
+ writer: currentUser?.userId ?? "",
153
+ deleteFileIds,
154
+ };
155
+ const formData = new FormData();
156
+ formData.append("request", JSON.stringify(request));
157
+ pendingFiles.forEach((f) => formData.append("files", f));
158
+ await apiFormDataInstance.put(`/posts/${postId}`, formData);
159
+ toast.success(COMMON_MESSAGES.UPDATE_SUCCESS);
160
+ void queryClient.invalidateQueries({ queryKey: [POST_QUERY_KEY] });
161
+ closeEditModal();
162
+ } finally {
163
+ setIsEditUploading(false);
164
+ }
165
+ };
166
+
167
+ const handleDelete = () => {
168
+ if (!post) return;
169
+ confirmModal({
170
+ content: `"${post.title}" 게시글을 삭제하시겠습니까?`,
171
+ onOk: async () => {
172
+ await deletePost(postId);
173
+ navigate("/post");
174
+ },
175
+ onCancel: () => {},
176
+ className: "max-w-100",
177
+ });
178
+ };
179
+
180
+ const isCommentOwner = (commentUserId: number | null) =>
181
+ commentUserId !== null && String(commentUserId) === String(currentUser?.id);
182
+
183
+ const handleCommentEditStart = (comment: Comment) => {
184
+ if (!isCommentOwner(comment.userId)) {
185
+ toast.error("본인의 댓글만 수정할 수 있습니다.");
186
+ return;
187
+ }
188
+ setEditingCommentId(comment.id);
189
+ };
190
+
191
+ const handleCommentDelete = (commentId: number, commentUserId: number | null) => {
192
+ if (!isCommentOwner(commentUserId)) {
193
+ toast.error("본인의 댓글만 삭제할 수 있습니다.");
194
+ return;
195
+ }
196
+ confirmModal({
197
+ content: "댓글을 삭제하시겠습니까?",
198
+ onOk: async () => {
199
+ await deleteComment(commentId);
200
+ },
201
+ onCancel: () => {},
202
+ className: "max-w-100",
203
+ });
204
+ };
205
+
206
+ const handleCommentSave = async (commentId: number, content: string, mentionUserIds: Array<number>) => {
207
+ await putComment({
208
+ commentId,
209
+ data: { content, mentionUserIds: mentionUserIds.length > 0 ? mentionUserIds : undefined },
210
+ });
211
+ setEditingCommentId(null);
212
+ };
213
+
214
+ const editDefaultValues: PostFormData | undefined = post
215
+ ? {
216
+ title: post.title,
217
+ content: post.content,
218
+ noticeCategory: post.noticeCategory,
219
+ visible: post.visible ?? true,
220
+ }
221
+ : undefined;
222
+
223
+ const renderCommentActions = (comment: Comment) => {
224
+ if (!isCommentOwner(comment.userId)) return null;
225
+ return (
226
+ <div className="flex shrink-0 items-center gap-0.5">
227
+ <Button
228
+ type="button"
229
+ variant="ghost"
230
+ size="icon-sm"
231
+ onClick={() => handleCommentEditStart(comment)}
232
+ className="cursor-pointer rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-blue-500"
233
+ aria-label="댓글 수정"
234
+ >
235
+ <Pencil size={14} />
236
+ </Button>
237
+ <Button
238
+ type="button"
239
+ variant="ghost"
240
+ size="icon-sm"
241
+ onClick={() => handleCommentDelete(comment.id, comment.userId)}
242
+ className="cursor-pointer rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-red-500"
243
+ aria-label="댓글 삭제"
244
+ >
245
+ <Trash2 size={14} />
246
+ </Button>
247
+ </div>
248
+ );
249
+ };
250
+
251
+ return (
252
+ <div className="p-6">
253
+ <ListHeader
254
+ title="게시글 상세"
255
+ rightArea={
256
+ <div className="flex items-center gap-2">
257
+ <Button variant="outline" onClick={() => navigate("/post")}>
258
+ 목록
259
+ </Button>
260
+ {post && (
261
+ <>
262
+ <Button variant="save" onClick={openEditModal}>
263
+ 수정
264
+ </Button>
265
+ <Button variant="delete" onClick={handleDelete}>
266
+ 삭제
267
+ </Button>
268
+ </>
269
+ )}
270
+ </div>
271
+ }
272
+ />
273
+
274
+ <div className="mt-6 space-y-6">
275
+ {/* 게시글 - 공지사항 스타일 */}
276
+ <div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
277
+ {isLoading ? (
278
+ <div className="p-8 text-center text-sm text-gray-400">불러오는 중...</div>
279
+ ) : post ? (
280
+ <>
281
+ {/* 제목 + 메타 정보 */}
282
+ <div className="border-b border-gray-100 bg-gray-50/50 px-6 py-5">
283
+ <h2 className="mb-3 text-xl font-bold leading-tight text-gray-900">{post.title}</h2>
284
+ <div className="flex items-center gap-3 text-xs text-gray-500">
285
+ <Badge
286
+ text={post.visible ? "노출" : "미노출"}
287
+ className={`scale-90 ${post.visible ? "bg-green-100 text-green-700 border-green-100" : "bg-gray-100 text-gray-500 border-gray-200"}`}
288
+ />
289
+ <span className="text-gray-300">|</span>
290
+ <span>작성자: {post.writer}</span>
291
+ <span className="text-gray-300">|</span>
292
+ <span>등록일: {formatDateTime(post.createdAt)}</span>
293
+ <span className="text-gray-300">|</span>
294
+ <span>수정일: {formatDateTime(post.updatedAt)}</span>
295
+ </div>
296
+ </div>
297
+
298
+ {/* 본문 */}
299
+ <div className="min-h-44 px-6 py-6">
300
+ <p className="whitespace-pre-wrap text-sm leading-7 text-gray-800">{post.content}</p>
301
+ </div>
302
+
303
+ {/* 첨부파일 미리보기 뷰어 */}
304
+ {postFiles.length > 0 && (
305
+ <>
306
+ <div className="m-4 grid grid-cols-8 gap-2 w-full">
307
+ {postFiles.map((postFile, idx) => (
308
+ <FilePreviewCard
309
+ key={idx}
310
+ src={blobUrls[idx] ?? ""}
311
+ fileName={previewFileNames[idx] ?? postFile.fileName}
312
+ fileType={previewFileTypes[idx]}
313
+ onClick={() => filePreview.open(idx)}
314
+ />
315
+ ))}
316
+ </div>
317
+ <FilePreviewViewer
318
+ {...filePreview.viewerProps}
319
+ fileNames={previewFileNames}
320
+ fileTypes={previewFileTypes}
321
+ />
322
+ </>
323
+ )}
324
+ </>
325
+ ) : (
326
+ <div className="p-8 text-center text-sm text-gray-400">게시글을 찾을 수 없습니다.</div>
327
+ )}
328
+ </div>
329
+
330
+ {/* 댓글 섹션 */}
331
+ <div className="rounded-xl border border-gray-200 bg-white">
332
+ <div className="border-b border-gray-100 px-5 py-3">
333
+ <h3 className="text-sm font-semibold text-gray-700">댓글 {totalCommentCount}개</h3>
334
+ </div>
335
+
336
+ {topComments.length > 0 ? (
337
+ <ul className="divide-y divide-gray-100">
338
+ {topComments.map((comment) => {
339
+ const depth2Replies = comment.replies ?? [];
340
+ const isReplying = replyingToId === comment.id;
341
+ const isEditing = editingCommentId === comment.id;
342
+
343
+ return (
344
+ <li key={comment.id}>
345
+ {/* depth 1: 원댓글 */}
346
+ <div className="flex items-start gap-3 px-5 py-4">
347
+ <div className="flex-1 space-y-1">
348
+ <div className="flex items-center gap-2">
349
+ <span className="text-sm font-semibold text-gray-800">
350
+ {comment.userName || "알수없음"}
351
+ </span>
352
+ <span className="text-xs text-gray-400">{formatDateTime(comment.createdAt)}</span>
353
+ </div>
354
+ {isEditing ? (
355
+ <CommentInput
356
+ initialContent={comment.content}
357
+ initialMentionUserIds={comment.mentionUserIds ?? []}
358
+ onSave={(content, mentionUserIds) =>
359
+ handleCommentSave(comment.id, content, mentionUserIds)
360
+ }
361
+ isSaving={isCommentUpdating}
362
+ saveLabel="저장"
363
+ onCancel={() => setEditingCommentId(null)}
364
+ />
365
+ ) : (
366
+ <>
367
+ <p className="whitespace-pre-wrap text-sm text-gray-700">{comment.content}</p>
368
+ {!comment.deletedAt && (
369
+ <button
370
+ type="button"
371
+ onClick={() => setReplyingToId(isReplying ? null : comment.id)}
372
+ className="mt-0.5 flex items-center gap-1 text-xs text-gray-400 transition-colors hover:text-blue-500"
373
+ >
374
+ <CornerDownRight size={11} />
375
+ {isReplying ? "취소" : "답글"}
376
+ </button>
377
+ )}
378
+ </>
379
+ )}
380
+ </div>
381
+ {!isEditing && renderCommentActions(comment)}
382
+ </div>
383
+
384
+ {/* depth 2: 대댓글 목록 */}
385
+ {depth2Replies.length > 0 && (
386
+ <ul className="border-t border-gray-50 bg-gray-50/60">
387
+ {depth2Replies.map((reply) => {
388
+ const depth3Replies = reply.replies ?? [];
389
+ const isReplyingToReply = replyingToId === reply.id;
390
+ const isEditingReply = editingCommentId === reply.id;
391
+
392
+ return (
393
+ <li key={reply.id} className="border-b border-gray-100 last:border-0">
394
+ <div className="flex items-start gap-2.5 py-3 pl-10 pr-5">
395
+ <CornerDownRight size={13} className="mt-0.5 shrink-0 text-gray-300" />
396
+ <div className="flex-1 space-y-0.5">
397
+ <div className="flex items-center gap-2">
398
+ <span className="text-sm font-semibold text-gray-800">
399
+ {reply.userName || "알수없음"}
400
+ </span>
401
+ <span className="text-xs text-gray-400">
402
+ {formatDateTime(reply.createdAt)}
403
+ </span>
404
+ </div>
405
+ {isEditingReply ? (
406
+ <CommentInput
407
+ initialContent={reply.content}
408
+ initialMentionUserIds={reply.mentionUserIds ?? []}
409
+ onSave={(content, mentionUserIds) =>
410
+ handleCommentSave(reply.id, content, mentionUserIds)
411
+ }
412
+ isSaving={isCommentUpdating}
413
+ saveLabel="저장"
414
+ onCancel={() => setEditingCommentId(null)}
415
+ />
416
+ ) : (
417
+ <>
418
+ <p className="whitespace-pre-wrap text-sm text-gray-600">
419
+ {reply.content}
420
+ </p>
421
+ {reply.content !== "삭제된 댓글입니다." && (
422
+ <button
423
+ type="button"
424
+ onClick={() => setReplyingToId(isReplyingToReply ? null : reply.id)}
425
+ className="mt-0.5 flex items-center gap-1 text-xs text-gray-400 transition-colors hover:text-blue-500"
426
+ >
427
+ <CornerDownRight size={11} />
428
+ {isReplyingToReply ? "취소" : "답글"}
429
+ </button>
430
+ )}
431
+ </>
432
+ )}
433
+ </div>
434
+ {!isEditingReply && renderCommentActions(reply)}
435
+ </div>
436
+
437
+ {/* depth 3: 대대댓글 목록 (답글 버튼 없음) */}
438
+ {depth3Replies.length > 0 && (
439
+ <ul className="bg-gray-100/50">
440
+ {depth3Replies.map((deepReply) => {
441
+ const isEditingDeepReply = editingCommentId === deepReply.id;
442
+ return (
443
+ <li
444
+ key={deepReply.id}
445
+ className="flex items-start gap-2.5 border-b border-gray-100 py-3 pl-16 pr-5 last:border-0"
446
+ >
447
+ <CornerDownRight
448
+ size={13}
449
+ className="mt-0.5 shrink-0 text-gray-200"
450
+ />
451
+ <div className="flex-1 space-y-0.5">
452
+ <div className="flex items-center gap-2">
453
+ <span className="text-sm font-semibold text-gray-800">
454
+ {deepReply.userName || "알수없음"}
455
+ </span>
456
+ <span className="text-xs text-gray-400">
457
+ {formatDateTime(deepReply.createdAt)}
458
+ </span>
459
+ </div>
460
+ {isEditingDeepReply ? (
461
+ <CommentInput
462
+ initialContent={deepReply.content}
463
+ initialMentionUserIds={deepReply.mentionUserIds ?? []}
464
+ onSave={(content, mentionUserIds) =>
465
+ handleCommentSave(deepReply.id, content, mentionUserIds)
466
+ }
467
+ isSaving={isCommentUpdating}
468
+ saveLabel="저장"
469
+ onCancel={() => setEditingCommentId(null)}
470
+ />
471
+ ) : (
472
+ <p className="whitespace-pre-wrap text-sm text-gray-600">
473
+ {deepReply.content}
474
+ </p>
475
+ )}
476
+ </div>
477
+ {!isEditingDeepReply && renderCommentActions(deepReply)}
478
+ </li>
479
+ );
480
+ })}
481
+ </ul>
482
+ )}
483
+
484
+ {/* depth 2 답글 입력창 */}
485
+ {isReplyingToReply && !isEditingReply && (
486
+ <div className="border-t border-blue-50 bg-blue-50/30 py-3 pl-10 pr-5">
487
+ <CommentInput
488
+ targetType="POST"
489
+ targetId={postId}
490
+ parentCommentId={reply.id}
491
+ placeholder="답글을 입력하세요. @를 입력하면 사용자를 멘션할 수 있습니다."
492
+ onSuccess={() => setReplyingToId(null)}
493
+ />
494
+ </div>
495
+ )}
496
+ </li>
497
+ );
498
+ })}
499
+ </ul>
500
+ )}
501
+
502
+ {/* depth 1 답글 입력창 */}
503
+ {isReplying && !isEditing && (
504
+ <div className="border-t border-blue-50 bg-blue-50/30 py-3 pl-10 pr-5">
505
+ <CommentInput
506
+ targetType="POST"
507
+ targetId={postId}
508
+ parentCommentId={comment.id}
509
+ placeholder="답글을 입력하세요. @를 입력하면 사용자를 멘션할 수 있습니다."
510
+ onSuccess={() => setReplyingToId(null)}
511
+ />
512
+ </div>
513
+ )}
514
+ </li>
515
+ );
516
+ })}
517
+ </ul>
518
+ ) : (
519
+ <div className="px-5 py-6 text-center text-sm text-gray-400">등록된 댓글이 없습니다.</div>
520
+ )}
521
+
522
+ {/* 최상위 댓글 입력창 */}
523
+ <div className="border-t border-gray-100 px-5 py-4">
524
+ <CommentInput targetType="POST" targetId={postId} parentCommentId={null} />
525
+ </div>
526
+ </div>
527
+ </div>
528
+
529
+ {/* 수정 모달 */}
530
+ <PostFormModal
531
+ mode="edit"
532
+ isOpen={isEditOpen}
533
+ onClose={closeEditModal}
534
+ defaultValues={editDefaultValues}
535
+ onSubmit={handleEdit}
536
+ isPending={isEditUploading}
537
+ pendingFiles={pendingFiles}
538
+ onPendingFilesChange={setPendingFiles}
539
+ existingFiles={existingFiles}
540
+ onDeleteExistingFile={handleDeleteExistingFile}
541
+ formKey={postId}
542
+ />
543
+ </div>
544
+ );
545
+ }