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

chalabi/modal fixes #87

Merged
merged 2 commits into from
Nov 27, 2024
Merged

chalabi/modal fixes #87

merged 2 commits into from
Nov 27, 2024

Conversation

chalabi2
Copy link
Collaborator

@chalabi2 chalabi2 commented Nov 26, 2024

partially fixes #28 (pending token factory modal logic rework)
fixes #64
fixes #31

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced readability of large transaction amounts with a new formatting function.
    • Streamlined modal handling for transaction and denomination information.
  • Bug Fixes

    • Improved error handling in modals with optional chaining for safer property access.
  • User Interface Improvements

    • Adjusted maximum height for member list display in the Member Management Modal.
  • Refactor

    • Simplified modal props and internal logic across multiple components for better maintainability.

Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

The pull request introduces several changes across multiple components, primarily focusing on the management of modal dialogs and the formatting of transaction amounts. A new function, formatLargeNumber, is added to enhance the readability of large numbers. The handling of modals has been streamlined by removing redundant functions and integrating modal logic directly into event handlers. Additionally, several components have been updated to utilize optional chaining for safer property access, improving error handling.

Changes

File Path Change Summary
components/bank/components/historyBox.tsx Added formatLargeNumber function; removed openModal and closeModal; updated TxInfoModal invocation.
components/bank/components/tokenList.tsx Removed openModal; integrated modal logic into onClick handlers; updated selectedDenom type.
components/bank/modals/txInfo.tsx Removed isOpen and onClose props from TxInfoModal; added modalId prop; updated rendering logic for safety.
components/factory/modals/denomInfo.tsx Removed isOpen and onClose props; simplified modal structure; added optional chaining for safety.
components/groups/modals/memberManagementModal.tsx Adjusted max height of member list; refined member deletion logic; maintained core functionality of handleConfirm.

Assessment against linked issues

Objective Addressed Explanation
All modals should be closable by pressing the Esc key. (#28) No explicit changes related to Esc key handling are evident.
Improve real estate usage when adding a new Group member (#64) The max height adjustment may improve usability.
Link in the transaction detail should point to the block explorer (#31) No changes related to transaction detail links were made.

Possibly related PRs

  • fix: denom info modal #37: The changes in the DenomInfoModal component involve removing the isOpen and onClose props, similar to the removal of the openModal function in the main PR, indicating a related approach to modal management.
  • fix: admin page layout & refactor #38: The ValidatorList component also removed the openModal function, aligning with the main PR's changes to modal handling, suggesting a common pattern in managing modal states.
  • fix: group & proposal theme and layout #41: The updates to the VoteDetailsModal component, particularly the changes in props and rendering logic, reflect a similar restructuring approach to modal management as seen in the main PR.
  • fix: admin theme #42: The changes in the admin theme, including updates to modal handling, suggest a broader effort to streamline modal interactions across different components, relating to the main PR's focus on modal logic.
  • fix: mint/burn form data display #78: The modifications in the MintForm and MintModal components, particularly the removal of the admin prop and simplification of the interface, suggest a parallel effort to streamline component interactions, similar to the changes in the main PR.

Suggested labels

render

Suggested reviewers

  • fmorency

🐰 In the meadow, where numbers play,
A function was born to brighten the day.
Modals now dance with a click and a cheer,
Formatting large sums, oh so clear!
With changes so bright, let’s hop and rejoice,
For clarity reigns, let’s all raise our voice! 🌼


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

codecov bot commented Nov 26, 2024

Codecov Report

Attention: Patch coverage is 76.66667% with 14 lines in your changes missing coverage. Please review.

Project coverage is 59.41%. Comparing base (263a5e1) to head (9365365).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
components/bank/components/historyBox.tsx 65.38% 9 Missing ⚠️
components/bank/components/tokenList.tsx 71.42% 4 Missing ⚠️
components/bank/modals/txInfo.tsx 91.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #87      +/-   ##
==========================================
+ Coverage   58.85%   59.41%   +0.56%     
==========================================
  Files         145      145              
  Lines       14040    14040              
==========================================
+ Hits         8263     8342      +79     
+ Misses       5777     5698      -79     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

🧹 Outside diff range and nitpick comments (9)
components/factory/modals/denomInfo.tsx (4)

16-18: Consider accessibility improvements

While the modal has basic ARIA attributes, consider adding:

  • role="dialog" for better screen reader support
  • Focus trap for keyboard navigation
  • Auto-focus on the close button

Line range hint 48-56: Improve error handling for BASE value decoding

The current implementation silently falls back to the encoded value on error. Consider:

  1. Adding user-friendly error messaging
  2. Logging the specific decoding error details
 try {
   return decodeURIComponent(denom?.base);
 } catch (e) {
-  console.error('Failed to decode BASE value:', e);
-  return denom.base;
+  const error = e instanceof Error ? e.message : 'Unknown error';
+  console.error('Failed to decode BASE value:', error);
+  return `Unable to decode: ${denom.base}`;
 }

63-66: Consider consolidating modal close handlers

The component has two form elements with method="dialog". Consider consolidating these into a single close handler for better maintainability.

- <form method="dialog" className="modal-backdrop">
-   <button>close</button>
- </form>
+ <div className="modal-backdrop" onClick={() => {
+   document.getElementById(modalId)?.close();
+ }}>
+ </div>

Line range hint 89-93: Update block explorer URL handling

Per Issue #31, the transaction links should point to the appropriate block explorer based on the selected endpoint. Currently, it's hardcoded to use NEXT_PUBLIC_TESTNET_EXPLORER_URL.

Consider:

  1. Accepting the explorer URL as a prop
  2. Using a context provider for network configuration
  3. Implementing a service to manage network-specific URLs
components/bank/components/tokenList.tsx (1)

111-116: Consider memoizing the selected denomination metadata

The find operation on filteredBalances is performed on every render. For better performance, consider memoizing this value.

+ const selectedDenomMetadata = useMemo(
+   () => filteredBalances.find(b => b.denom === selectedDenom)?.metadata ?? null,
+   [filteredBalances, selectedDenom]
+ );

  {selectedDenom && (
    <DenomInfoModal
-     denom={filteredBalances.find(b => b.denom === selectedDenom)?.metadata ?? null}
+     denom={selectedDenomMetadata}
      modalId="denom-info-modal"
    />
  )}
components/bank/components/historyBox.tsx (1)

Line range hint 1-276: Consider implementing a reusable modal management system

To better address the modal-related issues (#28) and improve maintainability, consider:

  1. Creating a custom hook for modal management
  2. Implementing a consistent pattern for handling modals across the application
  3. Adding proper keyboard event handling (Esc key)

Example implementation:

// hooks/useModal.ts
export function useModal(modalId: string) {
  const showModal = useCallback(() => {
    const modal = document.getElementById(modalId);
    if (modal instanceof HTMLDialogElement) {
      modal.showModal();
      const handleEsc = (e: KeyboardEvent) => {
        if (e.key === 'Escape') {
          modal.close();
          document.removeEventListener('keydown', handleEsc);
        }
      };
      document.addEventListener('keydown', handleEsc);
    }
  }, [modalId]);

  const hideModal = useCallback(() => {
    const modal = document.getElementById(modalId);
    if (modal instanceof HTMLDialogElement) {
      modal.close();
    }
  }, [modalId]);

  return { showModal, hideModal };
}
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 33-33: components/bank/components/historyBox.tsx#L33
Added line #L33 was not covered by tests


[warning] 35-35: components/bank/components/historyBox.tsx#L35
Added line #L35 was not covered by tests


[warning] 37-37: components/bank/components/historyBox.tsx#L37
Added line #L37 was not covered by tests


[warning] 39-39: components/bank/components/historyBox.tsx#L39
Added line #L39 was not covered by tests


[warning] 41-41: components/bank/components/historyBox.tsx#L41
Added line #L41 was not covered by tests

components/groups/modals/memberManagementModal.tsx (2)

Line range hint 41-43: Consider making member weight configurable

The weight for new members is hardcoded to '1'. Consider making this configurable to provide more flexibility in member management.

 const [members, setMembers] = useState<ExtendedMember[]>(() =>
   initialMembers.map(member => ({
     ...member,
     isNew: false,
     markedForDeletion: false,
-    weight: member.weight || '1',
+    weight: member.weight || defaultWeight,
   }))
 );

Also applies to: 52-60


Line range hint 301-309: Add user feedback for copy action

The copy button should provide visual feedback when the address is copied.

 <button
   onClick={e => {
     e.preventDefault();
-    navigator.clipboard.writeText(member.address);
+    navigator.clipboard.writeText(member.address)
+      .then(() => {
+        // Show toast or tooltip feedback
+        toast.success('Address copied to clipboard');
+      });
   }}
   className="btn btn-ghost hover:bg-transparent btn-sm ml-2"
 >
components/bank/modals/txInfo.tsx (1)

54-54: Increase test coverage for the transaction amount display

The rendering of transaction amounts starting at line 54 is not covered by tests. To ensure reliability and prevent future regressions, consider adding unit tests for this functionality.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 54-54: components/bank/modals/txInfo.tsx#L54
Added line #L54 was not covered by tests

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 263a5e1 and 9365365.

📒 Files selected for processing (5)
  • components/bank/components/historyBox.tsx (4 hunks)
  • components/bank/components/tokenList.tsx (3 hunks)
  • components/bank/modals/txInfo.tsx (5 hunks)
  • components/factory/modals/denomInfo.tsx (4 hunks)
  • components/groups/modals/memberManagementModal.tsx (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
components/bank/components/historyBox.tsx

[warning] 33-33: components/bank/components/historyBox.tsx#L33
Added line #L33 was not covered by tests


[warning] 35-35: components/bank/components/historyBox.tsx#L35
Added line #L35 was not covered by tests


[warning] 37-37: components/bank/components/historyBox.tsx#L37
Added line #L37 was not covered by tests


[warning] 39-39: components/bank/components/historyBox.tsx#L39
Added line #L39 was not covered by tests


[warning] 41-41: components/bank/components/historyBox.tsx#L41
Added line #L41 was not covered by tests


[warning] 200-203: components/bank/components/historyBox.tsx#L200-L203
Added lines #L200 - L203 were not covered by tests

components/bank/components/tokenList.tsx

[warning] 58-61: components/bank/components/tokenList.tsx#L58-L61
Added lines #L58 - L61 were not covered by tests

components/bank/modals/txInfo.tsx

[warning] 54-54: components/bank/modals/txInfo.tsx#L54
Added line #L54 was not covered by tests

🔇 Additional comments (9)
components/factory/modals/denomInfo.tsx (2)

11-14: LGTM: Improved null safety with optional chaining

The addition of optional chaining in denom?.name?.startsWith() provides better null safety compared to the previous implementation.


9-9: Verify Esc key functionality for modal closure

The PR aims to make modals closable with Esc key (Issue #28), but the native dialog element might need additional configuration to ensure this behavior works consistently across browsers.

Consider implementing a shared modal wrapper component that handles Esc key functionality consistently across all modals.

✅ Verification successful

Native dialog element handles Esc key automatically

The native HTML <dialog> element used in the modal implementation automatically handles the Esc key for closing modals without requiring additional JavaScript event handlers. This is a built-in accessibility feature of the <dialog> element across modern browsers.

  • The modal uses <dialog> element with proper method="dialog" forms for both content and backdrop
  • The backdrop form ensures clicking outside the modal also closes it
  • No additional keyboard event handlers are needed as Esc key handling is provided natively
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any ESC key handling implementations
rg -i "escape|esc" --type ts --type tsx

Length of output: 69


Script:

#!/bin/bash
# Search for any ESC key handling implementations with correct file type
rg -i "escape|esc" --type typescript

# Also check for dialog element usage and event handlers
rg -i "dialog.*onclose|onclose.*dialog" --type typescript

# Look for modal-related components and their implementations
fd -e ts -e tsx | xargs rg -l "modal"

Length of output: 2472


Script:

#!/bin/bash
# Let's check the dialog element implementation in the codebase
rg -l "<dialog" .

# Check for any keyboard event handlers in modal components
rg -i "keydown|keyup|keypress" components/factory/modals/

# Look for any shared modal components or hooks
fd -e ts -e tsx | grep -i "modal" | xargs cat

Length of output: 132036


Script:

#!/bin/bash
# Search for dialog element and its keyboard event handlers
rg -A 5 -B 5 "<dialog.*onKeyDown|onKeyPress|onKeyUp" .

# Look for any keyboard event handlers in the codebase
rg -i "keydown.*esc|escape.*keydown" .

# Check for any shared modal components or hooks that might handle keyboard events
fd -e ts -e tsx | grep -i "modal" | xargs rg -l "keydown|keyup|keypress"

Length of output: 2097

components/bank/components/tokenList.tsx (1)

58-63: 🛠️ Refactor suggestion

Consider refactoring modal management for better maintainability and testability

The current implementation has several concerns:

  1. Direct DOM manipulation via document.getElementById is not idiomatic React
  2. Modal opening logic is duplicated (here and in button click handler)
  3. Missing test coverage for this critical UI interaction
  4. No explicit handling of Esc key (from PR objectives)

Consider refactoring to use React state for modal management:

-  onClick={() => {
-    setSelectedDenom(balance?.denom);
-    (
-      document?.getElementById(`denom-info-modal`) as HTMLDialogElement
-    )?.showModal();
-  }}
+  const [isModalOpen, setIsModalOpen] = useState(false);
+  
+  const handleModalOpen = (denom: string) => {
+    setSelectedDenom(denom);
+    setIsModalOpen(true);
+  };
+
+  onClick={() => handleModalOpen(balance.denom)}

Let's verify the modal implementation across the codebase:

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 58-61: components/bank/components/tokenList.tsx#L58-L61
Added lines #L58 - L61 were not covered by tests

components/bank/components/historyBox.tsx (1)

259-261: LGTM: Transaction amount formatting looks good

The implementation correctly:

  • Handles decimal places using metadata
  • Formats large numbers for better readability
  • Maintains proper denomination display
components/groups/modals/memberManagementModal.tsx (1)

226-226: Consider improving modal interaction pattern

While the HTML5 <dialog> element provides native Esc key support (addressing Issue #28), the interaction between the main modal and contacts modal needs attention. Currently, the main modal is closed when opening contacts, which could lead to state inconsistency if the user presses Esc.

Let's verify the modal interaction pattern:

Consider these alternatives:

  1. Stack the modals using z-index management instead of closing the main modal
  2. Use a modal manager to handle modal state transitions

Also applies to: 391-394

components/bank/modals/txInfo.tsx (4)

9-13: Update modal control flow using modalId

Replacing isOpen and onClose with modalId in the TxInfoModal component streamlines modal management. This change should enhance consistency across the application’s modals.


27-33: Ensure modal opens and closes correctly with the new structure

With the shift to using the <dialog> element and removing the onClick handler from the close button, please verify that the modal opens and closes as expected, including when using the Esc key and the close button.


42-47: Good use of optional chaining to enhance error handling

Adding optional chaining (?.) when accessing properties of tx and tx.data improves robustness by preventing runtime errors if these objects are undefined.


91-91: Verify correctness of URL construction in external links

Please confirm that the href attribute constructs the correct URL for both transactions and accounts. Double-check the conditional logic to ensure it accurately reflects the intended paths for different labels.

components/bank/components/tokenList.tsx Show resolved Hide resolved
components/bank/components/historyBox.tsx Show resolved Hide resolved
components/bank/components/historyBox.tsx Show resolved Hide resolved
components/bank/components/historyBox.tsx Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants