Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[25.02.08 / TASK-109 / TASK-111] Feature - 샘플 로그인 및 글 바로가기 기능 추가 #10

Merged
merged 26 commits into from
Feb 8, 2025

Conversation

six-standard
Copy link
Member

@six-standard six-standard commented Feb 8, 2025

브랜치 정리도 할 겸, 리더보드 브랜치에서 작업해서 올립니다

작업한 것

스크린샷 2025-02-08 오후 11 05 26 스크린샷 2025-02-08 오후 11 05 41

샘플 로그인 기능 및 페이지 바로가기 기능을 추가하였습니다.
또한 일부 누락된 기능과 디자인 수정을 반영하였습니다

(정작 이 브랜치에서 진행해야 했을 리더보드는 비활성화하였습니다. API가 아직 없습니다)

Summary by CodeRabbit

  • 신규 기능

    • 샘플 로그인 옵션이 추가되어, 사용자가 테스트 계정으로 간편하게 로그인할 수 있습니다.
    • 리더보드 페이지가 개선되어 사용자 순위와 통계 정보를 한눈에 확인할 수 있습니다.
    • 차트의 날짜 선택 기능이 강화되어, 출시 이후의 날짜만 선택하도록 개선되었습니다.
    • Discord 통합 기능이 추가되어, 개발 환경에서 Discord와의 연동이 가능합니다.
    • 새로운 Content 컴포넌트가 추가되어 리더보드 정보를 표시합니다.
    • SvgrMock 컴포넌트가 추가되어 SVG 아이콘을 보다 유연하게 사용할 수 있습니다.
    • 새로운 환경 변수 NEXT_PUBLIC_EVENT_LOG가 추가되어 이벤트 로깅 동작을 세부적으로 제어할 수 있습니다.
  • 버그 수정

    • 로그인 기능의 테스트 케이스가 간소화되어, 서버 응답 시간 초과 처리 로직이 제거되었습니다.
  • UI 개선

    • 페이지 내비게이션과 레이아웃이 업데이트되어 보다 부드럽고 직관적인 사용자 경험을 제공합니다.
    • 로그아웃 처리 및 인터랙션 동작이 향상되어 안정적인 서비스 이용이 가능합니다.
    • 새로운 Section 컴포넌트가 추가되어 클릭 동작에 따라 다양한 반응을 제공합니다.
    • BarContentSidebarContent 컴포넌트에 id 속성이 추가되어 접근성과 DOM 조작이 개선되었습니다.

Copy link

coderabbitai bot commented Feb 8, 2025

Walkthrough

이 PR은 환경 변수 및 ESLint, Jest 구성 변경, 패키지 스크립트 업데이트, MSW 기반 모의 서버 및 핸들러 추가, API 요청과 트래킹 로직 개선, 레이아웃과 컴포넌트 구조 개편, 타입 및 유틸리티 함수 보완 등 다양한 영역에서 변경 사항을 포함합니다.

Changes

파일 그룹 변경 요약
.env.sample, .eslintrc.json, .gitignore, .vscode/settings.json, eslint.config.mjs, jest.config.ts, package.json, tsconfig.json - .env.sample: NEXT_PUBLIC_EVENT_LOG 변수 추가.
- .eslintrc.json: extends 배열 형식을 한 줄로 변경.
- .gitignore: 불필요한 주석 제거.
- .vscode/settings.json: Discord 통합 설정 추가.
- eslint.config.mjs: testing-library 규칙 2개 추가, @typescript-eslint/no-explicit-any 삭제.
- jest.config.ts: setupFilesAfterEnv 및 testEnvironment, testEnvironmentOptions, moduleNameMapper 속성 추가/변경.
- package.json: dev 스크립트에 포트 지정, autoBuild 스크립트 및 새로운 의존성 추가.
- tsconfig.json: 테스트 파일 포함 설정 추가.
setupTests.ts, src/.../mock/handlers.ts, src/.../mock/responses.ts, src/.../mock/server.ts, src/test/login.test.tsx, src/test/main.test.tsx - MSW를 이용한 mock 서버 설정 및 핸들러/응답 함수 추가.
- 로그인 테스트에서 타임아웃 관련 코드 제거 및 기대 경로 수정.
- 메인 대시보드 관련 단위 테스트 추가.
src/apis/instance.request.ts, src/apis/user.request.ts - instance.request.ts: Sentry 모듈을 개별 함수(import { captureException, setContext })로 변경하고 window.location 사용.
- user.request.ts: 별도의 sampleLogin 비동기 함수 추가.
src/app/(with-tracker)/(auth-required)/layout.tsx, src/app/(with-tracker)/(auth-required)/leaderboards/Content.tsx, src/app/(with-tracker)/(auth-required)/leaderboards/page.tsx, src/app/(with-tracker)/(auth-required)/main/Content.tsx, src/app/(with-tracker)/(auth-required)/main/page.tsx, src/app/(with-tracker)/(login)/Content.tsx, src/app/(with-tracker)/layout.tsx - 레이아웃 및 페이지 컴포넌트에서 queryClient 생성 로직을 getQueryClient()로 변경 및 IProp interface 도입.
- 메인, 로그인 컴포넌트에서 trackUserEvent 호출 추가 및 sampleLogin 관련 mutation 추가.
- Suspense를 이용해 TrackVisitEvent 감싸기.
src/components/auth-required/header/Section.tsx, src/components/auth-required/header/index.tsx, src/components/auth-required/index.ts, src/components/auth-required/leaderboards/Rank.tsx, src/components/auth-required/leaderboards/Ranker.tsx, src/components/auth-required/leaderboards/index.ts, src/components/auth-required/main/Section/Graph.tsx, src/components/auth-required/main/Section/index.tsx, src/components/auth-required/main/Summary/BarContent.tsx, src/components/auth-required/main/Summary/SidebarContent.tsx, src/components/auth-required/main/Summary/index.tsx - 인증 및 대시보드 관련 컴포넌트에서 Section, Rank, Ranker 등 새로운 컴포넌트 및 타입 추가.
- Graph 컴포넌트에 releasedAt 속성 추가.
- 몇몇 Summary 컴포넌트에 optional id prop 도입 및 optional chaining 적용.
- Header 컴포넌트는 queryClient 이용 및 custom Section 컴포넌트로 대체.
src/components/common/Dropdown.tsx, src/components/common/Icon/SvgrMock.tsx, src/components/common/Icon/icons/index.ts, src/components/common/Icon/index.tsx, src/components/common/QueryProvider.tsx - Dropdown의 div 높이 속성 변경.
- SvgrMock 컴포넌트 추가 및 관련 아이콘(export Shortcut, 조건부 렌더링) 개선.
- QueryProvider에서 직접 QueryClient 생성 대신 getQueryClient() 활용하도록 리팩터링.
src/constants/paths.constant.ts, src/hooks/useResponsive.ts, src/types/apis/index.ts, src/types/dashboard.type.ts, src/types/index.ts, src/types/user.type.ts, src/utils/index.tsx, src/utils/queryUtil.ts, src/utils/trackUtil.tsx - 상수: SAMPLELOGIN 경로 추가.
- useResponsive의 debounce delay 80ms → 10ms 변경.
- 타입 파일: dashboard 및 user 타입 관련 export 수정, PostType에 slug 추가, UserDto 프로필.thumbnail optional 처리.
- 유틸리티: queryUtil에 getQueryClient 함수 추가, trackUtil에서 MessageEnum 도입 및 trackUserEvent 파라미터 타입 수정, EVENT_LOG 조건 체크 추가.
- utils/index.tsx에서 trackUtil export 제거.

Sequence Diagram(s)

sequenceDiagram
    participant U as 사용자
    participant LC as 로그인 컴포넌트
    participant API as sampleLogin API
    participant TE as 트래킹 모듈
    participant B as 브라우저

    U->>LC: 샘플 로그인 클릭
    LC->>API: sampleLogin() 호출
    API-->>LC: 성공 응답 반환
    LC->>TE: trackUserEvent('REFRESH_INTERACT_MAIN') 호출
    LC->>B: window.location.replace('/main?asc=false&sort=') 실행
Loading

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • HA0N1
  • BDlhj

Poem

토끼 한 마리가 뛰어요,
코드 숲 속에서 발자취 남기며,
새로운 변수와 기능들이 춤추네,
트래킹과 테스트, 모두 모여
깔끔한 코드의 초원 위에서,
🥕 달콤한 변화에 모두 환호해!
귀여운 발걸음 잊지 말아요!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d6873b and 69dcca3.

📒 Files selected for processing (2)
  • src/app/(with-tracker)/(auth-required)/leaderboards/Content.tsx (1 hunks)
  • src/components/auth-required/leaderboards/Ranker.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/app/(with-tracker)/(auth-required)/leaderboards/Content.tsx
  • src/components/auth-required/leaderboards/Ranker.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@six-standard six-standard changed the title Feature/leaderboards [25.02.08 / TASK-109 / TASK-111] Feature - 샘플 로그인 및 글 바로가기 기능 추가 Feb 8, 2025
@Nuung Nuung self-assigned this Feb 8, 2025
Copy link

Copy link

@Nuung Nuung assigned six-standard and unassigned Nuung Feb 8, 2025
@Nuung Nuung self-requested a review February 8, 2025 14:08
@Nuung Nuung added the documentation Improvements or additions to documentation label Feb 8, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 14

🔭 Outside diff range comments (3)
src/app/(with-tracker)/(auth-required)/layout.tsx (1)

17-21: prefetch 에러 처리 추가 필요

prefetchQuery 실패 시의 처리가 누락되어 있습니다. 에러 발생 시 적절한 처리가 필요합니다.

   await client.prefetchQuery({
     queryKey: [PATHS.ME],
     queryFn: async () =>
-      await me(getCookieForAuth(cookies, ['access_token', 'refresh_token'])),
+      try {
+        return await me(getCookieForAuth(cookies, ['access_token', 'refresh_token']));
+      } catch (error) {
+        console.error('사용자 정보 조회 실패:', error);
+        throw error;
+      }
   });
src/__test__/login.test.tsx (1)

33-81: 테스트 케이스 보완이 필요합니다.

현재 테스트에서 다음과 같은 중요한 시나리오들이 누락되어 있습니다:

  • 로딩 상태 테스트
  • 폼 유효성 검사 테스트
  • 네트워크 에러 처리 테스트

다음과 같은 테스트 케이스 추가를 제안합니다:

it('로그인 요청 중에는 로딩 상태를 표시한다', async () => {
  renderPage();
  const { buttonEl, accessInputEl, refreshInputEl } = getElements();
  
  await userEvent.type(accessInputEl, 'access');
  await userEvent.type(refreshInputEl, 'refresh');
  await act(async () => buttonEl.click());
  
  expect(screen.getByRole('progressbar')).toBeInTheDocument();
});

it('토큰 형식이 올바르지 않으면 유효성 검사 메시지를 표시한다', async () => {
  renderPage();
  const { accessInputEl } = getElements();
  
  await userEvent.type(accessInputEl, 'invalid');
  
  expect(screen.getByText('올바른 토큰 형식이 아닙니다')).toBeInTheDocument();
});
src/components/auth-required/main/Section/Graph.tsx (1)

91-97: 날짜 입력 유효성 검사 강화 필요

시작 날짜가 종료 날짜보다 늦을 수 있는 잠재적 문제가 있습니다.

날짜 유효성 검사 로직을 추가하는 것을 추천드립니다:

 <Input
   size={isMBI ? 'SMALL' : 'MEDIUM'}
   form="SMALL"
   value={type.start}
   min={releasedAt.split('T')[0]}
   max={maxDate}
+  max={type.end || maxDate}
   onChange={(e) => setType({ ...type, start: e.target.value })}
   placeholder="시작 날짜"
   type="date"
 />
🧹 Nitpick comments (17)
src/app/(with-tracker)/layout.tsx (1)

6-9: Suspense에 fallback UI 추가 필요

비동기 컴포넌트의 로딩 상태를 사용자에게 표시하기 위해 Suspense에 fallback prop을 추가하는 것이 좋습니다.

-    <Suspense>
+    <Suspense fallback={<div>로딩 중...</div>}>
src/utils/queryUtil.ts (2)

4-6: 상수값을 설정 파일로 분리 권장

STALE_TIME과 GC_TIME 상수를 설정 파일로 분리하면 환경에 따라 쉽게 조정할 수 있습니다.

+// src/config/query.ts
+export const QUERY_CONFIG = {
+  STALE_TIME: 1000 * 60 * 3,
+  GC_TIME: 1000 * 60 * 30,
+} as const;

17-17: 에러 처리 개선 필요

현재 모든 에러를 동일한 방식으로 처리하고 있습니다. 에러 타입에 따라 다른 메시지를 표시하는 것이 좋습니다.

-      mutations: { onError: (err) => toast.error(`${err.message}`) },
+      mutations: {
+        onError: (err) => {
+          if (err instanceof NetworkError) {
+            toast.error('네트워크 연결을 확인해주세요');
+          } else if (err instanceof ValidationError) {
+            toast.error('입력값을 확인해주세요');
+          } else {
+            toast.error('오류가 발생했습니다. 잠시 후 다시 시도해주세요');
+          }
+        }
+      },
src/app/(with-tracker)/(auth-required)/layout.tsx (1)

24-30: 레이아웃 구조 검토 필요

현재 레이아웃은 고정된 패딩 값을 사용하고 있습니다. 반응형 디자인을 위해 CSS 변수나 테마 시스템 사용을 고려해보세요.

-    <main className="items-center w-full h-full flex flex-col p-[50px_70px_70px_70px] transition-all max-TBL:p-[20px_30px_30px_30px] max-MBI:p-[10px_25px_25px_25px]">
+    <main className="items-center w-full h-full flex flex-col p-[var(--layout-padding)] transition-all">
src/app/(with-tracker)/(auth-required)/main/page.tsx (1)

25-44: prefetch 작업에 대한 에러 처리가 필요합니다.

prefetch 작업이 실패할 경우에 대한 처리가 없습니다. try-catch 블록을 사용하여 에러를 적절히 처리하는 것이 좋습니다.

예시 코드:

try {
  await Promise.all([
    client.prefetchInfiniteQuery({
      // ... existing config
    }),
    client.prefetchQuery({
      // ... existing config
    })
  ]);
} catch (error) {
  console.error('Failed to prefetch data:', error);
  // 에러 상태를 전달하거나 대체 데이터를 보여주는 로직 추가
}
src/utils/trackUtil.tsx (4)

21-25: EVENT_LOG 환경 변수 필수 요구 사항 재고
ENV 미설정 시 앱이 바로 에러를 던지므로, 배포 환경에서 설정 누락 시 서비스가 바로 중단될 수 있습니다. 개발 및 QA 환경에서 기본값을 지정하거나 예외 처리를 도입하는 방안도 고민해 보시면 좋겠습니다.


27-33: 이벤트 추적 로직의 에러 핸들링 고려
현재 POST 요청 실패 시 별도의 후속 처리(재시도, 에러 메시지 등)가 없습니다. 이벤트 로그가 중요한 지표라면 에러를 모니터링할 수 있는 최소한의 로깅 혹은 핸들러를 고려해 보세요.


50-50: 프로덕션 환경 전용 unload 이벤트 등록
production 모드에서만 unload 이벤트를 등록하도록 했는데, QA나 스테이징 테스트를 위해선 필요 시 별도의 조건 처리를 고려할 수 있습니다.


55-55: 프로덕션 환경 전용 unload 이벤트 해제
위와 동일하게 production 모드에만 대응 중입니다. QA 환경에서도 이벤트를 확인하고 싶다면 조건을 유연하게 변경할 수 있습니다.

src/components/auth-required/leaderboards/Rank.tsx (1)

3-18: 컴포넌트가 깔끔하게 구현되었습니다!

반응형 디자인과 함께 컴포넌트 구조가 잘 구현되어 있습니다.

접근성 개선을 위한 제안사항이 있습니다.

시맨틱 HTML과 ARIA 속성을 추가하여 접근성을 개선할 수 있습니다.

다음과 같이 수정해 보세요:

- <div className="min-w-[40%] w-full p-[25px] bg-BG-SUB rounded-[4px] justify-between flex">
+ <div 
+   role="listitem"
+   aria-label={`${rank}위 ${name}`}
+   className="min-w-[40%] w-full p-[25px] bg-BG-SUB rounded-[4px] justify-between flex"
+ >
src/app/(with-tracker)/(auth-required)/leaderboards/Content.tsx (1)

8-15: 정적 데이터를 상수 파일로 분리하는 것이 좋습니다.

데이터를 컴포넌트 외부의 상수 파일로 분리하여 재사용성과 유지보수성을 높이는 것을 추천드립니다.

