Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/features/topics/components/ConfirmModalTopicCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { useRef } from 'react'

import { cn } from '@/shared/lib/utils'
import { Badge, Card } from '@/shared/ui'
import { NumberedCheckbox } from '@/shared/ui/NumberedCheckbox'

type ConfirmModalTopicCardProps = {
title: string
topicTypeLabel: string
description: string
createdByNickname: string
topicId: number
isSelected: boolean
}

export default function ConfirmModalTopicCard({
title,
topicTypeLabel,
description,
createdByNickname,
topicId,
isSelected,
}: ConfirmModalTopicCardProps) {
const checkboxRef = useRef<HTMLButtonElement>(null)

return (
<div className="cursor-pointer" onClick={() => checkboxRef.current?.click()}>
<Card
className={cn('flex gap-small items-start p-medium', isSelected && 'border-primary-200')}
>
<div className="flex items-center" onClick={(e) => e.stopPropagation()}>
<NumberedCheckbox id={topicId.toString()} ref={checkboxRef} />
</div>
<div className="flex flex-col gap-small flex-1">
<div className="flex justify-between items-start">
<div className="flex gap-xsmall items-center">
<p className="text-black typo-subtitle3">{title}</p>
<Badge size="small" color="grey">
{topicTypeLabel}
</Badge>
</div>
</div>
<p className="typo-body4 text-grey-700">{description}</p>
<p className="typo-body6 text-grey-600">제안 : {createdByNickname}</p>
</div>
</Card>
</div>
)
}
143 changes: 143 additions & 0 deletions src/features/topics/components/ConfirmTopicModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { useState } from 'react'

import { ConfirmModalTopicCard, TopicListSkeleton } from '@/features/topics/components'
import { useConfirmTopics, useProposedTopics } from '@/features/topics/hooks'
import {
Button,
Modal,
ModalBody,
ModalContent,
ModalFooter,
ModalHeader,
ModalTitle,
TextButton,
} from '@/shared/ui'
import { NumberedCheckboxGroup } from '@/shared/ui/NumberedCheckbox'
import { useGlobalModalStore } from '@/store'

export type ConfirmTopicModalProps = {
/** 모달 열림 상태 */
open: boolean
/** 모달 열림 상태 변경 핸들러 */
onOpenChange: (open: boolean) => void
gatheringId: number
meetingId: number
}

export default function ConfirmTopicModal({
open,
onOpenChange,
gatheringId,
meetingId,
}: ConfirmTopicModalProps) {
const [selectedTopicIds, setSelectedTopicIds] = useState<string[]>([])

const { openConfirm, openError } = useGlobalModalStore()
const confirmMutation = useConfirmTopics()

// 모달 전용 독립 데이터 - 한 번에 전체 로드 (pageSize 크게)
const { data: topicsInfiniteData, isLoading } = useProposedTopics({
gatheringId,
meetingId,
pageSize: 100,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

한 번에 전체 로드하게 하신 이유가 있나요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기는 초기로딩 길더라도 한번에 보여줘야 UX가 좋을 것 같아서 한번에 로드했습니다
찔끔찔끔 보이면 순서 정할때 답답할것 같아서요! 다른 아이디어나 의견있으면 말씀주십셔~

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

목데이터는 전체 개발 마무리되면 모두 제거하고
실제 api연동하고 테스트 해 볼 예정이었는데
아래 영애님 말대로 목데이터를 어떻게 관리할지 정해봐야겠어요~!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

무한스크롤 훅을 사용하는게 좋을까 했는데 무한 스크롤 훅이 모달에 대응하고 있지 않은 상태네요.
아직 주제는 그렇게 많이 등록되지 않는다는 가정 하에 현재는 이렇게만 하고,
추후 리팩토링 시 적용할 수 있으면 하시죠!

})

const topics = topicsInfiniteData?.pages.flatMap((page) => page.items) ?? []

const resetSelected = () => {
setSelectedTopicIds([])
}

const handleClose = () => {
resetSelected()
onOpenChange(false)
}

const handleConfirm = async () => {
const confirmed = await openConfirm(
'주제 확정',
`한 번 확정하면 이후에는 순서를 바꾸거나 주제를 추가하기 어려워요. \n이대로 확정할까요?`,
{ confirmText: '확정하기' }
)

if (!confirmed) return

confirmMutation.mutate(
{
gatheringId,
meetingId,
topicIds: selectedTopicIds.map(Number),
},
{
onSuccess: () => {
handleClose()
},
onError: (error) => {
openError('확정 실패', error.userMessage)
},
}
)
}

return (
<Modal open={open} onOpenChange={handleClose}>
<ModalContent variant="wide" onInteractOutside={(e) => e.preventDefault()}>
<ModalHeader className="items-start">
<ModalTitle>
<div className="flex flex-col gap-base">
<p>주제 확정하기</p>
<div className="flex justify-between items-center">
<p className="typo-subtitle4 text-grey-600">확정할 주제를 순서대로 선택해주세요</p>
{selectedTopicIds.length > 0 && (
<TextButton className="-mr-base" onClick={resetSelected}>
전체해제
</TextButton>
)}
</div>
</div>
</ModalTitle>
</ModalHeader>

<ModalBody className="flex flex-col gap-base">
{isLoading ? (
<TopicListSkeleton count={5} />
) : (
<NumberedCheckboxGroup
value={selectedTopicIds}
onChange={setSelectedTopicIds}
className="flex flex-col gap-small"
>
{topics.map((topic) => (
<ConfirmModalTopicCard
key={topic.topicId}
title={topic.title}
topicTypeLabel={topic.topicTypeLabel}
description={topic.description}
createdByNickname={topic.createdByInfo.nickname}
topicId={topic.topicId}
isSelected={selectedTopicIds.includes(topic.topicId.toString())}
/>
))}
</NumberedCheckboxGroup>
)}
</ModalBody>

<ModalFooter>
<div className="flex gap-large justify-between items-start flex-1">
<p className="typo-body4 text-grey-700 shrink-0">
선택 <span className="typo-body3 text-black">{selectedTopicIds.length}</span>개
</p>
<Button
size="medium"
className="w-full"
disabled={selectedTopicIds.length === 0 || confirmMutation.isPending}
onClick={handleConfirm}
>
확정하기
</Button>
</div>
</ModalFooter>
</ModalContent>
</Modal>
)
}
6 changes: 4 additions & 2 deletions src/features/topics/components/TopicHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ type ProposedHeaderProps = {
actions: { canConfirm: boolean; canSuggest: boolean }
confirmedTopic: boolean
confirmedTopicDate: string | null
proposedTopicsCount: number
onOpenChange: (open: boolean) => void
}

type ConfirmedHeaderProps = {
Expand Down Expand Up @@ -50,8 +52,8 @@ export default function TopicHeader(props: TopicHeaderProps) {
</div>

<div className="flex gap-xsmall">
{props.actions.canConfirm && (
<Button variant="secondary" outline>
{props.actions.canConfirm && props.proposedTopicsCount > 0 && (
<Button variant="secondary" outline onClick={() => props.onOpenChange(true)}>
주제 확정하기
</Button>
)}
Expand Down
2 changes: 2 additions & 0 deletions src/features/topics/components/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export { default as ConfirmedTopicList } from './ConfirmedTopicList'
export { default as ConfirmModalTopicCard } from './ConfirmModalTopicCard'
export { default as ConfirmTopicModal } from './ConfirmTopicModal'
export { default as DefaultTopicCard } from './DefaultTopicCard'
export { default as EmptyTopicList } from './EmptyTopicList'
export { default as ProposedTopicList } from './ProposedTopicList'
Expand Down
1 change: 1 addition & 0 deletions src/features/topics/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './topicQueryKeys'
export * from './useConfirmedTopics'
export * from './useConfirmTopics'
export * from './useCreateTopic'
export * from './useDeleteTopic'
export * from './useLikeTopic'
Expand Down
60 changes: 60 additions & 0 deletions src/features/topics/hooks/useConfirmTopics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* @file useConfirmTopics.ts
* @description 주제 확정 mutation 훅
*/

import { useMutation, useQueryClient } from '@tanstack/react-query'

import { ApiError } from '@/api/errors'

import { confirmTopics } from '../topics.api'
import type { ConfirmTopicsParams, ConfirmTopicsResponse } from '../topics.types'
import { topicQueryKeys } from './topicQueryKeys'

/**
* 주제 확정 mutation 훅
*
* @description
* 선택한 주제들을 순서대로 확정하고 관련 쿼리 캐시를 무효화합니다.
* - 제안된 주제 리스트 캐시 무효화
* - 확정된 주제 리스트 캐시 무효화
*
* @example
* ```tsx
* const confirmMutation = useConfirmTopics()
* confirmMutation.mutate(
* { gatheringId: 1, meetingId: 2, topicIds: [3, 1, 2] },
* {
* onSuccess: () => {
* console.log('주제가 확정되었습니다.')
* },
* onError: (error) => {
* console.error('확정 실패:', error.userMessage)
* },
* }
* )
* ```
*/
export const useConfirmTopics = () => {
const queryClient = useQueryClient()

return useMutation<ConfirmTopicsResponse, ApiError, ConfirmTopicsParams>({
mutationFn: (params: ConfirmTopicsParams) => confirmTopics(params),
onSuccess: (_, variables) => {
// 제안된 주제 무효화
queryClient.invalidateQueries({
queryKey: topicQueryKeys.proposedList({
gatheringId: variables.gatheringId,
meetingId: variables.meetingId,
}),
})
// 확정된 주제 무효화
queryClient.invalidateQueries({
queryKey: topicQueryKeys.confirmedList({
gatheringId: variables.gatheringId,
meetingId: variables.meetingId,
}),
})
},
})
}
36 changes: 35 additions & 1 deletion src/features/topics/topics.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import { api } from '@/api/client'
import { PAGE_SIZES } from '@/shared/constants'

import { TOPICS_ENDPOINTS } from './topics.endpoints'
import { getMockConfirmedTopics, getMockProposedTopics } from './topics.mock'
import { getMockConfirmedTopics, getMockConfirmTopics, getMockProposedTopics } from './topics.mock'
import type {
ConfirmTopicsParams,
ConfirmTopicsResponse,
CreateTopicParams,
CreateTopicResponse,
DeleteTopicParams,
Expand Down Expand Up @@ -211,3 +213,35 @@ export const likeTopicToggle = async (params: LikeTopicParams): Promise<LikeTopi
// 실제 API 호출 (로그인 완료 후 사용)
return api.post<LikeTopicResponse>(TOPICS_ENDPOINTS.LIKE_TOGGLE(gatheringId, meetingId, topicId))
}

/**
* 주제 확정
*
* @description
* 선택한 주제들을 순서대로 확정합니다.
*
* @param params - 확정 파라미터
* @param params.gatheringId - 모임 식별자
* @param params.meetingId - 약속 식별자
* @param params.topicIds - 확정할 주제 ID 목록 (순서대로)
*
* @returns 확정된 주제 정보
*/
export const confirmTopics = async (
params: ConfirmTopicsParams
): Promise<ConfirmTopicsResponse> => {
const { gatheringId, meetingId, topicIds } = params

// 🚧 임시: 로그인 기능 개발 전까지 목데이터 사용
// TODO: 로그인 완료 후 아래 주석을 해제하고 목데이터 로직 제거
if (USE_MOCK_DATA) {
// 실제 API 호출을 시뮬레이션하기 위한 지연
await new Promise((resolve) => setTimeout(resolve, 500))
return getMockConfirmTopics(meetingId, topicIds)
}

// 실제 API 호출 (로그인 완료 후 사용)
return api.post<ConfirmTopicsResponse>(TOPICS_ENDPOINTS.CONFIRM(gatheringId, meetingId), {
topicIds,
})
}
3 changes: 3 additions & 0 deletions src/features/topics/topics.endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ export const TOPICS_ENDPOINTS = {
LIKE_TOGGLE: (gatheringId: number, meetingId: number, topicId: number) =>
`${API_PATHS.GATHERINGS}/${gatheringId}/meetings/${meetingId}/topics/${topicId}/likes`,

// 주제 확정 (POST /api/gatherings/{gatheringId}/meetings/{meetingId}/topics/confirm)
CONFIRM: (gatheringId: number, meetingId: number) =>
`${API_PATHS.GATHERINGS}/${gatheringId}/meetings/${meetingId}/topics/confirm`,
// 주제 제안 (POST /api/gatherings/{gatheringId}/meetings/{meetingId}/topics)
CREATE: (gatheringId: number, meetingId: number) =>
`${API_PATHS.GATHERINGS}/${gatheringId}/meetings/${meetingId}/topics`,
Expand Down
23 changes: 22 additions & 1 deletion src/features/topics/topics.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import type {
ConfirmedTopicItem,
ConfirmTopicsResponse,
GetConfirmedTopicsResponse,
GetProposedTopicsResponse,
ProposedTopicItem,
Expand Down Expand Up @@ -435,7 +436,7 @@ export const getMockProposedTopics = (
nextCursor,
totalCount: cursorLikeCount === undefined ? mockProposedTopics.length : undefined,
actions: {
canConfirm: false,
canConfirm: true,
canSuggest: true,
},
}
Expand Down Expand Up @@ -489,3 +490,23 @@ export const getMockConfirmedTopics = (
},
}
}

/**
* 주제 확정 목데이터 반환 함수
*
* @description
* 실제 API 호출을 시뮬레이션하여 주제 확정 응답 목데이터를 반환합니다.
*/
export const getMockConfirmTopics = (
meetingId: number,
topicIds: number[]
): ConfirmTopicsResponse => {
return {
meetingId,
topicStatus: 'CONFIRMED',
topics: topicIds.map((topicId, index) => ({
topicId,
confirmOrder: index + 1,
})),
}
}
Loading
Loading