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

Display Descriptive Names in Breadcrumbs Instead of External IDs #9863

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

DonXavierdev
Copy link
Contributor

@DonXavierdev DonXavierdev commented Jan 9, 2025

Proposed Changes

@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

  • New Features
    • Enhanced Breadcrumbs component with dynamic name fetching for facilities, patients, and encounters
    • Implemented intelligent loading of entity names based on path segments
    • Added support for displaying "Loading..." while names are being retrieved

@DonXavierdev DonXavierdev requested a review from a team as a code owner January 9, 2025 15:12
Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

The pull request enhances the Breadcrumbs component by introducing dynamic name fetching for facilities, patients, and encounters. New asynchronous functions are implemented to retrieve names based on IDs from the current path. The component now intelligently identifies ID segments, fetches corresponding names via API calls, and updates the breadcrumbs display accordingly. This allows for more informative and context-aware navigation by replacing raw IDs with human-readable names during rendering.

Changes

File Change Summary
src/components/Common/Breadcrumbs.tsx - Added fetchFacilityName, fetchPatientName, and fetchEncounterName functions
- Implemented fetchNames function to handle dynamic name retrieval
- Modified useEffect to trigger name fetching
- Updated breadcrumbs mapping to use fetched names

Assessment against linked issues

Objective Addressed Explanation
Replace External IDs with names [#9822]

Possibly related PRs

Suggested labels

tested

Suggested reviewers

  • Jacobjeevan
  • rithviknishad

Poem

🐰 Hop along the breadcrumb trail,
Where IDs transform without fail,
Names bloom like spring's first light,
Replacing numbers cold and tight,
A rabbit's magic makes paths bright! 🌟

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. (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 9, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit e320caf
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/677fe76f6c874d0008458135
😎 Deploy Preview https://deploy-preview-9863--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.

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 (4)
src/components/Common/Breadcrumbs.tsx (4)

3-3: Consider wrapping async operations in an error boundary

While the new imports support the async functionality, consider implementing a React Error Boundary to gracefully handle any potential API failures at the component level, preventing the entire navigation from breaking.

Also applies to: 23-24


87-97: Improve encounter date formatting

The encounter date concatenation could benefit from proper date formatting and localization.

-      return "Encounter on " + response.data?.period.start || id;
+      const date = new Date(response.data?.period.start);
+      return `Encounter on ${date.toLocaleDateString()}` || id;

99-117: Refactor ID type detection for better maintainability

The current implementation uses sequential if-else statements which could become harder to maintain as more types are added. Consider using a mapping object for better maintainability.

+ const ID_TYPE_MAPPING = {
+   facility: "facility",
+   patient: "patient",
+   encounter: "encounter"
+ };

  const idQueries = path
    ?.slice(1)
    .split("/")
    .map((field, i, arr) => {
      const isId = /^[0-9a-fA-F-]{36}$/.test(field);
      const prevBreadcrumb = arr[i - 1];

-      if (isId) {
-        if (prevBreadcrumb === "facility") {
-          return { id: field, type: "facility" };
-        } else if (prevBreadcrumb === "patient") {
-          return { id: field, type: "patient" };
-        } else if (prevBreadcrumb === "encounter") {
-          return { id: field, type: "encounter" };
-        }
-      }
+      if (isId && prevBreadcrumb in ID_TYPE_MAPPING) {
+        return { id: field, type: ID_TYPE_MAPPING[prevBreadcrumb] };
+      }
      return null;
    })

153-170: Enhance loading and error state UI

The current implementation uses a simple "Loading..." text. Consider implementing a more user-friendly loading state and error handling UI.

-          (isId
-            ? names[field] || "Loading..."
-            : MENU_TAGS[field] || capitalize(field)),
+          (isId
+            ? names[field] === undefined
+              ? <span className="animate-pulse">Loading...</span>
+              : names[field].startsWith("Error")
+                ? <span className="text-red-500">{names[field]}</span>
+                : names[field]
+            : MENU_TAGS[field] || capitalize(field)),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f0589e6 and e320caf.

📒 Files selected for processing (1)
  • src/components/Common/Breadcrumbs.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Test
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (1)
src/components/Common/Breadcrumbs.tsx (1)

Line range hint 1-170: Implementation successfully addresses the PR objectives

The changes effectively replace external IDs with descriptive names in the breadcrumbs, improving the user experience as intended. While there are suggestions for improvements, the core functionality is well-implemented.

Comment on lines +141 to +148
useEffect(() => {
const getNames = async () => {
const fetchedNames = await fetchNames();
setNames(fetchedNames);
};

getNames();
}, [path]);
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

Implement proper cleanup and caching

The current implementation lacks cleanup for pending requests and doesn't cache previously fetched names. This could lead to unnecessary API calls and potential memory leaks.

 useEffect(() => {
+  const controller = new AbortController();
   const getNames = async () => {
     const fetchedNames = await fetchNames();
     setNames(fetchedNames);
   };

   getNames();
+  return () => controller.abort();
 }, [path]);

Consider implementing a caching mechanism to store previously fetched names:

const [nameCache, setNameCache] = useState<Record<string, string>>({});

const fetchNames = async () => {
  const results: Record<string, string> = {};
  
  for (const query of idQueries || []) {
    if (query?.id in nameCache) {
      results[query.id] = nameCache[query.id];
      continue;
    }
    // ... existing fetch logic
  }
  
  setNameCache(prev => ({...prev, ...results}));
  return results;
};

Comment on lines +65 to +75
const fetchFacilityName = async (id: string) => {
try {
const response = await request(routes.getAnyFacility, {
pathParams: { id },
});
return response.data?.name || id;
} catch (error) {
console.error("Error fetching facility name:", error);
return "Error fetching facility";
}
};
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

Enhance error handling with user-friendly messages

The current error handling returns a generic message. Consider providing more context-specific messages and implementing proper error tracking.

 } catch (error) {
-  console.error("Error fetching facility name:", error);
-  return "Error fetching facility";
+  console.error("Failed to fetch facility name:", { id, error });
+  return `Facility ${id.slice(0, 8)}...`;
 }
📝 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
const fetchFacilityName = async (id: string) => {
try {
const response = await request(routes.getAnyFacility, {
pathParams: { id },
});
return response.data?.name || id;
} catch (error) {
console.error("Error fetching facility name:", error);
return "Error fetching facility";
}
};
const fetchFacilityName = async (id: string) => {
try {
const response = await request(routes.getAnyFacility, {
pathParams: { id },
});
return response.data?.name || id;
} catch (error) {
console.error("Failed to fetch facility name:", { id, error });
return `Facility ${id.slice(0, 8)}...`;
}
};

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.

Replace External IDs in breadcrumbs with names
1 participant