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

Use useNavigate instead of accessing window.__navigate #3904

Merged
merged 3 commits into from
Dec 5, 2024

Conversation

joel-jeremy
Copy link
Contributor

No description provided.

@actual-github-bot actual-github-bot bot changed the title Use useNavigate instead of accessing window.__navigate [WIP] Use useNavigate instead of accessing window.__navigate Nov 26, 2024
Copy link

netlify bot commented Nov 26, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit aba6e97
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67463e3af9622c0008ee321e
😎 Deploy Preview https://deploy-preview-3904.demo.actualbudget.org
📱 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.

@joel-jeremy joel-jeremy changed the title [WIP] Use useNavigate instead of accessing window.__navigate Use useNavigate instead of accessing window.__navigate Nov 26, 2024
Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

The pull request introduces several changes across multiple components in the desktop client application. The primary modification involves the integration of the useNavigate hook from a local hooks module to enhance navigation capabilities. In the LoggedInUser, ImportActualModal, ImportYNAB4Modal, and ImportYNAB5Modal components, direct calls to window.__navigate have been replaced with the navigate function from the hook, allowing for more structured navigation handling. The ConfigServer component has also been updated to improve the flow of actions, specifically by modifying the onCreateTestFile function to ensure navigation occurs immediately after creating a test file. Additionally, the importBudget function in the budgets.ts file has seen a change where the automatic navigation to the '/budget' route upon successful import has been removed, requiring users to navigate manually. Overall, these changes focus on refining navigation and control flow within the application while maintaining existing functionalities.

Possibly related PRs

Suggested labels

:sparkles: Merged, :white_check_mark: Approved

Suggested reviewers

  • youngcw
  • MikesGlitch

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/desktop-client/src/components/manager/ConfigServer.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-eslint-plugin".

(The package "eslint-plugin-eslint-plugin" was not found when loaded as a Node module from the directory "/packages/eslint-plugin-actual".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-eslint-plugin@latest --save-dev

The plugin "eslint-plugin-eslint-plugin" was referenced from the config file in "packages/eslint-plugin-actual/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ba96440 and aba6e97.

📒 Files selected for processing (1)
  • packages/desktop-client/src/components/manager/ConfigServer.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/desktop-client/src/components/manager/ConfigServer.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

github-actions bot commented Nov 26, 2024

Bundle Stats — desktop-client

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
10 5.45 MB → 5.45 MB (+220 B) +0.00%
Changeset
File Δ Size
src/components/modals/manager/ImportYNAB5Modal.tsx 📈 +63 B (+1.57%) 3.91 kB → 3.97 kB
src/components/modals/manager/ImportYNAB4Modal.tsx 📈 +63 B (+1.57%) 3.91 kB → 3.97 kB
src/components/modals/manager/ImportActualModal.tsx 📈 +63 B (+1.43%) 4.32 kB → 4.38 kB
src/components/manager/ConfigServer.tsx 📈 +58 B (+0.79%) 7.16 kB → 7.22 kB
src/components/LoggedInUser.tsx 📈 +7 B (+0.25%) 2.72 kB → 2.73 kB
home/runner/work/actual/actual/packages/loot-core/src/client/actions/budgets.ts 📉 -34 B (-0.61%) 5.45 kB → 5.42 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/index.js 3.44 MB → 3.44 MB (+220 B) +0.01%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/useAccountPreviewTransactions.js 1.68 kB 0%
static/js/narrow.js 82.93 kB 0%
static/js/AppliedFilters.js 21.32 kB 0%
static/js/wide.js 241.19 kB 0%
static/js/ReportRouter.js 1.52 MB 0%

Copy link
Contributor

github-actions bot commented Nov 26, 2024

Bundle Stats — loot-core

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
1 1.32 MB 0%

Changeset

No files were changed

View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

No assets were bigger

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
kcab.worker.js 1.32 MB 0%

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

🧹 Outside diff range and nitpick comments (3)
packages/desktop-client/src/components/LoggedInUser.tsx (1)

Line range hint 49-67: Consider adding error handling for async operations

While the navigation implementation is correct, consider adding try-catch blocks for the async operations to handle potential failures gracefully.

Here's a suggested improvement:

  async function onMenuSelect(type) {
    setMenuOpen(false);

    switch (type) {
      case 'change-password':
-       onChangePassword();
+       try {
+         await onChangePassword();
+       } catch (error) {
+         console.error('Failed to change password:', error);
+         // Handle error appropriately
+       }
        break;
      case 'sign-in':
-       await closeBudget();
-       navigate('/login');
+       try {
+         await closeBudget();
+         navigate('/login');
+       } catch (error) {
+         console.error('Failed to close budget:', error);
+         // Handle error appropriately
+       }
        break;
      // Similar changes for other cases
    }
  }
packages/desktop-client/src/components/modals/manager/ImportActualModal.tsx (1)

Line range hint 1-1: Consider enabling TypeScript strict mode

The file currently ignores strict TypeScript checks. Consider addressing type safety issues to remove the @ts-strict-ignore directive.

Would you like help identifying and fixing the TypeScript strict mode issues?

packages/desktop-client/src/components/modals/manager/ImportYNAB5Modal.tsx (1)

Line range hint 36-51: Consider adding success feedback before navigation

The implementation correctly replaces window.__navigate with the useNavigate hook. However, consider adding a success message or brief feedback before navigating away, as immediate navigation might be jarring for users.

 try {
   await dispatch(importBudget(res[0], 'ynab5'));
+  // Consider showing a success message
+  await new Promise(resolve => setTimeout(resolve, 1000)); // Brief delay to show feedback
   navigate('/budget');
 } catch (err) {
   setError(err.message);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c25e3d4 and ba96440.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3904.md is excluded by !**/*.md
📒 Files selected for processing (6)
  • packages/desktop-client/src/components/LoggedInUser.tsx (3 hunks)
  • packages/desktop-client/src/components/manager/ConfigServer.tsx (1 hunks)
  • packages/desktop-client/src/components/modals/manager/ImportActualModal.tsx (3 hunks)
  • packages/desktop-client/src/components/modals/manager/ImportYNAB4Modal.tsx (3 hunks)
  • packages/desktop-client/src/components/modals/manager/ImportYNAB5Modal.tsx (3 hunks)
  • packages/loot-core/src/client/actions/budgets.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/loot-core/src/client/actions/budgets.ts
🔇 Additional comments (10)
packages/desktop-client/src/components/LoggedInUser.tsx (3)

9-9: LGTM! Clean import of useNavigate hook

The import is properly organized with other hooks and follows the established pattern.


42-42: LGTM! Proper hook initialization

The useNavigate hook is correctly initialized at the component level, following React hooks rules.


44-47: LGTM! Proper navigation flow in onChangePassword

The function maintains the correct sequence: closing the budget before navigation.

Let's verify all navigation paths are consistently updated:

✅ Verification successful

Navigation implementation is consistent across the codebase

The verification shows that:

  • The /change-password route is properly defined in ManagementApp.tsx
  • All references to 'change-password' in LoggedInUser.tsx are using the new navigation approach
  • There's an ongoing migration from window.__navigate to useNavigate (as noted in release notes), and this change aligns with that migration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining window.__navigate usage
rg "window.__navigate" --type ts --type tsx

# Search for all navigation paths to /change-password to ensure consistency
rg "(/change-password|'change-password')" --type ts --type tsx -A 2

Length of output: 175


Script:

#!/bin/bash
# Search for any remaining window.__navigate usage without file type restrictions
rg "window.__navigate"

# Search for all navigation paths to /change-password
rg "(/change-password|'change-password')" -A 2

Length of output: 1666

packages/desktop-client/src/components/modals/manager/ImportYNAB4Modal.tsx (3)

8-8: LGTM: Import statement for useNavigate is correctly added

The import statement is properly placed and aligns with the PR objective to use the useNavigate hook.


27-27: LGTM: Hook initialization follows React best practices

The useNavigate hook is properly initialized at the component level, consistent with other hooks usage.


41-43: Verify navigation timing after budget import

While the navigation placement is logically correct, we should verify that the budget import is fully processed before navigation occurs. Consider adding a verification to ensure the imported budget is ready for viewing.

Consider implementing a callback or promise resolution from importBudget to confirm the budget is ready before navigation.

✅ Verification successful

Let's also check the Redux action and its implementation:


Based on the search results, I can now generate the final response:

Navigation after budget import is implemented correctly

The implementation is safe because:

  • The importBudget action is properly awaited before navigation occurs
  • The action internally handles errors and only resolves after the budget is fully imported
  • The same pattern is consistently used across all import handlers (YNAB4, YNAB5, and Actual)
  • The action closes the modal only after successful import, indicating proper completion handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar patterns in other import handlers to verify consistent behavior
rg -A 5 "importBudget.*navigate.*budget" --type typescript

Length of output: 95


Script:

#!/bin/bash
# Search for similar patterns in other import handlers to verify consistent behavior, without file type restriction
rg -A 5 "importBudget.*navigate.*budget"

# Also search for the importBudget action definition
ast-grep --pattern 'const importBudget = $_'

Length of output: 3076


Script:

#!/bin/bash
# Search for importBudget implementation
rg -A 10 "function importBudget"

# Look for dispatch calls with importBudget
rg "dispatch.*importBudget"

Length of output: 3159

packages/desktop-client/src/components/modals/manager/ImportActualModal.tsx (2)

8-8: LGTM: Proper hook implementation

The useNavigate hook is correctly imported and initialized at the component level, following React hooks best practices.

Also applies to: 35-35


49-51: Verify navigation timing after budget import

While the navigation implementation is functionally correct, let's verify that the navigation timing doesn't cause any race conditions or UI/UX issues.

Let's check how other components handle post-import navigation:

Consider adding a small delay or ensuring the import is fully processed before navigation:

 await dispatch(importBudget(res[0], 'actual'));
+await new Promise(resolve => setTimeout(resolve, 100)); // Small delay for UI feedback
 navigate('/budget');
✅ Verification successful

Navigation after budget import is correctly implemented

The implementation is safe and follows the proper pattern. The importBudget action is fully asynchronous and the navigation only occurs after:

  1. The server-side import is complete (await send('import-budget'))
  2. The modal is closed (dispatch(closeModal()))
  3. Preferences are reloaded (await dispatch(loadPrefs()))

This pattern is consistently used across all import modals (YNAB4, YNAB5, and Actual) and is verified by e2e tests that check for the budget table's visibility after import.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar patterns of navigation after importBudget
rg -A 5 "importBudget.*navigate.*budget" --type typescript

# Check if there are any existing tests covering this scenario
rg -l "importBudget.*test" --type typescript

Length of output: 177


Script:

#!/bin/bash
# Search for similar patterns of navigation after importBudget without file type restriction
rg -A 5 "importBudget.*navigate.*budget"

# Look for importBudget usage patterns
rg -A 5 "importBudget"

# Find test files related to budget import
fd ".*test.*" | rg -i "budget|import"

Length of output: 9108


Script:

#!/bin/bash
# Check the implementation of importBudget action to understand its async behavior
ast-grep --pattern 'export function importBudget($$$)'

# Look for the server-side implementation of import-budget handler
rg -A 10 "'import-budget'"

Length of output: 2805

packages/desktop-client/src/components/modals/manager/ImportYNAB5Modal.tsx (2)

8-8: LGTM: Clean import of useNavigate hook

The import statement correctly brings in the useNavigate hook from the local hooks directory, aligning with the PR's objective to standardize navigation.


30-30: LGTM: Proper hook initialization

The useNavigate hook is correctly initialized at the component's top level, following React hooks rules and conventions.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@joel-jeremy joel-jeremy merged commit 2c0bd6b into master Dec 5, 2024
20 checks passed
@joel-jeremy joel-jeremy deleted the useNavigate-instead-of-window.__navigate branch December 5, 2024 23:37
@coderabbitai coderabbitai bot mentioned this pull request Dec 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants