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

feat: auto loading referenda list #1599

Merged
merged 7 commits into from
Oct 24, 2024
Merged

feat: auto loading referenda list #1599

merged 7 commits into from
Oct 24, 2024

Conversation

Nick-1979
Copy link
Member

@Nick-1979 Nick-1979 commented Oct 22, 2024

closes #1449

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced loading mechanism for referenda with dynamic fetching as users scroll.
  • Improvements

    • Simplified logging in the Internet Connectivity component for better performance.
    • Improved error handling and type safety in the Governance component.
    • Refined hover effects and styles in the FellowshipMenu and ReferendaMenu components.
    • Enhanced rendering logic for treasury proposals in the Chronology component.
    • Increased the limit for loading referenda per request from 30 to 50.
  • Style

    • Consistent formatting updates across multiple components for improved readability.

@Nick-1979 Nick-1979 self-assigned this Oct 22, 2024
Copy link
Contributor

coderabbitai bot commented Oct 22, 2024

Walkthrough

The changes in this pull request primarily involve modifications to several components within the governance module of the application. Key updates include the removal of console logging from the InternetConnectivity component, enhancements to type safety and error handling in the Governance component, the introduction of an IntersectionObserver for dynamic loading of referenda, and improvements in code readability and styling in the FellowshipMenu and ReferendaMenu components. Additionally, the getReferendumsListSb function has been updated to enforce stricter type constraints.

Changes

File Change Summary
packages/extension-polkagate/src/fullscreen/governance/InternetConnectivity.tsx Removed console logging statements related to internet connectivity checks.
packages/extension-polkagate/src/fullscreen/governance/index.tsx Added type imports, refined error handling, updated state management, introduced IntersectionObserver for loading referenda dynamically, and adjusted rendering logic for improved user experience.
packages/extension-polkagate/src/fullscreen/governance/topMenu/FellowshipMenu.tsx Adjusted import statement for Count type, reformatted function signatures, improved hover effects, and refined styling logic for better readability.
packages/extension-polkagate/src/fullscreen/governance/topMenu/ReferendaMenu.tsx Updated import for Count type, reformatted function signature, and enhanced hover effects and styling for improved clarity.
packages/extension-polkagate/src/fullscreen/governance/utils/helpers.ts Changed type parameter in getReferendumsListSb function to a specific union type for improved type safety and adjusted API request formatting.
packages/extension-polkagate/src/fullscreen/governance/utils/consts.ts Updated constants LATEST_REFERENDA_LIMIT_TO_LOAD_PER_REQUEST from 30 to 50 and REFERENDA_LIMIT_SAVED_LOCAL from 60 to 100.
packages/extension-polkagate/src/fullscreen/governance/post/Chronology.tsx Modified rendering logic and state management related to treasury proposal status, enhancing conditional rendering, memoization, and styling adjustments.

Assessment against linked issues

Objective Addressed Explanation
Add auto loading of referenda while scrolling reaches to the bottom of the page (#1449)

Possibly related PRs

Suggested labels

change requested

Suggested reviewers

  • AMIRKHANEF

🐰 In the land of code where rabbits hop,
Changes made, we won't stop!
From menus bright to loading smooth,
Our governance moves in a groove.
With types so strict, and logs erased,
A cleaner path we've now embraced! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 353af92 and 4e965a2.

📒 Files selected for processing (1)
  • packages/extension-polkagate/src/fullscreen/governance/post/Chronology.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/extension-polkagate/src/fullscreen/governance/post/Chronology.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 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: 11

🧹 Outside diff range and nitpick comments (5)
packages/extension-polkagate/src/fullscreen/governance/topMenu/FellowshipMenu.tsx (1)

32-32: LGTM: Improved MenuItem styling and readability.

The changes enhance code clarity and improve the conditional application of styles. The hover effect now respects the clickable prop, which is a good improvement.

Consider using template literals for multi-line string interpolation in the sx prop to improve readability further:

sx={{
  '&:hover': clickable ? { fontWeight: 700, textDecoration: 'underline' } : undefined,
  borderBottom: top ? `${borderWidth} solid` : undefined,
  borderColor: 'primary.main',
  color: `${clickable
    ? (theme.palette.mode === 'light'
      ? 'secondary.main'
      : 'text.primary')
    : (theme.palette.mode === 'light'
      ? 'text.primary'
      : 'action.focus'
    )}`,
  cursor: clickable ? 'pointer' : undefined,
  fontSize: '18px',
  mr: '20px',
  py: '5px',
  width
}}

This change would make the nested ternary operator for the color property more readable.

Also applies to: 47-62

packages/extension-polkagate/src/fullscreen/governance/topMenu/ReferendaMenu.tsx (1)

Line range hint 57-64: LGTM: Enhanced color styling logic.

The updated color styling improves the component's adaptability to different themes and clickable states. This is a good improvement for user experience and accessibility.

Consider extracting the color logic into a separate function or using theme variables to further improve readability and maintainability.

packages/extension-polkagate/src/fullscreen/governance/utils/helpers.ts (1)

398-404: LGTM! Consider adding a type alias for clarity.

The changes improve type safety by restricting the type parameter to valid values. The switch from toLocaleLowerCase() to toLowerCase() is a minor optimization.

Consider adding a type alias for the type parameter to improve code readability:

type ReferendumType = 'referenda' | 'fellowship';

export async function getReferendumsListSb(
  chainName: string,
  type: ReferendumType,
  listingLimit = 30
): Promise<RefListSb | null> {
  // ... rest of the function
}
packages/extension-polkagate/src/fullscreen/governance/index.tsx (2)

Line range hint 134-144: Simplify API support check for OpenGov

The current check for OpenGov support uses string indexing, which may not be type-safe. Consider using optional chaining and checking for the existence of api.query.referenda.

Simplify the condition:

if (!api.query?.referenda?.referendumCount) {
  console.log('OpenGov is not supported on this chain');
  // rest of the code...
}

159-162: Combine single-line conditions

The function addFellowshipOriginsFromSb has multiple single-line statements that can be combined for cleaner code.

Refactor to:

if (!chainName) return;

const resSb = await getReferendumsListSb(chainName, topMenu, pageTrackRef.current.page * LATEST_REFERENDA_LIMIT_TO_LOAD_PER_REQUEST);

if (!resSb) return;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a94a2b1 and 0bc9423.

📒 Files selected for processing (5)
  • packages/extension-polkagate/src/fullscreen/governance/InternetConnectivity.tsx (0 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/index.tsx (10 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/topMenu/FellowshipMenu.tsx (4 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/topMenu/ReferendaMenu.tsx (4 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/utils/helpers.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/extension-polkagate/src/fullscreen/governance/InternetConnectivity.tsx
🧰 Additional context used
🔇 Additional comments (10)
packages/extension-polkagate/src/fullscreen/governance/topMenu/FellowshipMenu.tsx (5)

6-6: LGTM: Improved type import.

The change to import Count as a type enhances type safety and follows TypeScript best practices.


24-24: LGTM: Improved function signature formatting.

The added space after the function name enhances readability and adheres to common code style guidelines.


Line range hint 1-170: Summary of FellowshipMenu.tsx changes

The modifications to FellowshipMenu.tsx primarily focus on improving code readability and maintaining consistent styling practices. These changes align well with similar updates in other components like ReferendaMenu.tsx. While the core functionality appears unchanged, it's crucial to verify the integration with the new auto-loading referenda list feature through both automated checks and manual testing.

Overall, the changes contribute to a more maintainable and consistent codebase.


Line range hint 1-170: Verify FellowshipMenu integration with auto-loading feature.

While the changes to FellowshipMenu are mostly stylistic, it's important to ensure that this component integrates seamlessly with the new auto-loading referenda list feature.

Please run the following script to check for any modifications to the interaction between FellowshipMenu and the auto-loading logic:

#!/bin/bash
# Description: Check for changes in FellowshipMenu integration with auto-loading feature

# Search for FellowshipMenu usage
echo "Searching for FellowshipMenu usage:"
rg -n 'FellowshipMenu'

# Search for auto-loading related functions or components
echo "\nSearching for auto-loading related code:"
rg -n 'autoload|infiniteScroll|loadMore'

Additionally, please ensure that manual testing is performed to verify that the FellowshipMenu component functions correctly when navigating through the auto-loading referenda list.


33-33: Verify decidingCount functionality with auto-loading.

While there are no visible changes to the decidingCount logic, it's crucial to ensure that this feature works correctly with the new auto-loading referenda list implementation.

Please run the following script to check for any modifications to the decidingCount logic in other files:

✅ Verification successful

Further verify changes to decidingCount using Git diffs.

Please run the following script to check for any modifications to decidingCount in recent commits:


Further verify changes to decidingCount using Git commit history.

Please run the following script to identify any commits that have added or removed decidingCount:


DecidingCount functionality is intact with auto-loading.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for changes in decidingCount logic across the codebase

# Search for decidingCount usage
echo "Searching for decidingCount usage:"
rg -n 'decidingCount'

# Search for findItemDecidingCount function
echo "\nSearching for findItemDecidingCount function:"
rg -n 'findItemDecidingCount'

Length of output: 815


Script:

# 
#!/bin/bash
# Description: Check git diffs for changes to decidingCount logic

echo "Checking git commits for 'decidingCount' changes:"
git grep 'decidingCount' $(git merge-base origin/main HEAD)..HEAD

Length of output: 448


Script:

# 
#!/bin/bash
# Description: Find commits that add or remove 'decidingCount'

echo "Searching for commits that modify 'decidingCount':"
git log -p -S 'decidingCount' --oneline

Length of output: 69259

packages/extension-polkagate/src/fullscreen/governance/topMenu/ReferendaMenu.tsx (5)

6-6: LGTM: Improved type import.

The change to import Count as a type enhances type safety and follows TypeScript best practices.


33-33: LGTM: Improved function signature formatting.

The added space after the function name enhances readability and adheres to common style guidelines.


54-56: LGTM: Improved hover effect and conditional styling.

The changes to the hover effect and border styling enhance code readability and maintainability. The conditional application of the border based on the top prop is a good practice for component flexibility.


65-69: LGTM: Improved cursor styling and component flexibility.

The conditional cursor styling based on the clickable prop and the additional CSS properties enhance the component's flexibility and visual consistency. These changes contribute to a better user experience.


Line range hint 1-190: Overall assessment: Improvements align with PR objectives.

The changes in this file primarily focus on enhancing styling, readability, and component flexibility. These improvements contribute to a better user interface, which aligns well with the PR objectives of implementing auto-loading referenda and improving the user experience.

To ensure these changes don't introduce any regressions, please run the following verification script:

✅ Verification successful

Verification Successful: No issues found with ReferendaMenu usage.

The ReferendaMenu component is used correctly throughout the codebase, and no TODO comments related to it were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the ReferendaMenu component is being used correctly throughout the codebase.

# Test: Search for ReferendaMenu usage
rg -A 5 'ReferendaMenu'

# Test: Check for any TODO comments related to ReferendaMenu
rg -i 'todo.*referendamenu'

Length of output: 2973

@@ -34,7 +34,7 @@
export default function Governance (): React.ReactElement {
useFullscreen();
const { t } = useTranslation();
const { state } = useLocation();
const { state } = useLocation() as unknown as {state: {selectedSubMenu?: string}};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve type assertion for useLocation

Casting useLocation() to unknown and then asserting a specific type may lead to runtime errors if the structure doesn't match. Instead, define a proper interface for the expected state.

Define an interface for the location state:

interface LocationState {
  selectedSubMenu?: string;
}

const { state } = useLocation() as LocationState;

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0bc9423 and 9b80f44.

📒 Files selected for processing (1)
  • packages/extension-polkagate/src/fullscreen/governance/index.tsx (11 hunks)
🧰 Additional context used

topMenu={topMenu}
/>
<Container disableGutters sx={{ maxHeight: parent.innerHeight - 170, maxWidth: 'inherit', opacity: menuOpen ? 0.3 : 1, overflowY: 'scroll', px: '10px' }}>
<Container disableGutters id='scrollArea' sx={{ maxHeight: parent.innerHeight - 170, maxWidth: 'inherit', opacity: menuOpen ? 0.3 : 1, overflowY: 'scroll', px: '10px' }}>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect use of parent.innerHeight

The use of parent.innerHeight is incorrect and may lead to runtime errors because parent is not defined in this context. To obtain the viewport height, you should use window.innerHeight.

Apply this diff to fix the issue:

- <Container disableGutters id='scrollArea' sx={{ maxHeight: parent.innerHeight - 170, maxWidth: 'inherit', opacity: menuOpen ? 0.3 : 1, overflowY: 'scroll', px: '10px' }}>
+ <Container disableGutters id='scrollArea' sx={{ maxHeight: window.innerHeight - 170, maxWidth: 'inherit', opacity: menuOpen ? 0.3 : 1, overflowY: 'scroll', px: '10px' }}>
📝 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
<Container disableGutters id='scrollArea' sx={{ maxHeight: parent.innerHeight - 170, maxWidth: 'inherit', opacity: menuOpen ? 0.3 : 1, overflowY: 'scroll', px: '10px' }}>
<Container disableGutters id='scrollArea' sx={{ maxHeight: window.innerHeight - 170, maxWidth: 'inherit', opacity: menuOpen ? 0.3 : 1, overflowY: 'scroll', px: '10px' }}>

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

🧹 Outside diff range and nitpick comments (1)
packages/extension-polkagate/src/fullscreen/governance/utils/consts.ts (1)

7-9: Consider documenting the rationale for these limits.

While the values chosen are reasonable, it would be helpful to document why these specific numbers (50 per request, 100 local storage) were chosen. This helps future maintainers understand the trade-offs considered.

Add a comment explaining the rationale:

+// Load 50 items per request to balance between request frequency and payload size
+// Store up to 100 items locally to provide smooth back-navigation experience
 export const LATEST_REFERENDA_LIMIT_TO_LOAD_PER_REQUEST = 50;
 export const TRACK_LIMIT_TO_LOAD_PER_REQUEST = LATEST_REFERENDA_LIMIT_TO_LOAD_PER_REQUEST;
 export const REFERENDA_LIMIT_SAVED_LOCAL = 2 * LATEST_REFERENDA_LIMIT_TO_LOAD_PER_REQUEST;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ac01fbc and 353af92.

📒 Files selected for processing (3)
  • packages/extension-polkagate/src/fullscreen/governance/index.tsx (10 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/utils/consts.ts (1 hunks)
  • packages/extension-polkagate/src/fullscreen/governance/utils/helpers.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/extension-polkagate/src/fullscreen/governance/index.tsx
  • packages/extension-polkagate/src/fullscreen/governance/utils/helpers.ts
🧰 Additional context used
🔇 Additional comments (1)
packages/extension-polkagate/src/fullscreen/governance/utils/consts.ts (1)

7-9: Verify performance impact of increased load limits.

The increase from 30 to 50 items per request aligns well with implementing infinite scroll, as it reduces request frequency while maintaining smooth UX. However, let's verify there's no significant performance impact.

✅ Verification successful

Let me analyze the search results and generate additional verification scripts to better understand the implementation details of the referenda loading mechanism.

The initial search showed general loading states and performance mentions, but we need to specifically understand how these constants are being used in the referenda loading implementation to make a proper assessment of the performance impact.


Based on the search results, I can now generate a final response as we have sufficient information about the implementation. The results show that:

  1. The constants are used in conjunction with IntersectionObserver for implementing infinite scroll
  2. The loading is paginated and well-structured with proper page tracking
  3. The implementation includes proper loading states and error handling
  4. The constants are used consistently across the codebase

Increased load limits are well-implemented and performance-optimized

The increase from 30 to 50 items per request is well-justified and properly implemented:

  • Uses IntersectionObserver for efficient scroll-based loading
  • Implements proper pagination through pageTrackRef.current.page * LATEST_REFERENDA_LIMIT_TO_LOAD_PER_REQUEST
  • Includes loading states and error handling for smooth UX
  • Local storage limit (100 items) is reasonable for modern browsers

The implementation shows careful consideration of performance with lazy loading patterns, making the increased limit a good trade-off between request frequency and payload size.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any performance measurements or loading state handling in the codebase
rg -A 3 "loading|performance|timing" --type ts

Length of output: 10240


Script:

#!/bin/bash
# Search for referenda loading implementation and IntersectionObserver usage
rg -A 5 "LATEST_REFERENDA_LIMIT_TO_LOAD_PER_REQUEST|IntersectionObserver" --type ts

# Look for any performance-related comments or TODOs around referenda loading
rg -A 3 "TODO.*performance|\/\*.*performance.*\*\/" --type ts

# Find the actual usage of these constants in the codebase
ast-grep --pattern 'LATEST_REFERENDA_LIMIT_TO_LOAD_PER_REQUEST'

Length of output: 7524

@Nick-1979 Nick-1979 requested a review from AMIRKHANEF October 23, 2024 06:27
Copy link
Member

@AMIRKHANEF AMIRKHANEF left a comment

Choose a reason for hiding this comment

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

displaying unknown doesn't look good

@Nick-1979 Nick-1979 requested a review from AMIRKHANEF October 23, 2024 08:16
@Nick-1979 Nick-1979 merged commit c987138 into main Oct 24, 2024
5 checks passed
@Nick-1979 Nick-1979 deleted the autoLoadingReferenda branch October 24, 2024 07:27
github-actions bot pushed a commit that referenced this pull request Oct 24, 2024
# [0.20.0](v0.19.6...v0.20.0) (2024-10-24)

### Features

* auto loading referenda list ([#1599](#1599)) ([c987138](c987138))
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.

add auto loading of referenda while scrolling reaches to the bottom of the page
2 participants