Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix loading of number format on initial app startup #4038

Merged
merged 2 commits into from
Dec 27, 2024

Conversation

jfdoming
Copy link
Contributor

@jfdoming jfdoming commented Dec 25, 2024

Fixes #4037. The bug occurs because the React component renders without using useFormat at all. An easy fix would be to just call that hook inside the component, but then we risk this bug cropping up on other pages. Instead I changed the logic at preference load time so it's valid for all components

Requesting Matiss since this relates to #3397 but feel free to request someone else instead

Copy link

netlify bot commented Dec 25, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit d35f61c
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/676c3a3f604ca50008bd2e18
😎 Deploy Preview https://deploy-preview-4038.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.

Copy link
Contributor

github-actions bot commented Dec 25, 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.64 MB → 5.64 MB (+321 B) +0.01%
Changeset
File Δ Size
home/runner/work/actual/actual/packages/loot-core/src/client/actions/prefs.ts 📈 +200 B (+14.00%) 1.4 kB → 1.59 kB
home/runner/work/actual/actual/packages/loot-core/src/shared/util.ts 📈 +182 B (+2.76%) 6.43 kB → 6.61 kB
src/components/spreadsheet/useFormat.ts 📉 -61 B (-3.65%) 1.63 kB → 1.57 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.71 MB → 3.71 MB (+321 B) +0.01%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/useAccountPreviewTransactions.js 1.63 kB 0%
static/js/AppliedFilters.js 10.24 kB 0%
static/js/narrow.js 83.36 kB 0%
static/js/wide.js 104.11 kB 0%
static/js/ReportRouter.js 1.58 MB 0%

Copy link
Contributor

github-actions bot commented Dec 25, 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
File Δ Size
packages/loot-core/src/shared/util.ts 📈 +194 B (+1.80%) 10.54 kB → 10.73 kB
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%

@jfdoming jfdoming force-pushed the jfdoming/fix-number-format-loading branch from 13950ca to d35f61c Compare December 25, 2024 17:00
@jfdoming jfdoming changed the title Fix loading of number format on initial app load Fix loading of number format on initial app startup Dec 25, 2024
@jfdoming jfdoming marked this pull request as ready for review December 25, 2024 17:07
Copy link
Contributor

coderabbitai bot commented Dec 25, 2024

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/spreadsheet/useFormat.ts

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.

Walkthrough

The pull request introduces modifications to number formatting across multiple files. In packages/desktop-client/src/components/spreadsheet/useFormat.ts, the import and usage of number format functions are updated. In packages/loot-core/src/shared/util.ts, a new parseNumberFormat function is added, which validates and processes number format configurations. The isNumberFormat function is changed from an exported to a private function. These changes aim to improve the handling of number formats, particularly focusing on the "hide decimal places" functionality. The modifications streamline the number formatting process and provide more robust configuration options.

Assessment against linked issues

Objective Addressed Explanation
Fix PWA quick action number input when "hide decimal places" is enabled [#4037]
Ensure correct number formatting with decimal place hiding

Possibly related PRs

Suggested labels

sparkles: Merged

Suggested reviewers

  • youngcw
  • carkom

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 0

🧹 Nitpick comments (2)
packages/desktop-client/src/components/spreadsheet/useFormat.ts (1)

6-6: **Use descriptive imports to maintain clarity **

The introduction of parseNumberFormat is sound. However, consider grouping or commenting imports to keep context clear for future contributors. For example, grouping “number format” related imports under a dedicated comment section can reduce confusion as the file grows.

packages/loot-core/src/client/actions/prefs.ts (1)

35-42: **Prevent global side effects **

Storing number formatting in a global state (setNumberFormat) can result in side effects outside the React tree. If possible, prefer a reactive context or a shared store to reduce hidden dependencies. This is functional, but can be improved by gradually removing reliance on the global variable in setNumberFormat().

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9213ed7 and d35f61c.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4038.md is excluded by !**/*.md
📒 Files selected for processing (3)
  • packages/desktop-client/src/components/spreadsheet/useFormat.ts (2 hunks)
  • packages/loot-core/src/client/actions/prefs.ts (2 hunks)
  • packages/loot-core/src/shared/util.ts (2 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/loot-core/src/client/actions/prefs.ts (2)
Learnt from: MatissJanis
PR: actualbudget/actual#3544
File: packages/loot-core/src/client/state-types/prefs.d.ts:13-18
Timestamp: 2024-11-10T16:45:31.225Z
Learning: When action types like `SetPrefsAction` are updated with new properties, ensure that reducers are correctly handling these properties before suggesting a potential issue.
Learnt from: MatissJanis
PR: actualbudget/actual#3458
File: packages/loot-core/src/client/state-types/prefs.d.ts:5-5
Timestamp: 2024-11-10T16:45:25.627Z
Learning: In future reviews, ensure that changes related to `PrefsState` in `prefs.d.ts` do not incorrectly assume necessary updates in other parts of the codebase. Verify the impact thoroughly before making suggestions.
🔇 Additional comments (6)
packages/desktop-client/src/components/spreadsheet/useFormat.ts (1)

67-67: **Validate fallback handling of ‘hideFraction’ and ‘numberFormat’ **

While calling parseNumberFormat({ format: numberFormat, hideFraction }), ensure that the defaults for numberFormat and hideFraction behave as intended if the user or environment does not supply values. The logic itself appears consistent, but testing with null/undefined values might help confirm this is robust to edge cases.

✅ Verification successful

Let me check the implementation of parseNumberFormat to understand how it handles defaults.


Let me check the isNumberFormat function to complete the verification.


Let me try a different pattern to find the isNumberFormat implementation.


Let me check what the NUMBER_FORMATS constant contains.


Fallback handling for 'hideFraction' and 'numberFormat' is properly implemented

The implementation has robust fallback handling:

  • numberFormat: If the format is undefined or invalid, it defaults to 'comma-dot' (which is a valid format in NUMBER_FORMATS)
  • hideFraction: Converts input to string and checks against 'true', effectively handling undefined/null by defaulting to false

The implementation in parseNumberFormat is safe and handles all edge cases appropriately.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Looking for references to parseNumberFormat usage.
# We want to see if there's any other usage that needs consistent defaults.
rg -A 5 "parseNumberFormat"

Length of output: 2390


Script:

#!/bin/bash
# Let's look at the implementation of parseNumberFormat in util.ts
ast-grep --pattern 'export function parseNumberFormat($_) {
  $$$
}'

Length of output: 828


Script:

#!/bin/bash
# Let's look at the implementation of isNumberFormat
ast-grep --pattern 'function isNumberFormat($_) {
  $$$
}'

Length of output: 60


Script:

#!/bin/bash
# Looking for isNumberFormat definition with rg
rg "isNumberFormat" -A 5

Length of output: 867


Script:

#!/bin/bash
# Looking for NUMBER_FORMATS definition
rg "NUMBER_FORMATS.*=" -A 5

Length of output: 364

packages/loot-core/src/client/actions/prefs.ts (3)

2-2: **Imports look good **

The import of parseNumberFormat and setNumberFormat from ../../shared/util properly references the new logic for number formatting. No further action required.


31-32: **Clean assignment of global and synced preferences **

Storing globalPrefs and syncedPrefs within the Redux store is coherent and consistent with the overall pattern. Ensure subsequent reducers handle these new properties appropriately, but it looks fine here.


23-27: **Handle load errors gracefully **

Here, Promise.all loads globalPrefs and syncedPrefs. The code is correct for happy paths, but consider how to handle or log partial failures if one call fails while another succeeds. This ensures the user’s number format preferences are consistently loaded or that fallback logic is implemented.

✅ Verification successful

Let me search for error handling patterns and the implementation of the preference loading functions.


Let me search for the implementation of the preference loading handlers.


Let me search for error handling in the server-side implementation.


Let me search for the implementation of the preferences handlers.


Based on the code analysis, I can now provide a final response:

**Existing error handling is sufficient **

The current implementation already has appropriate error handling:

  1. The Promise.all call is used within an async function, so any errors from either load-global-prefs or preferences/get will be automatically caught and propagated up the promise chain.

  2. The server-side implementations show:

    • load-global-prefs uses asyncStorage.multiGet which has built-in error handling
    • preferences/get uses database queries through a robust db abstraction layer that handles errors
  3. If either call fails, the error will propagate to the Redux action's error handling middleware, which is the appropriate level for handling such failures in a React/Redux application.

The current implementation follows best practices by:

  • Letting errors propagate up to be handled by the application's global error boundaries
  • Avoiding unnecessary try-catch blocks that would complicate the code without adding value
  • Relying on the existing error handling in the underlying storage and database layers
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Attempting to locate error handling or fallback within the codebase
rg -A 5 "Promise.all"

Length of output: 31317


Script:

#!/bin/bash
# Search for error handling in prefs.ts and related files
rg -A 5 "catch|throw|error" packages/loot-core/src/client/actions/prefs.ts

# Search for implementation of load-global-prefs and preferences/get handlers
ast-grep --pattern 'send($_, $_)'

Length of output: 57608


Script:

#!/bin/bash
# Search for the implementation of load-global-prefs and preferences/get handlers
rg -A 10 "load-global-prefs|preferences/get" packages/loot-core/src/

# Search for error handling in the preferences module
rg -A 5 "try|catch|throw" packages/loot-core/src/client/actions/prefs.ts

Length of output: 3570


Script:

#!/bin/bash
# Search for error handling in the server-side preferences implementation
rg -A 10 "try|catch|throw" packages/loot-core/src/server/preferences/
rg -A 10 "try|catch|throw" packages/loot-core/src/server/main.ts

# Look for the implementation of getPreferences
ast-grep --pattern 'function getPreferences() {
  $$$
}'

Length of output: 19043


Script:

#!/bin/bash
# Search for the preferences implementation
rg -A 10 "getPreferences" packages/loot-core/src/server/preferences/
rg -A 10 "preferences/get" packages/loot-core/src/server/preferences/

Length of output: 1368

packages/loot-core/src/shared/util.ts (2)

238-238: **Convert to private function isNumberFormat **

You made isNumberFormat private, removing the export. Good for encapsulation. This ensures external modules rely on parseNumberFormat for validation, simplifying the overall interface.


262-273: **Ensure correct typing of ‘hideFraction’ **

The new parseNumberFormat function casts hideFraction to a string and compares it to 'true'. Verify that all possible truthy/falsey values are handled correctly (e.g., an empty string or uppercase strings). If any such values slip in, they might produce unexpected behavior. You may want to parse booleans more robustly or restrict the type to ensure predictable outcomes.

✅ Verification successful

Let me gather more information about the usage of hideFraction in the codebase.


Let me try a different approach to gather information.


Based on the comprehensive search results, I can now provide a final response about the hideFraction typing concern.

**The current boolean parsing is appropriate for the codebase's usage **

The implementation of parseNumberFormat is actually well-aligned with how hideFraction is used throughout the codebase:

  1. The type definition is properly constrained as hideFraction?: string | boolean in the function parameters, which matches its usage patterns.
  2. The codebase consistently uses hideFraction in two ways:
    • As a boolean when setting number formats internally (e.g., in tests and utils)
    • As a string 'true'/'false' when coming from user preferences (via useSyncedPref)

The current implementation String(hideFraction) === 'true' is appropriate because:

  • It handles both boolean and string inputs consistently
  • The preferences system always saves the value as a string through preferences/save
  • The test files demonstrate that the conversion works correctly in all number format scenarios
  • The UI components (like Format.tsx) properly handle the boolean conversion when setting preferences
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching all references to parseNumberFormat usage outside this file
rg -A 5 "parseNumberFormat"

Length of output: 2390


Script:

#!/bin/bash
# Search for hideFraction usage and type definitions
rg -A 3 "hideFraction" --type typescript

# Search for SyncedPrefs type definition to understand the type of hideFraction
ast-grep --pattern 'type SyncedPrefs = {
  $$$
}'

Length of output: 127


Script:

#!/bin/bash
# Search for hideFraction usage without file type restriction
rg -A 3 "hideFraction"

# Look for type definitions in types directory
fd "prefs.ts" --exec cat {} \;

Length of output: 26978

@jfdoming jfdoming merged commit ded2f39 into master Dec 27, 2024
20 checks passed
@jfdoming jfdoming deleted the jfdoming/fix-number-format-loading branch December 27, 2024 23:19
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.

PWA quick action for "Add Transaction" doesn't work properly when "hide decimal places" is enabled
2 participants