-const data = [
+// src/constants/leaderboard.constant.ts
+export const LEADERBOARD_SAMPLE_DATA = [
  { rank: 1, name: '정현우', count: 1235 },
  { rank: 2, name: '최하온', count: 1234 },
  { rank: 3, name: '이하준', count: 1233 },
  { rank: 4, name: '육기준', count: 1232 },
  { rank: 5, name: '칠기준', count: 1231 },
  { rank: 6, name: '팔기준', count: 1230 },
];
src/__test__/main.test.tsx (1)

20-37: 테스트 설정 개선이 필요합니다.

  1. beforeEach에서 원본 fetch를 저장하고 afterEach에서 복원하는 것이 좋습니다.
  2. 매직 스트링을 상수로 분리하는 것이 좋습니다.
+const TEST_TOKENS = {
+  ACCESS: 'access',
+  REFRESH: 'refresh'
+} as const;
+
+let originalFetch: typeof global.fetch;
+
+beforeEach(() => {
+  originalFetch = global.fetch;
+});
+
+afterEach(() => {
+  global.fetch = originalFetch;
+});
+
 const withFetch = (withOriginalFetch?: typeof global.fetch) => {
   if (withOriginalFetch) {
     global.fetch = withOriginalFetch;
     return;
   }
 
-  const fetchApi = global.fetch;
   global.fetch = async (input, init) => {
-    return await fetchApi(input, {
+    return await originalFetch(input, {
       ...init,
       headers: {
         ...Object.fromEntries(Array.from(init?.headers as Headers)),
-        access_token: 'access',
-        refresh_token: 'refresh',
+        access_token: TEST_TOKENS.ACCESS,
+        refresh_token: TEST_TOKENS.REFRESH,
       },
     });
   };
 };
src/__mock__/handlers.ts (2)

22-32: 테스트 데이터를 분리해야 합니다.

하드코딩된 테스트 데이터는 유지보수를 어렵게 만들 수 있습니다.

src/__mock__/test-data.ts 파일을 생성하고 다음과 같이 데이터를 분리하는 것을 제안합니다:

// src/__mock__/test-data.ts
export const MOCK_SUMMARY_DATA = {
  stats: {
    lastUpdatedDate: '2025-01-09T00:00:00Z102',
    totalLikes: 100,
    totalViews: 100,
    yesterdayLikes: 50,
    yesterdayViews: 50,
  },
  totalPostCount: 10,
};

10-12: 에러 메시지를 상수로 분리해야 합니다.

반복되는 에러 메시지는 상수로 관리되어야 합니다.

다음과 같이 에러 메시지를 상수로 분리하는 것을 제안합니다:

const ERROR_MESSAGES = {
  INVALID_TOKEN: '잘못된 토큰입니다',
  ABNORMAL_TOKEN: '정상적인 토큰이 아닙니다',
} as const;

Also applies to: 19-21, 38-40, 53-55

src/app/(with-tracker)/(login)/Content.tsx (1)

80-85: 접근성 개선 제안

샘플 로그인 링크에 대한 접근성을 개선하면 좋을 것 같습니다.

 <span
   className="text-TEXT-ALT text-I2 max-MBI:text-ST5 after:cursor-pointer after:hover:underline after:ml-2 after:content-['체험_계정으로_로그인'] after:text-PRIMARY-MAIN after:inline-block"
   onClick={() => sampleMutate()}
+  role="button"
+  tabIndex={0}
+  onKeyPress={(e) => e.key === 'Enter' && sampleMutate()}
 >
   서비스를 체험해보고 싶다면?
 </span>
src/components/auth-required/main/Section/index.tsx (1)

29-47: 바로가기 기능 구현이 잘 되었습니다

글 제목을 클릭하여 해당 글로 이동하는 바로가기 기능이 사용자 경험을 개선합니다.

다만, 다음과 같은 개선을 제안드립니다:

 <div
   className="flex items-center gap-1"
   title="해당 글로 바로가기"
   onClick={(e) => {
     e.stopPropagation();
     window.open(
       `${process.env.NEXT_PUBLIC_VELOG_URL}/@${username}/${p.slug}`,
     );
   }}
+  role="link"
+  tabIndex={0}
+  onKeyPress={(e) => {
+    if (e.key === 'Enter') {
+      e.stopPropagation();
+      window.open(
+        `${process.env.NEXT_PUBLIC_VELOG_URL}/@${username}/${p.slug}`,
+      );
+    }
+  }}
 >
src/components/auth-required/main/Section/Graph.tsx (1)

126-154: 차트 반응형 설정 최적화 필요

maintainAspectRatio: false와 함께 사용된 CSS 클래스의 !important 사용은 피해야 합니다.

-className="w-[100%_!important] h-[auto_!important] max-h-[300px]"
+className="w-full h-auto max-h-[300px]"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4fb015e and f0c1d3b.

⛔ Files ignored due to path filters (2)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • src/components/common/Icon/icons/Shortcut.svg is excluded by !**/*.svg
📒 Files selected for processing (48)
  • .env.sample (1 hunks)
  • .eslintrc.json (1 hunks)
  • .gitignore (0 hunks)
  • .vscode/settings.json (1 hunks)
  • eslint.config.mjs (1 hunks)
  • jest.config.ts (1 hunks)
  • package.json (2 hunks)
  • setupTests.ts (1 hunks)
  • src/__mock__/handlers.ts (1 hunks)
  • src/__mock__/responses.ts (1 hunks)
  • src/__mock__/server.ts (1 hunks)
  • src/__test__/login.test.tsx (1 hunks)
  • src/__test__/main.test.tsx (1 hunks)
  • src/apis/instance.request.ts (2 hunks)
  • src/apis/user.request.ts (1 hunks)
  • src/app/(with-tracker)/(auth-required)/layout.tsx (2 hunks)
  • src/app/(with-tracker)/(auth-required)/leaderboards/Content.tsx (1 hunks)
  • src/app/(with-tracker)/(auth-required)/leaderboards/page.tsx (1 hunks)
  • src/app/(with-tracker)/(auth-required)/main/Content.tsx (4 hunks)
  • src/app/(with-tracker)/(auth-required)/main/page.tsx (1 hunks)
  • src/app/(with-tracker)/(login)/Content.tsx (2 hunks)
  • src/app/(with-tracker)/layout.tsx (1 hunks)
  • src/components/auth-required/header/Section.tsx (1 hunks)
  • src/components/auth-required/header/index.tsx (2 hunks)
  • src/components/auth-required/index.ts (1 hunks)
  • src/components/auth-required/leaderboards/Rank.tsx (1 hunks)
  • src/components/auth-required/leaderboards/Ranker.tsx (1 hunks)
  • src/components/auth-required/leaderboards/index.ts (1 hunks)
  • src/components/auth-required/main/Section/Graph.tsx (4 hunks)
  • src/components/auth-required/main/Section/index.tsx (2 hunks)
  • src/components/auth-required/main/Summary/BarContent.tsx (2 hunks)
  • src/components/auth-required/main/Summary/SidebarContent.tsx (3 hunks)
  • src/components/auth-required/main/Summary/index.tsx (3 hunks)
  • src/components/common/Dropdown.tsx (1 hunks)
  • src/components/common/Icon/SvgrMock.tsx (1 hunks)
  • src/components/common/Icon/icons/index.ts (1 hunks)
  • src/components/common/Icon/index.tsx (2 hunks)
  • src/components/common/QueryProvider.tsx (1 hunks)
  • src/constants/paths.constant.ts (1 hunks)
  • src/hooks/useResponsive.ts (1 hunks)
  • src/types/apis/index.ts (0 hunks)
  • src/types/dashboard.type.ts (1 hunks)
  • src/types/index.ts (1 hunks)
  • src/types/user.type.ts (1 hunks)
  • src/utils/index.tsx (0 hunks)
  • src/utils/queryUtil.ts (1 hunks)
  • src/utils/trackUtil.tsx (2 hunks)
  • tsconfig.json (1 hunks)
💤 Files with no reviewable changes (3)
  • .gitignore
  • src/utils/index.tsx
  • src/types/apis/index.ts
✅ Files skipped from review due to trivial changes (8)
  • .eslintrc.json
  • src/app/(with-tracker)/(auth-required)/leaderboards/page.tsx
  • src/mock/server.ts
  • src/components/auth-required/leaderboards/index.ts
  • .vscode/settings.json
  • src/components/auth-required/index.ts
  • src/types/index.ts
  • src/components/common/Icon/SvgrMock.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
src/__test__/main.test.tsx

[error] 52-54: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (35)
src/components/common/QueryProvider.tsx (1)

11-20: 코드 구조가 개선되었습니다!

QueryClient 생성 로직을 별도의 유틸리티로 분리하여 관심사 분리가 잘 이루어졌습니다. React Query DevTools도 적절히 구현되어 있습니다.

src/app/(with-tracker)/(auth-required)/layout.tsx (1)

10-12: 타입 정의가 개선되었습니다!

인터페이스를 사용한 타입 정의로 코드의 안정성이 향상되었습니다.

src/app/(with-tracker)/(auth-required)/main/page.tsx (2)

1-8: 타입 정의와 임포트 구조가 개선되었습니다!

QueryClient를 직접 생성하는 대신 getQueryClient 유틸리티를 사용하도록 변경한 것이 좋습니다. 또한 IProp 인터페이스를 통해 searchParams의 타입을 명확하게 정의한 것이 코드의 안정성을 높여줍니다.

Also applies to: 15-20


22-24: undefined

src/utils/trackUtil.tsx (2)

11-19: MessageEnum 정의에 대한 구조와 명확성 호평
이 객체 기반 열거 방식(as const)은 타입 안전성과 유지보수에 용이합니다. 추후 새로운 이벤트 타입이 추가될 경우 이 객체를 함께 업데이트해 주세요.


43-43: unloadDate 설정 시점 검토
페이지 언로드 시점을 정확히 트래킹해야 한다면 beforeunload 이벤트도 함께 고려할 수 있습니다. 일부 브라우저에서는 unload 이벤트가 제한적일 수 있으니 주의가 필요합니다.

src/types/user.type.ts (1)

11-11: thumbnail 필드의 선택적 속성 전환
thumbnail이 이제 선택적이므로, 이 필드가 없을 수 있는 상황을 처리하는 로직이나 UI 표시에 유의하세요.
[approval]

src/constants/paths.constant.ts (1)

3-3: 새로운 SAMPLELOGIN 경로 추가
기존 경로들과 충돌하지 않으며 명확한 명칭입니다. 로그인 시나리오 분기 처리가 필요한 경우 대응 로직이 제대로 구현되었는지 확인해 보세요.

setupTests.ts (1)

1-10: MSW 설정이 올바르게 구현되었습니다!

테스트 환경에서 API 모킹을 위한 MSW 설정이 잘 구현되어 있습니다. 처리되지 않은 요청에 대한 에러 처리와 테스트 간 상태 초기화가 적절히 구성되어 있습니다.

src/components/common/Icon/icons/index.ts (1)

6-6: 새로운 Shortcut 아이콘이 올바르게 추가되었습니다!

기존 아이콘 내보내기 패턴과 일관성 있게 구현되어 있습니다.

src/types/dashboard.type.ts (1)

8-8: 타입 추가가 적절합니다!

게시물의 URL 구성에 필요한 slug 필드가 잘 추가되었습니다.

jest.config.ts (1)

10-17: Jest 설정 변경사항 검증이 필요합니다.

다음 사항들을 확인해주세요:

  1. setupTests.ts 파일이 존재하는지
  2. jest-fixed-jsdom 패키지가 설치되어 있는지
✅ Verification successful

🏁 Script executed:

#!/bin/bash
# setupTests.ts 파일 존재 여부 확인
test -f setupTests.ts && echo "setupTests.ts exists" || echo "setupTests.ts missing"

# jest-fixed-jsdom 패키지 설치 여부 확인
grep "jest-fixed-jsdom" package.json || echo "jest-fixed-jsdom not found in package.json"

Length of output: 145


Jest 설정 변경사항에 문제가 없습니다.

  • setupTests.ts 파일이 존재합니다.
  • package.json 내에 jest-fixed-jsdom 패키지가 정상적으로 설치되어 있습니다.
src/components/auth-required/main/Summary/BarContent.tsx (1)

8-8: 접근성 향상을 위한 id 속성 추가가 적절합니다.

컴포넌트의 접근성과 DOM 조작을 위한 id 속성 추가는 좋은 개선사항입니다.

Also applies to: 19-19, 27-27

src/components/common/Icon/index.tsx (1)

2-2: SvgrMock 내보내기가 적절합니다.

테스트 환경에서 SVG 컴포넌트를 모킹하기 위한 유틸리티 내보내기입니다.

src/components/auth-required/main/Summary/SidebarContent.tsx (1)

8-8: BarContent와 일관된 id 속성 추가가 적절합니다.

접근성과 DOM 조작을 위한 id 속성 추가가 BarContent 컴포넌트와 일관되게 구현되었습니다.

Also applies to: 19-19, 29-29

src/components/auth-required/leaderboards/Ranker.tsx (1)

1-6: 인터페이스 정의가 명확합니다.

Props 인터페이스가 잘 정의되어 있으며, 필수값과 선택값이 적절히 구분되어 있습니다.

src/components/common/Dropdown.tsx (1)

22-22: 높이 설정이 적절히 개선되었습니다!

h-fit 속성을 사용하여 컨텐츠에 맞게 높이가 조절되도록 한 것이 좋습니다.

src/app/(with-tracker)/(auth-required)/leaderboards/Content.tsx (1)

28-31: undefined

eslint.config.mjs (1)

41-42: Testing Library 관련 규칙이 적절히 추가되었습니다!

no-containerno-node-access 규칙을 추가한 것이 좋습니다. 이는 Testing Library의 모범 사례를 따르는데 도움이 됩니다.

src/apis/instance.request.ts (3)

2-3: Sentry 임포트 최적화가 잘 되었습니다!

필요한 함수만 선택적으로 임포트하여 번들 크기를 최적화했습니다.


81-81: window 객체 명시적 참조 개선

window.location.replace를 사용하여 전역 객체를 명시적으로 참조하도록 개선되었습니다.


84-87: 에러 추적 로직이 개선되었습니다

Sentry를 통한 에러 추적이 더 체계적으로 구현되었습니다:

  • 요청 컨텍스트 설정
  • 서버 응답 지연 에러 추적
  • 예상치 못한 서버 에러 추적
  • 상태 코드별 에러 추적

Also applies to: 89-90, 96-97, 100-101

src/app/(with-tracker)/(login)/Content.tsx (2)

24-27: 이벤트 추적 구현이 잘 되었습니다

로그인 성공 시 사용자 이벤트를 추적하고 메인 페이지로 리다이렉션하는 로직이 깔끔하게 구현되었습니다.


34-37: 샘플 로그인 기능 추가

샘플 계정 로그인 기능이 기존 로그인 로직을 재사용하여 효율적으로 구현되었습니다.

src/components/auth-required/main/Section/index.tsx (2)

15-17: 사용자 데이터 조회 구현이 깔끔합니다

Query Client를 통한 사용자 데이터 조회가 효율적으로 구현되었습니다.


23-26: 이벤트 추적 구현이 적절합니다

섹션 상호작용에 대한 이벤트 추적이 잘 구현되었습니다.

src/app/(with-tracker)/(auth-required)/main/Content.tsx (4)

44-44: 비동기 처리가 개선되었습니다

queryFn에서 await 키워드를 명시적으로 사용하여 비동기 처리를 더 명확하게 했습니다.


64-64: Null 처리가 개선되었습니다

lastUpdatedDate가 없는 경우에 대한 폴백 처리가 적절히 구현되었습니다.

Also applies to: 76-76


68-74: 사용자 상호작용 추적이 잘 구현되었습니다

새로고침, 정렬 변경 등 주요 사용자 상호작용에 대한 이벤트 추적이 체계적으로 구현되었습니다.

Also applies to: 81-86, 95-98


104-104: 안전한 배열 접근이 구현되었습니다

Optional chaining을 사용하여 pages 배열이 undefined일 때의 런타임 에러를 방지했습니다.

.env.sample (1)

6-6: 🏁 Script executed:

#!/bin/bash
# 환경 변수 타입 체크 로직 검색
rg "process\.env\.NEXT_PUBLIC_EVENT_LOG" src/

Length of output: 124

package.json (4)

6-6: 개발 서버 포트 지정 변경 확인
dev 스크립트에서 개발 서버를 기본 포트가 아닌 3000번 포트에서 실행하도록 변경한 점은 의도한 동작인지 다시 한번 확인 바랍니다.


8-8: 자동 빌드 스크립트 추가 확인
새롭게 추가된 autoBuild 스크립트는 빌드 후 필요한 파일들을 standalone 디렉터리로 복사하는 작업을 수행합니다. 이 스크립트가 실제 빌드 및 배포 환경에서 올바르게 동작하는지 테스트해 보시기 바랍니다.


20-20: 테스트 환경 개선을 위한 jest-fixed-jsdom 패키지 추가 확인
jest-fixed-jsdom 패키지가 추가되어 테스트 환경에서의 jsdom 이슈를 해결하려는 목적이 보입니다. 해당 패키지의 버전과 프로젝트와의 호환성을 재검토해 주시기 바랍니다.


22-22: 모킹 서버 구현을 위한 msw 패키지 추가 확인
msw 패키지를 추가하여 모의 서버 기능을 확장한 점은 긍정적입니다. 추가된 버전이 다른 테스트 구성요소들과 충돌 없이 작동하는지 확인해 주시기 바랍니다.

src/__mock__/responses.ts Show resolved Hide resolved
src/hooks/useResponsive.ts Show resolved Hide resolved
src/apis/user.request.ts Show resolved Hide resolved
src/components/common/Icon/index.tsx Show resolved Hide resolved
src/components/auth-required/leaderboards/Ranker.tsx Outdated Show resolved Hide resolved
Comment on lines +106 to +109
onClick={() => {
out();
trackUserEvent('LOGOUT');
}}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

이벤트 추적 순서 개선 필요

로그아웃 이벤트 추적이 실제 로그아웃 이전에 발생하면 사용자 컨텍스트가 손실될 수 있습니다.

 onClick={() => {
+  trackUserEvent('LOGOUT');
   out();
-  trackUserEvent('LOGOUT');
 }}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onClick={() => {
out();
trackUserEvent('LOGOUT');
}}
onClick={() => {
trackUserEvent('LOGOUT');
out();
}}

src/components/auth-required/header/index.tsx Outdated Show resolved Hide resolved
src/components/auth-required/header/index.tsx Show resolved Hide resolved
@@ -35,6 +35,7 @@
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"src/__test__/main.test.tsx.ignore"
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

테스트 파일 무시 설정 검증 필요

.ignore 확장자를 가진 테스트 파일을 포함하는 것은 일반적이지 않습니다.

다음 명령으로 해당 파일의 용도를 확인해보세요:


🏁 Script executed:

#!/bin/bash
# 테스트 파일 내용 확인
cat src/__test__/main.test.tsx.ignore 2>/dev/null || echo "파일이 존재하지 않습니다"

Length of output: 76


테스트 파일 무시 설정 관련 이슈 발견

  • tsconfig.json 파일의 38번째 줄에 "src/test/main.test.tsx.ignore" 항목이 포함되어 있지만, 실제 해당 파일이 존재하지 않습니다.
  • .ignore 확장자는 일반적인 테스트 파일 무시 방식이 아니며, 파일이 없으므로 이 설정은 실제로는 아무런 효과를 발휘하지 않습니다.
  • 이 설정이 의도된 것인지, 추후 실제 테스트 파일이 추가될 예정인지 여부를 다시 한번 확인하고, 불필요하다면 해당 항목을 제거하거나 수정할 필요가 있습니다.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/utils/trackUtil.tsx (1)

38-41: 날짜 처리 로직을 분리하는 것이 좋겠습니다.

날짜 관련 로직을 별도의 유틸리티 함수로 분리하면 재사용성과 테스트 용이성이 향상될 것 같습니다.

+const getISODateTime = () => new Date().toISOString();
+
 const setUnloadData = () => {
-  data.current = { ...data.current, unloadDate: new Date().toISOString() };
+  data.current = { ...data.current, unloadDate: getISODateTime() };
   instance('/stay', { body: data.current, method: 'POST', keepalive: true });
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f0c1d3b and 4ca651f.

📒 Files selected for processing (1)
  • src/utils/trackUtil.tsx (2 hunks)
🔇 Additional comments (3)
src/utils/trackUtil.tsx (3)

11-19: 이벤트 타입 정의가 잘 구조화되어 있습니다!

이벤트 타입을 숫자로 정의하고 논리적으로 그룹화한 것이 좋습니다. 인증(11-13), 메인 페이지 상호작용(21-23), 게시판 상호작용(31) 등으로 명확하게 구분되어 있습니다.


23-30: 이벤트 추적 함수가 개선되었습니다!

환경 변수를 통한 이벤트 로깅 제어와 MessageEnum을 활용한 타입 안정성이 잘 구현되어 있습니다.


43-55: 이벤트 리스너 관리가 잘 구현되어 있습니다!

프로덕션 환경과 이벤트 로깅 설정에 따른 조건부 이벤트 리스너 관리가 잘 되어 있습니다.

src/utils/trackUtil.tsx Show resolved Hide resolved
src/utils/trackUtil.tsx Outdated Show resolved Hide resolved
Copy link
Member

@Nuung Nuung left a comment

Choose a reason for hiding this comment

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

좋았던 점

  • 변수명이 clearly 해서 좋았어요!
  • 어느새 testing 을 위한 Data mocking 과 리더보드를 위한 예상 데이터셋까지~ 아주 좋은 것 같아요!! API 개발에 선행되어서 필요한 데이터가 뭔지 한 번에 바로 알아 볼 수 있는 것 같아요!!

아쉬운 점

  • 선생님 PR 덩어리가 너무 커요, 코드 리뷰 힘들어요 ㅠㅠ
  • 코멘트 참조해주세요! 그리고 slack 으로 궁금한 부분 남겨뒀습니다 :)

@six-standard
Copy link
Member Author

이번에 브랜치 정리한다고 따로 안 나누고 한 곳에 다 넣어서 좀 큰가 봅니다;
다음부터 최대한 잘 나눠보도록 노력하겠습니다!

@six-standard six-standard requested a review from Nuung February 8, 2025 15:12
@six-standard six-standard merged commit 72ad44e into main Feb 8, 2025
1 check passed
@six-standard six-standard deleted the feature/leaderboards branch February 8, 2025 15:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants