Skip to content

Conversation

@hammsik
Copy link
Collaborator

@hammsik hammsik commented Feb 27, 2025

  • Easing 값 변경
  • 팀 만들고 바로 팀 세팅하도록
  • Service Worker에서 Push message 수신 시 클라이언트에 신호 줘서 캐시 만료시키도록

Summary by CodeRabbit

  • New Features
    • Enhanced push notifications now display alerts while simultaneously updating client views.
    • Improved real-time data updates refresh notifications and schedule displays for a more dynamic main page.
    • Smoother transition animations using a custom easing function deliver refined visual feedback.
    • Streamlined team management now automatically updates and selects newly created teams for a seamless experience.

@vercel
Copy link

vercel bot commented Feb 27, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
feedhanjum ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 27, 2025 8:34am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 27, 2025

Walkthrough

This update enhances the front-end application’s push notification and state management functionalities. A new asynchronous function in the service worker now sends messages to all active window clients concurrently with notifications. Several API hooks have been updated to include query invalidation and a new service worker message hook has been introduced. Import statements in components were streamlined by removing unused hooks, and components managing notifications and team data now incorporate updated state handling and animations.

Changes

Files Change Summary
front-end/public/service-worker.js Added sendMessageToClients to send messages to window clients concurrently with displaying notifications using Promise.allSettled.
front-end/src/api/useMainPage.js, front-end/src/api/usePushNoti.js Updated hooks to return additional invalidation functions; changed usePushNoti export from default to named; added useServiceWorkerMessage for handling SW messages.
front-end/src/components/Accordion.jsx, front-end/src/pages/main/MainPage.jsx, front-end/src/pages/teamspace/TeamSpaceMake.jsx Revised import statements to remove unused dependencies and adjust hook imports; updated state management for notifications and team data; applied custom easing in transition animations.

Sequence Diagram(s)

sequenceDiagram
    participant SW as Service Worker
    participant Client as Window Client
    participant Main as MainPage Component

    SW->>SW: Push event received
    par Concurrent Operations
        SW->>SW: showNotification()
        SW->>Client: sendMessageToClients(notificationType)
    end
    Client->>Client: useServiceWorkerMessage listens for messages
    Client->>Main: Trigger cache invalidation (invalidateNotification/invalidateMainCard)
Loading

Possibly related PRs

Suggested labels

FE, feat, fix

Suggested reviewers

  • lsj1137

Poem

Hi, I'm a rabbit with hops so light,
Joyfully coding well into the night.
I bounce through changes with a twitch of my nose,
Celebrating new hooks and transitions that glow.
🎉 With every line, my happy heart sings—
CodeRabbit brings cheer as the fresh code springs!
🐰💕

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
  • @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.

Copy link
Contributor

@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 (4)
front-end/public/service-worker.js (1)

98-107: Well-structured client messaging function.

The sendMessageToClients function is properly implemented to communicate with all active window clients. This enables the service worker to notify the client about push notifications, which can be used to invalidate caches as mentioned in the PR objectives.

However, consider adding error handling for potential failures in client messaging:

 async function sendMessageToClients(type) {
-  const clients = await self.clients.matchAll({
-    type: 'window',
-    includeUncontrolled: true,
-  });
-  const data = { type };
-  for (const client of clients) {
-    client.postMessage(data);
-  }
+  try {
+    const clients = await self.clients.matchAll({
+      type: 'window',
+      includeUncontrolled: true,
+    });
+    const data = { type };
+    for (const client of clients) {
+      client.postMessage(data);
+    }
+  } catch (error) {
+    console.error('Error sending message to clients:', error);
+  }
 }
front-end/src/pages/teamspace/TeamSpaceMake.jsx (1)

60-60: Use functional update pattern for state updates.

When updating state based on previous state, use the functional update pattern to avoid potential race conditions.

-setTeams([...teams, teamData]);
+setTeams(prevTeams => [...prevTeams, teamData]);
front-end/src/api/usePushNoti.js (1)

102-113: Add type checking for message handling.

The current implementation doesn't check if the received message data has a type property before trying to use it.

 const handleServiceWorkerMessage = (event) => {
   const data = event.data;
+  if (!data || typeof data !== 'object' || !('type' in data)) {
+    console.warn('Received invalid message format from service worker:', data);
+    return;
+  }
   if (allMessageType) {
     onMessage(data);
   } else if (messageTypes.includes(data.type)) {
     onMessage(data);
   }
 };
front-end/src/api/useMainPage.js (1)

26-29: Consider adding error handling for the query.

While the implementation is correct, consider destructuring and returning isLoading and isError states as well to provide consumers with more information about the query status.

-  const { data } = useQuery({
+  const { data, isLoading, isError } = useQuery({
     queryKey: ['mainCard', teamId],
     queryFn: () => api.get({ url: `/api/team/${teamId}/schedule` }),
     enabled: !!teamId,
   });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ce4ddd4 and b9b585f.

📒 Files selected for processing (6)
  • front-end/public/service-worker.js (2 hunks)
  • front-end/src/api/useMainPage.js (4 hunks)
  • front-end/src/api/usePushNoti.js (3 hunks)
  • front-end/src/components/Accordion.jsx (1 hunks)
  • front-end/src/pages/main/MainPage.jsx (7 hunks)
  • front-end/src/pages/teamspace/TeamSpaceMake.jsx (2 hunks)
🔇 Additional comments (22)
front-end/public/service-worker.js (1)

74-78: Good implementation of concurrent notification processing.

The use of Promise.allSettled ensures that both the client messaging and notification display happen concurrently without one blocking the other. This is a robust approach for handling multiple asynchronous operations.

front-end/src/pages/teamspace/TeamSpaceMake.jsx (1)

33-33: LGTM - Added additional team state management.

Properly expanded the destructuring assignment to include setTeams and teams from the useTeam hook.

front-end/src/components/Accordion.jsx (1)

1-5: Import cleanup and update.

Good removal of unused React hooks and update to the named import of usePushNoti to match its export declaration.

front-end/src/api/usePushNoti.js (1)

37-37: Export type changed from default to named.

Changed the export of usePushNoti from default to named export for better import/export consistency.

front-end/src/api/useMainPage.js (9)

1-1: Good use of useCallback.

Adding the useCallback import supports the optimization of function references through memoization, which is utilized effectively in the new invalidation functions.


20-20: JSDoc update properly reflects new return values.

The updated JSDoc comment accurately documents the new return structure of the useMainCard hook, making it clear for other developers.


23-25: Proper hook placement.

Correctly initialized the queryClient at the top level of the component, following React's rules of hooks.


32-37: Good implementation of memoized invalidation function.

The use of useCallback with proper dependencies ensures the function reference stability across renders, which is important for performance optimization.


39-42: Return structure updated correctly.

The return object now properly includes both data and the invalidation function, matching the updated JSDoc.


60-60: JSDoc update properly reflects new return values.

The updated JSDoc comment accurately documents the new return structure of the useNotification hook.


72-75: Nice implementation of callback with inline function.

Good use of the useCallback pattern with an inline function for brevity while maintaining the same dependency array pattern.


80-80: Great simplification of onSuccess callback.

Replaced direct query invalidation with the memoized function, making the code more maintainable and consistent.


88-88: Return structure updated correctly.

Added the invalidateNotification function to the return object, making it available to consumers.

front-end/src/pages/main/MainPage.jsx (9)

33-33: Good import update for service worker message handling.

Updated import to include the new useServiceWorkerMessage hook, which will be used to handle service worker communication.


59-63: Updated destructuring for useNotification hook.

Properly destructured to include the new invalidateNotification function.


78-88: Good implementation of service worker message handlers.

Added useServiceWorkerMessage hooks to invalidate cache when specific push messages are received, improving the real-time update capability of the application.

The comment explains the purpose clearly and the implementation correctly maps specific message types to the appropriate invalidation functions.


169-170: Well-defined custom easing function.

Added a customEasing array with carefully chosen values to cover layout shifting time, improving animation smoothness.


178-178: Animation transition improved with custom easing.

Applied the custom easing function to the main container animation, which should result in smoother transitions.


199-199: Enhanced notification banner entrance animation.

Doubled the initial y-offset from -10 to -20, which will make the entrance animation more noticeable and provide a smoother appearance.


207-209: Improved opacity transition with custom easing.

Updated the opacity transition to use the custom easing function instead of the default, providing a more consistent animation feel throughout the application.


227-227: Consistent animation updates across components.

Applied the same custom easing to all motion components in the page, ensuring a consistent animation experience throughout the UI.

Also applies to: 245-245


56-57:

Details

✅ Verification successful

Updated hook destructuring to include invalidation capability.

Now consuming the invalidateMainCard function from the useMainCard hook, but you're no longer destructuring isPending. Verify if this was intentional.


🏁 Script executed:

#!/bin/bash
# Check if isPending is used elsewhere in the file
rg "isMainCardPending" front-end/src/pages/main/MainPage.jsx

Length of output: 60


🏁 Script executed:

#!/bin/bash
# Check if 'isPending' is referenced anywhere in MainPage.jsx
rg "isPending" front-end/src/pages/main/MainPage.jsx

Length of output: 52


Attention: Invalidation Update Confirmed
After verifying the usage in the file, it appears that the previously destructured isPending property is not referenced anywhere in front-end/src/pages/main/MainPage.jsx. This suggests that its removal was intentional and does not affect any functionality. Please confirm that you do not plan to utilize a pending indicator in this component. If you intend to handle any asynchronous state indicators later, consider reintroducing it accordingly.

  • Verified that no instance of isPending is used.
  • Removal seems safe as long as no pending state logic is required.

Comment on lines +97 to +131
/**
* Service Worker로부터 메시지를 받는 Hook
* @param {function} onMessage - 메시지를 받았을 때 실행할 함수
* @param {string[]} messageTypes - 받을 메시지 타입
*/
export const useServiceWorkerMessage = (onMessage, messageTypes) => {
const allMessageType = useMemo(() => !messageTypes, [!!messageTypes]);

useEffect(() => {
const handleServiceWorkerMessage = (event) => {
const data = event.data;
if (allMessageType) {
onMessage(data);
} else if (messageTypes.includes(data.type)) {
onMessage(data);
}
};

if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener(
'message',
handleServiceWorkerMessage,
);
}

return () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.removeEventListener(
'message',
handleServiceWorkerMessage,
);
}
};
}, [messageTypes, allMessageType, onMessage]);
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Well-implemented service worker message hook.

The useServiceWorkerMessage hook provides a clean interface for components to listen for and respond to service worker messages, which aligns with the PR objectives.

However, there's an issue with the allMessageType memoization:

-  const allMessageType = useMemo(() => !messageTypes, [!!messageTypes]);
+  const allMessageType = useMemo(
+    () => !messageTypes || messageTypes.length === 0, 
+    [messageTypes]
+  );

The current implementation will not correctly detect an empty array, as !!messageTypes will be true for an empty array. This could lead to incorrect message filtering.

📝 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
/**
* Service Worker로부터 메시지를 받는 Hook
* @param {function} onMessage - 메시지를 받았을 실행할 함수
* @param {string[]} messageTypes - 받을 메시지 타입
*/
export const useServiceWorkerMessage = (onMessage, messageTypes) => {
const allMessageType = useMemo(() => !messageTypes, [!!messageTypes]);
useEffect(() => {
const handleServiceWorkerMessage = (event) => {
const data = event.data;
if (allMessageType) {
onMessage(data);
} else if (messageTypes.includes(data.type)) {
onMessage(data);
}
};
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener(
'message',
handleServiceWorkerMessage,
);
}
return () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.removeEventListener(
'message',
handleServiceWorkerMessage,
);
}
};
}, [messageTypes, allMessageType, onMessage]);
};
/**
* Service Worker로부터 메시지를 받는 Hook
* @param {function} onMessage - 메시지를 받았을 실행할 함수
* @param {string[]} messageTypes - 받을 메시지 타입
*/
export const useServiceWorkerMessage = (onMessage, messageTypes) => {
const allMessageType = useMemo(
() => !messageTypes || messageTypes.length === 0,
[messageTypes]
);
useEffect(() => {
const handleServiceWorkerMessage = (event) => {
const data = event.data;
if (allMessageType) {
onMessage(data);
} else if (messageTypes.includes(data.type)) {
onMessage(data);
}
};
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener(
'message',
handleServiceWorkerMessage,
);
}
return () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.removeEventListener(
'message',
handleServiceWorkerMessage,
);
}
};
}, [messageTypes, allMessageType, onMessage]);
};

'scheduleCreate',
'regularFeedbackRequest',
]);

Copy link
Collaborator

Choose a reason for hiding this comment

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

invalidate 함수들 별개로 만든거 보기좋군요

Copy link
Collaborator

@lsj1137 lsj1137 left a comment

Choose a reason for hiding this comment

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

고생하셨습니다~

@lsj1137 lsj1137 merged commit 4fef675 into develop Feb 27, 2025
4 checks passed
@lsj1137 lsj1137 deleted the FD-434--fe-issue branch February 27, 2025 09:36
@hammsik hammsik added FE 프론트엔드 풀 리퀘스트 feat 새 기능 추가 refactor labels Feb 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

FE 프론트엔드 풀 리퀘스트 feat 새 기능 추가 refactor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants