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

Fix : View(list/card/board) retention for encounters/resource/users pages #10039

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

Mahendar0701
Copy link
Contributor

@Mahendar0701 Mahendar0701 commented Jan 18, 2025

Proposed Changes

view.mp4

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new view management system with local storage synchronization
    • Added dynamic view switching for resources, users, and appointments
  • Improvements

    • Simplified view state management across multiple components
    • Enhanced login process with view cache invalidation
  • Bug Fixes

    • Resolved inconsistent view state handling across different sections of the application
  • Chores

    • Refactored routing and view management logic
    • Updated component implementations to use new view utility hooks

Copy link
Contributor

coderabbitai bot commented Jan 18, 2025

Walkthrough

This pull request introduces a comprehensive view management system across multiple components. The changes focus on implementing persistent view state retention using a new custom hook useView and a utility module ViewCache. The modifications affect routing in ResourceRoutes, state management in components like ResourceBoard, ResourceList, FacilityUsers, and AppointmentsPage, and add a new View component to handle dynamic view rendering.

Changes

File Change Summary
src/Routers/routes/ResourceRoutes.tsx Removed Redirect component, introduced new View component with simplified routing
src/Utils/ViewCache.ts Added utility functions to manage view preferences in local storage
src/Utils/useView.ts New custom React hook for synchronizing view state with local storage
src/components/Auth/Login.tsx Added ViewCache.invalidateAll() during login submission
src/components/Common/View.tsx New component for dynamic view rendering using useView hook
src/components/Facility/FacilityUsers.tsx Replaced useState with useView for activeTab management
src/components/Resource/ResourceBoard.tsx Integrated useView for view state management
src/components/Resource/ResourceList.tsx Replaced navigation-based view switching with useView
src/pages/Appointments/AppointmentsPage.tsx Updated view mode management using useView hook

Assessment against linked issues

Objective Addressed Explanation
View retention when navigating away and revisiting

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 Hopping through code with glee,
Views now dance, persistently free!
Local storage, our trusty friend,
Remembering states that never end.
A rabbit's magic, view retention's art! 🌈

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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.

Copy link

netlify bot commented Jan 18, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 2a41942
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/678b4f9a5859ff00089bc6b8
😎 Deploy Preview https://deploy-preview-10039--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@Mahendar0701 Mahendar0701 marked this pull request as ready for review January 18, 2025 06:53
@Mahendar0701 Mahendar0701 requested a review from a team as a code owner January 18, 2025 06:53
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: 2

🧹 Nitpick comments (7)
src/Utils/ViewCache.ts (2)

1-3: Add namespace prefix to localStorage keys.

The getKey function should include a namespace prefix to prevent potential naming conflicts with other localStorage keys used in the application.

 const getKey = (name: string) => {
-  return `${name}`;
+  return `view_preference_${name}`;
 };

15-18: Use TypeScript enum or const for view keys.

Consider using a TypeScript enum or const object to maintain type safety and centralize the view keys configuration.

export const VIEW_TYPES = {
  USERS: 'users',
  RESOURCE: 'resource',
  APPOINTMENTS: 'appointments'
} as const;

const invalidateAll = () => {
  Object.values(VIEW_TYPES).forEach(invalidate);
};
src/components/Common/View.tsx (2)

14-14: Extract default view as a prop.

The default view ("board") is hardcoded in the useView hook call. Consider making it configurable through props.

+interface ViewProps {
+  name: typeof VIEW_TYPES[keyof typeof VIEW_TYPES];
+  board: ComponentType;
+  list: ComponentType;
+  defaultView?: "board" | "list";
+}

-const [view] = useView(name, "board");
+const [view] = useView(name, props.defaultView ?? "board");

21-21: Improve type safety for view selection.

The type assertion in view as keyof typeof views could be unsafe. Consider adding runtime validation.

-const SelectedView = views[view as keyof typeof views] || board;
+const isValidView = (v: string): v is keyof typeof views => 
+  v === "board" || v === "list";
+const SelectedView = isValidView(view) ? views[view] : board;
src/Utils/useView.ts (1)

10-13: Add error handling for localStorage operations.

The localStorage operations should be wrapped in try-catch blocks to handle potential errors (e.g., when storage is full or disabled).

 const updateView = (newView: string) => {
-  localStorage.setItem(name, newView);
-  setView(newView);
+  try {
+    localStorage.setItem(name, newView);
+    setView(newView);
+  } catch (error) {
+    console.error(`Failed to update view preference: ${error}`);
+    setView(newView); // Still update state even if storage fails
+  }
 };
src/components/Facility/FacilityUsers.tsx (1)

126-126: Remove debugging console.log statement.

This console.log statement appears to be a debugging artifact and should be removed.

-  console.log("activeTab", activeTab);
src/components/Auth/Login.tsx (1)

33-33: Move cache invalidation after validation.

The cache invalidation should occur only after successful validation to avoid unnecessary cache clearing.

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
-   ViewCache.invalidateAll();
    const validated = validateData();
    if (!validated) return;
+   ViewCache.invalidateAll();

    staffLoginMutation.mutate(validated);
  };

Also applies to: 246-246

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c5c52b6 and 2a41942.

📒 Files selected for processing (9)
  • src/Routers/routes/ResourceRoutes.tsx (1 hunks)
  • src/Utils/ViewCache.ts (1 hunks)
  • src/Utils/useView.ts (1 hunks)
  • src/components/Auth/Login.tsx (2 hunks)
  • src/components/Common/View.tsx (1 hunks)
  • src/components/Facility/FacilityUsers.tsx (3 hunks)
  • src/components/Resource/ResourceBoard.tsx (3 hunks)
  • src/components/Resource/ResourceList.tsx (3 hunks)
  • src/pages/Appointments/AppointmentsPage.tsx (4 hunks)
🔇 Additional comments (8)
src/Routers/routes/ResourceRoutes.tsx (1)

10-10: LGTM! Clean implementation of view routing.

The routing implementation is simplified and well-structured, properly utilizing the new View component.

src/components/Resource/ResourceBoard.tsx (1)

27-27: LGTM! View state management has been simplified.

The changes effectively centralize view state management using the useView hook, removing the need for explicit navigation and local storage manipulation.

Also applies to: 40-40, 97-97

src/components/Facility/FacilityUsers.tsx (1)

19-19: LGTM! View state management has been updated consistently.

The changes align with the PR objective by implementing view retention using the useView hook.

Also applies to: 124-124

src/components/Resource/ResourceList.tsx (1)

23-23: LGTM! View state management has been simplified consistently.

The changes align with the broader refactor by:

  1. Using the useView hook for centralized view state management.
  2. Removing navigation-based view switching.
  3. Simplifying the control flow.

Also applies to: 28-28, 223-223

src/pages/Appointments/AppointmentsPage.tsx (4)

68-68: LGTM! Clean import of the view retention hook.

The import of useView hook aligns with the PR objective of implementing view retention.


332-333: LGTM! Proper implementation of the Tabs component.

The Tabs component is correctly configured with the new activeTab state and includes proper type casting in the onValueChange handler.


641-641: LGTM! Clean conditional rendering implementation.

The ternary operator provides a clean way to toggle between board and list views based on the activeTab state.


242-242: Implementation of view retention looks good.

The useView hook is properly configured with "appointments" namespace and "board" as the default view.

Let's verify the view persistence across navigation:

✅ Verification successful

View persistence implementation verified successfully

The useView hook implementation properly handles view persistence using localStorage with cross-tab synchronization. The single usage with "appointments" namespace prevents any state conflicts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of useView hook across the codebase
# Expect: No conflicting implementations using the same namespace

# Search for other usages of the appointments namespace
rg "useView\(['\"]appointments['\"]" -A 2

Length of output: 293


Script:

#!/bin/bash
# Search for the useView hook implementation
ast-grep --pattern 'const useView = $_'

# Also search for any exports of useView
rg "export.*useView"

Length of output: 110


Script:

#!/bin/bash
# Get the implementation of useView
cat src/Utils/useView.ts

Length of output: 709

src/components/Common/View.tsx Show resolved Hide resolved
Comment on lines +14 to +24
useEffect(() => {
const interval = setInterval(() => {
const storedView = localStorage.getItem(name);
if (storedView !== view) {
setView(storedView || defaultView);
}
}, 100);
return () => {
clearInterval(interval);
};
}, [name, view]);
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

Replace polling with storage event listener.

The current implementation uses polling with a 100ms interval, which is inefficient. Consider using the storage event listener instead.

 useEffect(() => {
-  const interval = setInterval(() => {
+  const handleStorageChange = (e: StorageEvent) => {
+    if (e.key === name) {
+      const storedView = e.newValue;
+      if (storedView !== view) {
+        setView(storedView || defaultView);
+      }
+    }
+  };
+
+  window.addEventListener('storage', handleStorageChange);
+  return () => {
+    window.removeEventListener('storage', handleStorageChange);
+  };
-    const storedView = localStorage.getItem(name);
-    if (storedView !== view) {
-      setView(storedView || defaultView);
-    }
-  }, 100);
-  return () => {
-    clearInterval(interval);
-  };
 }, [name, view]);
📝 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
useEffect(() => {
const interval = setInterval(() => {
const storedView = localStorage.getItem(name);
if (storedView !== view) {
setView(storedView || defaultView);
}
}, 100);
return () => {
clearInterval(interval);
};
}, [name, view]);
useEffect(() => {
const handleStorageChange = (e: StorageEvent) => {
if (e.key === name) {
const storedView = e.newValue;
if (storedView !== view) {
setView(storedView || defaultView);
}
}
};
window.addEventListener('storage', handleStorageChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
};
}, [name, view]);

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This wont be needed once #9768 gets merged

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

View retention in appoinments, resource and users page
1 participant