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: add state loading component #2117

Draft
wants to merge 1 commit into
base: next
Choose a base branch
from
Draft

Conversation

edisontim
Copy link
Collaborator

@edisontim edisontim commented Nov 15, 2024

Needs dojoengine/dojo.js#332 to be merged

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new BottomLeftContainer component for flexible content display.
    • Added BottomLeftNavigation component to provide navigation functionality.
    • Enhanced loading state management with a loading indicator in the BottomLeftNavigation component.
  • Improvements

    • Increased timeout for event synchronization to improve performance.
    • Enhanced UI state management with new properties for tracking event loading state.

These updates aim to provide a smoother user experience and better visual feedback during event loading.

Copy link

vercel bot commented Nov 15, 2024

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

Name Status Preview Comments Updated (UTC)
eternum ❌ Failed (Inspect) Nov 15, 2024 8:24pm
eternum-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 15, 2024 8:24pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
eternum-landing ⬜️ Ignored (Inspect) Visit Preview Nov 15, 2024 8:24pm

Copy link
Contributor

mentatbot bot commented Nov 15, 2024

You are out of MentatBot reviews. Your usage will refresh November 18 at 08:00 AM.

Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Walkthrough

The pull request introduces modifications to the setup function in client/src/dojo/setup.ts, enhancing loading state management during synchronization processes. It adds new properties and methods to the UIStore interface in client/src/hooks/store/useUIStore.tsx to track event loading states. Additionally, it introduces a new BottomLeftContainer component in client/src/ui/containers/BottomLeftContainer.tsx and updates the World.tsx layout to include lazy-loaded components. A new BottomLeftNavigation component is also added to provide visual feedback during loading states.

Changes

File Path Change Summary
client/src/dojo/setup.ts - Modified setup function to include useUIStore for managing loading states and updated timeout values for sync functions.
client/src/hooks/store/useUIStore.tsx - Added properties: eventsLoadingState (boolean) and setEventsLoadingState (function) to UIStore interface.
client/src/ui/containers/BottomLeftContainer.tsx - Introduced new component BottomLeftContainer that accepts children prop and renders a positioned div.
client/src/ui/layouts/World.tsx - Added lazy-loaded components: BottomLeftContainer and BottomLeftNavigation, updating the layout structure.
client/src/ui/modules/navigation/BottomLeftNavigation.tsx - Created new component BottomLeftNavigation that renders a loading indicator based on eventsLoadingState.

Possibly related PRs

Suggested reviewers

  • ponderingdemocritus
  • aymericdelab

Poem

In the land of code where rabbits play,
New components hop in, brightening the day.
With loading states managed, events in sync,
Our UI now dances, don’t you think?
So let’s celebrate this change with cheer,
For a smoother experience is finally here! 🐇✨

Warning

Rate limit exceeded

@edisontim has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 31 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between ebf6aae and cbda657.


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

Failed to generate code suggestions for PR

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

🧹 Outside diff range and nitpick comments (4)
client/src/ui/containers/BottomLeftContainer.tsx (2)

1-3: Consider enhancing component structure and type safety.

The component implementation could be improved for better maintainability and type safety.

Consider applying these improvements:

+interface BottomLeftContainerProps {
+  children: React.ReactNode;
+}
+
-const BottomLeftContainer = ({ children }: { children: React.ReactNode }) => {
+const BottomLeftContainer: React.FC<BottomLeftContainerProps> = ({ children }) => {
-  return <div className="absolute bottom-0 left-0">{children}</div>;
+  return (
+    <aside 
+      className="absolute bottom-0 left-0"
+      role="complementary"
+    >
+      {children}
+    </aside>
+  );
};

This refactor:

  • Extracts props interface for better type documentation
  • Uses semantic aside element instead of div
  • Adds ARIA role for better accessibility

1-5: Consider adding CSS isolation.

The component uses global CSS classes which could lead to styling conflicts.

Consider using CSS modules or styled-components for better CSS isolation:

// BottomLeftContainer.module.css
.container {
  position: absolute;
  bottom: 0;
  left: 0;
}

// BottomLeftContainer.tsx
import styles from './BottomLeftContainer.module.css';

// ... then use styles.container instead of direct classes
client/src/ui/modules/navigation/BottomLeftNavigation.tsx (1)

3-4: Add TypeScript types for better type safety

Consider adding TypeScript types to improve code maintainability and catch potential issues early:

-export const BottomLeftNavigation = () => {
+export const BottomLeftNavigation: React.FC = () => {
+  const eventsLoadingState = useUIStore((state: { eventsLoadingState: boolean }) => state.eventsLoadingState);
client/src/dojo/setup.ts (1)

1-1: Consider a more robust state management approach

While using useUIStore.getState() works, it creates tight coupling between the setup logic and UI state. Consider:

  1. Passing the state setter as a configuration parameter to make the setup function more flexible and testable
  2. Adding error handling in case the store isn't initialized
-export async function setup({ ...config }: DojoConfig) {
+export async function setup({ 
+  ...config,
+  onEventsLoadingStateChange?: (loading: boolean) => void 
+}: DojoConfig & { 
+  onEventsLoadingStateChange?: (loading: boolean) => void 
+}) {
   const network = await setupNetwork(config);
   const components = createClientComponents(network);
   const systemCalls = createSystemCalls(network);

-  const setLoadingState = useUIStore.getState().setEventsLoadingState;
+  const setLoadingState = onEventsLoadingStateChange ?? useUIStore.getState()?.setEventsLoadingState;

Also applies to: 18-19

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ebf6aae and cbda657.

📒 Files selected for processing (5)
  • client/src/dojo/setup.ts (2 hunks)
  • client/src/hooks/store/useUIStore.tsx (2 hunks)
  • client/src/ui/containers/BottomLeftContainer.tsx (1 hunks)
  • client/src/ui/layouts/World.tsx (2 hunks)
  • client/src/ui/modules/navigation/BottomLeftNavigation.tsx (1 hunks)
🔇 Additional comments (8)
client/src/ui/containers/BottomLeftContainer.tsx (1)

2-2: Verify parent container positioning.

The use of absolute positioning requires the parent container to have relative positioning to work as expected.

Let's verify the parent container's positioning:

✅ Verification successful

Let me gather more information about the parent component's structure.


Let me check the complete structure of World.tsx to see how the container is rendered and its styling.


The absolute positioning is correctly implemented

The parent container #world has fixed positioning and spans the full viewport with w-screen h-screen, which creates a proper positioning context for the absolutely positioned BottomLeftContainer. The absolute positioning will work as expected in this setup.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the parent component (World.tsx) has proper positioning
# Expected: Should find relative/absolute/fixed positioning in the parent component

rg -A 5 "BottomLeftContainer" | rg -B 5 "relative|absolute|fixed"

Length of output: 529


Script:

#!/bin/bash
# Check the World.tsx component's structure and styling
rg -A 10 "function World|const World" client/src/ui/layouts/World.tsx

Length of output: 496


Script:

#!/bin/bash
# Get the full content of World.tsx to check the container's wrapper/parent
cat client/src/ui/layouts/World.tsx

Length of output: 6871

client/src/ui/modules/navigation/BottomLeftNavigation.tsx (2)

1-1: LGTM!

Clean import statement using absolute path.


1-12: Verify component integration points

Let's verify the integration with the container and store setup.

✅ Verification successful

Component integration is properly implemented

The verification confirms:

  • Component is correctly imported and used in World.tsx using lazy loading
  • Properly wrapped in BottomLeftContainer in World.tsx
  • UIStore interface includes eventsLoadingState with correct initialization
  • Store usage in component matches the interface definition
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify component integration and store usage

# Check BottomLeftContainer implementation
echo "Checking BottomLeftContainer implementation:"
rg -l "BottomLeftContainer" --type tsx

# Verify store implementation
echo "\nVerifying store implementation:"
ast-grep --pattern 'interface UIStore {
  $$$
  eventsLoadingState: boolean
  $$$
}'

# Check usage in World.tsx
echo "\nChecking World.tsx integration:"
rg -A 5 "BottomLeftNavigation" --type tsx

Length of output: 4364


Script:

#!/bin/bash
# Let's try with correct file extensions and additional context

# Check BottomLeftContainer and Navigation usage
echo "Checking component usage:"
rg -l "BottomLeftNavigation" .

# Check World.tsx content specifically
echo "\nChecking World.tsx content:"
rg -A 10 "BottomLeftNavigation" .

# Check if BottomLeftContainer exists
echo "\nChecking BottomLeftContainer existence:"
rg -l "BottomLeftContainer" .

# Verify store initialization
echo "\nChecking store initialization and eventsLoadingState usage:"
rg "eventsLoadingState" .

Length of output: 4010

client/src/dojo/setup.ts (1)

21-21: Document and verify the timeout increase

The sync timeout has been doubled from 10,000 to 20,000ms. While this might solve timeout issues, it could mask underlying performance problems.

✅ Verification successful

Let me analyze the search results to verify the timeout concern:

  1. The search shows several timeouts in the codebase:
  • A 20,000ms timeout in config/index.ts
  • Multiple UI-related timeouts in various components for animations and state updates
  • No error logs or comments indicating timeout issues
  1. Let's search specifically for the sync-related code and any potential timeout issues:

Based on the search results, I can now generate a final response since I have sufficient context about the sync timeout change:

Timeout increase appears justified for entity synchronization

The timeout increase from 10,000 to 20,000ms is used specifically for getSyncEntities from @dojoengine/state, which is a core initialization function. This matches a similar 20,000ms timeout in config/index.ts, suggesting a standardized timeout value for network operations. There are no error logs or comments indicating performance issues, implying this is a proactive adjustment for reliability rather than a reaction to problems.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for timeout-related issues in the codebase
# Look for patterns that might indicate performance problems

# Search for timeout-related comments or issues
rg -i "timeout|timed?.?out" --type ts

# Look for similar timeout configurations
rg "(?:\d{4,5}_000|[12]\d{4})" --type ts

# Search for performance-related comments
rg -i "(?:slow|performance|latency)" --type ts

Length of output: 21426


Script:

#!/bin/bash
# Search for sync-related code and timeout patterns
rg -A 5 "getSyncEntities" --type ts

# Look for any error handling or comments around sync timeouts
rg -i "sync.*timeout|timeout.*sync" --type ts

# Search for any sync-related issues or performance comments
rg -B 2 -A 2 "sync.*error|error.*sync" --type ts

Length of output: 1387

client/src/hooks/store/useUIStore.tsx (2)

61-62: LGTM! Interface additions follow consistent patterns

The new properties for events loading state management are well-structured and follow the existing patterns in the store interface.


122-123: Verify integration with sync events handling

The implementation looks good, but let's verify the integration points mentioned in the summary:

  1. Usage in setup.ts for sync events completion
  2. Usage in BottomLeftNavigation for loading indicator
✅ Verification successful

Integration points for eventsLoadingState are correctly implemented

The verification confirms that:

  • setup.ts correctly accesses the setter via getState() for updating loading state during sync
  • BottomLeftNavigation properly subscribes to the state for displaying loading indicator
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration of eventsLoadingState

# Check setup.ts usage
echo "Checking setup.ts integration..."
rg "setEventsLoadingState" "client/src/dojo/setup.ts"

# Check BottomLeftNavigation usage
echo "Checking BottomLeftNavigation integration..."
rg "eventsLoadingState" "client/src/ui/modules/navigation/BottomLeftNavigation.tsx"

Length of output: 488

client/src/ui/layouts/World.tsx (2)

46-49: LGTM: Component declarations follow established patterns

The lazy loading implementation for both components follows the codebase's established patterns and best practices for code splitting.


154-157: Verify loading state integration

The AI summary mentions that BottomLeftNavigation uses eventsLoadingState from useUIStore. Let's verify this integration:

#!/bin/bash
# Description: Verify the loading state integration

# Check if BottomLeftNavigation properly uses eventsLoadingState
echo "Checking BottomLeftNavigation for eventsLoadingState usage..."
ast-grep --pattern 'const $state = useUIStore((state) => state.eventsLoadingState)' $(fd -t f "BottomLeftNavigation.tsx$")

# Verify if eventsLoadingState is properly defined in UIStore
echo "Checking UIStore for eventsLoadingState definition..."
rg "eventsLoadingState" $(fd -t f "useUIStore.tsx$")

Comment on lines +6 to +11
return eventsLoadingState ? (
<div className="flex flex-row mb-4 ml-4 items-center bg-hex bg-black/50 rounded-lg p-2">
<img src="/images/eternum-logo_animated.png" className="invert w-10 h-10" />
<div className="text-xs text-white/90 ml-2 animate-pulse">Game state is loading...</div>
</div>
) : null;
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

Improve accessibility and performance

Several improvements can be made to enhance the component:

  1. Add alt text to the image for screen readers
  2. Consider reducing animation impact on performance
  3. Externalize text for internationalization
  4. Ensure sufficient contrast ratio for text visibility
 return eventsLoadingState ? (
   <div className="flex flex-row mb-4 ml-4 items-center bg-hex bg-black/50 rounded-lg p-2">
-    <img src="/images/eternum-logo_animated.png" className="invert w-10 h-10" />
-    <div className="text-xs text-white/90 ml-2 animate-pulse">Game state is loading...</div>
+    <img 
+      src="/images/eternum-logo_animated.png" 
+      alt="Loading indicator" 
+      className="invert w-10 h-10" 
+      loading="lazy"
+    />
+    <div className="text-xs text-white ml-2 animate-pulse" role="status">
+      {t('loading.gameState')}
+    </div>
   </div>
 ) : null;

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +22 to +30
const eventSync = getSyncEvents(
network.toriiClient,
network.contractComponents.events as any,
undefined,
[],
20_000,
false,
() => setLoadingState(false),
);
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 event sync error handling and loading state management

Several concerns with the current implementation:

  1. Loading state is only set to false but never explicitly set to true
  2. Missing error handling could leave the UI stuck in a loading state
  3. The purpose of the false parameter is unclear and should be documented

Consider implementing this more robust approach:

+  // Set initial loading state
+  setLoadingState(true);
+
   const eventSync = getSyncEvents(
     network.toriiClient,
     network.contractComponents.events as any,
     undefined,
     [],
     20_000,
     false, // Add comment explaining this parameter
-    () => setLoadingState(false),
+    () => setLoadingState(false)
+  ).catch(error => {
+    console.error('Event sync failed:', error);
+    setLoadingState(false);
+    throw error;
   });
📝 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 eventSync = getSyncEvents(
network.toriiClient,
network.contractComponents.events as any,
undefined,
[],
20_000,
false,
() => setLoadingState(false),
);
// Set initial loading state
setLoadingState(true);
const eventSync = getSyncEvents(
network.toriiClient,
network.contractComponents.events as any,
undefined,
[],
20_000,
false, // Add comment explaining this parameter
() => setLoadingState(false)
).catch(error => {
console.error('Event sync failed:', error);
setLoadingState(false);
throw error;
});

Comment on lines +154 to +157

<BottomLeftContainer>
<BottomLeftNavigation />
</BottomLeftContainer>
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Mobile handling is appropriate, but layout needs adjustment

The BottomLeftNavigation component already has appropriate mobile handling through its conditional rendering based on eventsLoadingState. However, there are two layout considerations:

  1. The absolute positioning (absolute bottom-0 left-0) in BottomLeftContainer could conflict with other UI elements since it's placed at the exact corner.
  2. The component includes proper mobile-friendly padding (mb-4 ml-4) and styling, but the background might need z-index handling to prevent overlaps.

Recommendations:

  • Add a z-index to the BottomLeftContainer to ensure proper layering
  • Consider adding some base padding/margin to the container to prevent edge-touching on mobile devices
🔗 Analysis chain

Verify mobile device handling and layout positioning

The new bottom-left components are added without mobile-specific handling, unlike other containers in the layout (e.g., BottomRightContainer). Please verify:

  1. If these components should be hidden on mobile devices
  2. If the positioning conflicts with other mobile UI elements

Let's check for any mobile-specific handling in the new components:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for mobile-specific handling in the new components

# Check BottomLeftContainer for mobile handling
echo "Checking BottomLeftContainer for mobile handling..."
rg -A 5 "IS_MOBILE" $(fd -t f "BottomLeftContainer.tsx$")

# Check BottomLeftNavigation for mobile handling
echo "Checking BottomLeftNavigation for mobile handling..."
rg -A 5 "IS_MOBILE" $(fd -t f "BottomLeftNavigation.tsx$")

# Check for potential layout conflicts
echo "Checking for other components with 'bottom-left' positioning..."
rg -i "bottom.?left" $(fd -t f -e tsx -e css)

Length of output: 766


Script:

#!/bin/bash
# Let's check for mobile-specific styling and layout handling

# Check BottomLeftContainer styling and mobile handling
echo "Checking BottomLeftContainer styling..."
fd -t f "BottomLeftContainer" -x cat {}

# Check BottomLeftNavigation styling and mobile handling
echo "Checking BottomLeftNavigation styling..."
fd -t f "BottomLeftNavigation.tsx$" -x cat {}

# Check for any mobile-specific utilities or constants
echo "Checking for mobile utilities usage..."
rg "IS_MOBILE|isMobile|mobile" client/src/ui/layouts/World.tsx

# Check for any z-index or positioning conflicts
echo "Checking for positioning styles..."
rg "position:|z-index:|bottom:|left:" client/src/ui/layouts/World.tsx

Length of output: 1454

@edisontim edisontim marked this pull request as draft November 16, 2024 22:16
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.

1 participant