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 ETA null, Add Route Operator and Service Type Info, Reduce Duplicate Route No #202

Merged
merged 3 commits into from
Sep 13, 2024

Conversation

chengkeith
Copy link
Contributor

@chengkeith chengkeith commented Aug 31, 2024

Description

This PR includes three changes (each of which is an individual commit):

  1. Handle ETA may be null (and hence unable to sort ETA times) as a result of new code change in Let null ETA remain if there are no service with ETA on the route hk-bus-eta#3
  2. Add Route Company and Service Type Info (if any) in both Stop Dialog and Home Screen (Favourites/Nearby Routes)
  3. Reduce duplicate route no (hide special routes with higher service type value) in Home Screen (Nearby Routes)

The PR partially addresses some issues raised in Issue #200. The compiled version of this PR can also be found in https://alpha.hkbus.app/

Screenshots

At Stop Dialog
image

At Home Screen
image

Summary by CodeRabbit

  • New Features

    • Introduced a new serviceType property in the time report, enhancing the display with context-specific labels.
    • Added logic to prevent duplicate route entries in the nearby routes list, improving data accuracy.
  • Bug Fixes

    • Improved handling of empty arrays in transport sorting, ensuring robust output.

Copy link

coderabbitai bot commented Aug 31, 2024

Walkthrough

The changes introduce a new property, serviceType, to the SuccinctTimeReport component, impacting its rendering logic. The NearbyRouteList now includes an addedList array to prevent duplicate route entries. These modifications collectively refine the functionality and user experience across the affected components.

Changes

File Change Summary
src/components/home/SuccinctTimeReport.tsx Added serviceType to destructured props; conditional rendering for "特別班"; new style objects.
src/components/home/lists/NearbyRouteList.tsx Introduced addedList in getRoutes to prevent duplicate route entries.

Poem

In the meadow, I hop with glee,
New routes and times, oh what a spree!
With special trips and no repeats,
The world is bright, with tasty treats.
Let’s dance and play, so full of cheer,
For every change brings joy near! 🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 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

@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

Outside diff range, codebase verification and nitpick comments (2)
src/components/home/lists/NearbyRouteList.tsx (1)

Line range hint 132-158: Refactor suggestion for getRoutes function to improve performance and readability.

The getRoutes function has been modified to include a new array addedList to prevent duplicate route entries. This is a good approach to handle duplicates, but there are a few areas that could be improved for better performance and readability:

  1. Use of find in a loop: The current implementation uses find inside a nested loop, which can be inefficient for large datasets. Consider using a Set or a Map for addedList to check for existence in constant time.
  2. Complexity and readability: The nested loops and conditionals make the function quite complex. Refactoring to break down the function or using helper functions could improve readability.

Here's a suggested refactor using a Map to track added routes:

- const addedList = [] as [string, Company, string][];
+ const addedList = new Map<string, boolean>();

  const nearbyRoutes = Object.entries(stopList)
    .map((stop: [string, StopListEntry]): [string, StopListEntry, number] =>
      [...stop, getDistance(stop[1].location, geolocation)]
    )
    .filter((stop) => stop[2] < searchRange)
    .sort((a, b) => a[2] - b[2])
    .slice(0, 20)
    .reduce((acc, [stopId]) => {
      Object.entries(routeList).forEach(([key, route]) => {
        (["kmb", "lrtfeeder", "lightRail", "gmb", "ctb", "nlb"] as Company[]).forEach((co) => {
          if (route.stops[co] && route.stops[co].includes(stopId)) {
            if (acc[coToType[co]] === undefined) acc[coToType[co]] = [];
-           if(addedList.find(([_route, _co, _serviceType]) => _route == route.route && _co == co && _serviceType < route.serviceType) === undefined) {
+           const addedKey = `${route.route}-${co}-${route.serviceType}`;
+           if (!addedList.has(addedKey)) {
              acc[coToType[co]].push(key + "/" + route.stops[co].indexOf(stopId));
-             addedList.push([route.route, co, route.serviceType]);
+             addedList.set(addedKey, true);
            }
          });
        });
      });
      return acc;
    }, { bus: [], mtr: [], lightRail: [], minibus: [], ferry: [] } as Record<TransportType, string[]>);

This refactor uses a Map to store the combination of route, company, and service type as a key, which allows for constant time complexity checks and reduces the overhead of searching through an array.

Tools
Biome

[error] 151-152: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

src/components/home/SuccinctTimeReport.tsx (1)

Line range hint 101-294: Enhance SuccinctTimeReport component with service type handling and improve code readability.

The SuccinctTimeReport component has been updated to handle a new property serviceType, which is used to conditionally render additional information in the UI. This is a valuable addition for providing context to the users. However, there are a few areas that could be improved:

  1. Conditional rendering logic: The current implementation directly checks the serviceType within the JSX. This could be abstracted into a helper function to improve readability and maintainability.
  2. Styling: The new styles companySx and specialTripSx are defined at the bottom of the file. It's a good practice to keep related styles closer to their usage or abstract them into a separate file to improve the organization.

Here's a suggested refactor to abstract the conditional rendering and improve the organization of styles:

+ const renderSpecialTripInfo = (serviceType, t) => {
+   if (parseInt(serviceType, 10) >= 2) {
+     return (
+       <Typography variant="caption" sx={specialTripSx}>
+         {t("特別班")}
+       </Typography>
+     );
+   }
+   return null;
+ };

  return (
    <>
      <ListItem onClick={handleClick} sx={rootSx}>
        <ListItemText
          primary={
            <Box overflow="hidden">
              <RouteNo
                routeNo={language === "zh" ? t(routeNo) : routeNo}
                fontSize={co[0] === "mtr" ? "1.1rem" : undefined}
              />
-             {parseInt(serviceType, 10) >= 2 && (
-               <Typography variant="caption" sx={specialTripSx}>
-                 {t("特別班")}
-               </Typography>
-             )}
+             {renderSpecialTripInfo(serviceType, t)}
            </Box>
          }
          secondary={
            <Typography component="h4" variant="caption" sx={companySx}>
              {co.map((co) => t(co)).join("+")}
            </Typography>
          }
        />
        ...
      </ListItem>
      ...
    </>
  );

This refactor introduces a helper function renderSpecialTripInfo that encapsulates the logic for rendering the special trip information based on the serviceType. This makes the component more readable and easier to maintain.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 57d3acd and 337bed1.

Files selected for processing (3)
  • src/components/home/SuccinctTimeReport.tsx (3 hunks)
  • src/components/home/lists/NearbyRouteList.tsx (2 hunks)
  • src/hooks/useStopEtas.tsx (1 hunks)

Comment on lines +203 to +205
a = a.filter((e) => e.eta);
b = b.filter((e) => e.eta);
if (a.length === 0 && b.length === 0) return keyA < keyB ? -1 : 1;
Copy link

Choose a reason for hiding this comment

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

Improve sorting logic in useStopEtas hook for better performance and clarity.

The useStopEtas hook has been updated to include additional filtering logic to handle cases where both filtered arrays are empty, returning a comparison based on the keys. This is a crucial update for handling edge cases more gracefully. However, the current implementation could be optimized further:

  1. Filtering logic: The filtering of eta values is done inline within the sorting function. This could be moved outside the sort function to avoid repeated computation.
  2. Comparison logic: The comparison logic is somewhat convoluted and could be simplified for better readability.

Here's a suggested refactor to optimize the filtering and comparison logic:

- a = a.filter((e) => e.eta);
- b = b.filter((e) => e.eta);
+ const filteredA = a.filter((e) => e.eta);
+ const filteredB = b.filter((e) => e.eta);

- if (a.length === 0 && b.length === 0) return keyA < keyB ? -1 : 1;
- if (a.length === 0) return 1;
- if (b.length === 0) return -1;
+ if (filteredA.length === 0 && filteredB.length === 0) return keyA.localeCompare(keyB);
+ if (filteredA.length === 0) return 1;
+ if (filteredB.length === 0) return -1;

  if (isLightRail) {
    if (filteredA[0].remark.zh === filteredB[0].remark.zh) {
      return filteredA[0].eta < filteredB[0].eta ? -1 : 1;
    }
    return filteredA[0].remark.zh < filteredB[0].remark.zh ? -1 : 1;
  }
  if (filteredA[0].eta === filteredB[0].eta) {
    return keyA.localeCompare(keyB);
  }
  return filteredA[0].eta < filteredB[0].eta ? -1 : 1;

This refactor moves the filtering logic outside the sort function, reducing the complexity and improving performance by avoiding repeated filtering. Additionally, the comparison logic is simplified using localeCompare for string comparisons, which is more robust and readable.

Committable suggestion was skipped due to low confidence.

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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 337bed1 and 8041902.

Files selected for processing (2)
  • src/components/home/SuccinctTimeReport.tsx (3 hunks)
  • src/components/home/lists/NearbyRouteList.tsx (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • src/components/home/SuccinctTimeReport.tsx
  • src/components/home/lists/NearbyRouteList.tsx

@chengkeith
Copy link
Contributor Author

Description

  • New commit fixed "Special Route" text colour in stop dialog in dark mode

Screenshot

image

@chunlaw chunlaw merged commit fece3fa into hkbus:master Sep 13, 2024
2 checks passed
@chengkeith chengkeith deleted the fix-eta-null branch September 15, 2024 10:15
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.

2 participants