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

Convert BudgetTable.jsx to tsx #3899

Merged
merged 2 commits into from
Dec 10, 2024
Merged

Convert BudgetTable.jsx to tsx #3899

merged 2 commits into from
Dec 10, 2024

Conversation

joel-jeremy
Copy link
Contributor

No description provided.

@actual-github-bot actual-github-bot bot changed the title Convert BudgetTable.jsx to tsx [WIP] Convert BudgetTable.jsx to tsx Nov 25, 2024
Copy link

netlify bot commented Nov 25, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit a149e32
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/6744fa72a7a4910008fd525e
😎 Deploy Preview https://deploy-preview-3899.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] Convert BudgetTable.jsx to tsx Convert BudgetTable.jsx to tsx Nov 25, 2024
Copy link
Contributor

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 (+304 B) +0.01%
Changeset
File Δ Size
src/components/budget/BudgetTable.tsx 🆕 +6.23 kB 0 B → 6.23 kB
node_modules/clsx/dist/clsx.js 🆕 +509 B 0 B → 509 B
node_modules/clsx/dist/clsx.js?commonjs-module 🆕 +27 B 0 B → 27 B
src/components/budget/DynamicBudgetTable.tsx 📈 +16 B (+0.54%) 2.88 kB → 2.89 kB
src/components/budget/index.tsx 📈 +39 B (+0.42%) 9.03 kB → 9.07 kB
node_modules/react-grid-layout/build/ReactGridLayout.js 📉 -1 B (-0.00%) 24.96 kB → 24.96 kB
node_modules/react-grid-layout/build/GridItem.js 📉 -1 B (-0.00%) 21.49 kB → 21.49 kB
node_modules/react-grid-layout/build/components/WidthProvider.js 📉 -1 B (-0.02%) 5.22 kB → 5.22 kB
src/components/budget/BudgetTable.jsx 🔥 -6.08 kB (-100%) 6.08 kB → 0 B
node_modules/clsx/dist/clsx.mjs 🔥 -368 B (-100%) 368 B → 0 B
node_modules/clsx/dist/clsx.mjs?commonjs-proxy 🔥 -64 B (-100%) 64 B → 0 B
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/wide.js 241.19 kB → 241.39 kB (+203 B) +0.08%
static/js/index.js 3.44 MB → 3.44 MB (+168 B) +0.00%

Smaller

Asset File Size % Changed
static/js/ReportRouter.js 1.52 MB → 1.52 MB (-67 B) -0.00%

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%

Copy link
Contributor

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 bot commented Nov 25, 2024

Walkthrough

The pull request introduces several modifications across multiple components related to budget management in the desktop client. The BudgetTable component has been updated to include a new type, BudgetTableProps, which enhances type safety by explicitly defining required properties such as type, prewarmStartMonth, and callback functions. The DynamicBudgetTable component also sees changes, with the addition of the type property and updates to its props using TypeScript's Omit utility to exclude numMonths. The MonthPicker component's monthBounds prop type has been renamed from BoundsProps to MonthBounds, reflecting a change in type naming conventions. Similarly, in MonthsContext, the BoundsProps type has been renamed to MonthBounds, affecting its usage in function signatures. Lastly, the onApplyBudgetTemplatesInGroup function is now passed as a prop to the DynamicBudgetTable component within both the TrackingBudgetProvider and EnvelopeBudgetProvider, enhancing functionality without altering existing logic.

Possibly related PRs

Suggested labels

sparkles: Merged

Suggested reviewers

  • youngcw
  • matt-fidd

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/budget/BudgetTable.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.


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

🧹 Outside diff range and nitpick comments (12)
packages/desktop-client/src/components/budget/MonthsContext.tsx (3)

6-9: Consider using a more specific type for month strings.

The type rename from BoundsProps to MonthBounds is a good improvement in naming. However, consider using a more specific type for the month strings to ensure type safety.

+type MonthString = `${number}-${string}`; // e.g., "2024-01"

 export type MonthBounds = {
-  start: string;
-  end: string;
+  start: MonthString;
+  end: MonthString;
 };

11-14: Add return type annotation and improve null safety.

While the type update is good, consider these improvements for better type safety:

 export function getValidMonthBounds(
   bounds: MonthBounds,
   startMonth: undefined | string,
   endMonth: string,
-) {
+): MonthBounds {
+  if (!startMonth) {
+    return bounds;
+  }

Consider initializing MonthsContext with a proper default value instead of null

The @ts-strict-ignore directive can be removed after fixing the unsafe null initialization of the context. The context is typed as MonthsContextProps but initialized with null, which is unsafe. Instead, provide a proper default value:

export const MonthsContext = createContext<MonthsContextProps>({
  months: [],
  type: ''
});
🔗 Analysis chain

Line range hint 1-1: Consider removing ts-strict-ignore.

The file has TypeScript strict mode disabled. Since we're working on improving type safety, we should investigate if this can be removed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if we can enable strict mode by running TypeScript compiler in strict mode
echo "Checking TypeScript errors..."
npx tsc packages/desktop-client/src/components/budget/MonthsContext.tsx --strict --noEmit --jsx react

Length of output: 266


Script:

#!/bin/bash
# Let's examine the content of the file and look for potential type-related issues
cat packages/desktop-client/src/components/budget/MonthsContext.tsx

# Also search for other ts-strict-ignore comments in the codebase to understand the pattern
rg "@ts-strict-ignore" -A 5

Length of output: 100451


Script:

#!/bin/bash
# Let's check for any type-related issues in the file
ast-grep --pattern $'type MonthsContextProps = {
  $$$
};

export const MonthsContext = createContext<MonthsContextProps>($$$);'

# Also check for any potential null/undefined issues
ast-grep --pattern $'createContext<$_>($$$)'

Length of output: 4091

packages/desktop-client/src/components/budget/DynamicBudgetTable.tsx (2)

148-154: Consider enhancing type safety

A few suggestions to improve the type definitions:

  1. The maxMonths property has a default value in the component but is marked as required in the type definition.
  2. Consider removing the @ts-strict-ignore directive by addressing type issues.

Apply this diff to improve type safety:

 type DynamicBudgetTableProps = Omit<
   ComponentProps<typeof BudgetTable>,
   'numMonths'
 > & {
-  maxMonths: number;
+  maxMonths?: number;
   onMonthSelect: (month: string, numMonths: number) => void;
 };

Line range hint 1-167: Well-structured component architecture

The component demonstrates good architectural patterns:

  • Clear separation of concerns between size management (AutoSizer) and core functionality
  • Effective use of React hooks for keyboard shortcuts
  • Robust month bounds validation and handling
packages/desktop-client/src/components/budget/MonthPicker.tsx (1)

Line range hint 91-98: LGTM! Consider extracting style conditions.

The implementation correctly handles month bounds validation and provides appropriate visual feedback. However, the inline styles could be made more maintainable by extracting the complex conditional styling logic into separate functions or constants.

Example refactor:

const getMonthStyle = (isMonthBudgeted: boolean) => ({
  textDecoration: isMonthBudgeted ? 'none' : 'line-through',
  color: isMonthBudgeted ? theme.pageText : theme.pageTextSubdued
});
packages/desktop-client/src/components/budget/BudgetTable.tsx (5)

29-59: Consider improving type safety for onBudgetAction

The onBudgetAction callback uses unknown for its args parameter, which could be made more type-safe.

Consider creating a discriminated union type for the budget actions:

type BudgetAction = 
  | { type: 'set_budget'; amount: number }
  | { type: 'copy_last'; month: string }
  // Add other action types as needed

type BudgetTableProps = {
  // ... other props
  onBudgetAction: (month: string, type: string, args: BudgetAction) => void;
};

289-289: Remove @ts-expect-error by completing TypeScript migration

The comment indicates that BudgetCategories component needs to be migrated to TypeScript. This should be addressed to maintain full type safety across the codebase.

Would you like me to help create a new PR to migrate the BudgetCategories component to TypeScript?


177-183: Simplify the group check in moveVertically

The continue statement can be removed by restructuring the condition.

-        if ('isGroup' in next && next.isGroup) {
-          nextIdx += dir;
-          continue;
-        } else if (
+        if (!('isGroup' in next && next.isGroup) && (
           type === 'report' ||
           ('is_income' in next && !next.is_income)
-        ) {
+        )) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 179-179: Unnecessary continue statement

Unsafe fix: Delete the unnecessary continue statement

(lint/correctness/noUnnecessaryContinue)


Line range hint 154-192: Consider enhancing moveVertically with boundary checks

The vertical movement logic could benefit from additional safety checks:

  1. Ensure nextIdx doesn't exceed array bounds
  2. Add a maximum iteration limit to prevent potential infinite loops
const MAX_ITERATIONS = 1000; // Prevent infinite loops
let iterations = 0;

while (nextIdx >= 0 && nextIdx < flattened.length && iterations < MAX_ITERATIONS) {
  iterations++;
  // ... existing logic
}

if (iterations === MAX_ITERATIONS) {
  console.warn('Maximum iterations reached in moveVertically');
}

Line range hint 1-307: Overall TypeScript conversion looks good

The conversion to TypeScript has been well executed with proper type definitions and usage. The remaining work involves:

  1. Migrating BudgetCategories to TypeScript
  2. Improving type safety for action handlers
  3. Adding proper type guards for runtime checks

These can be addressed in follow-up PRs to maintain the focused scope of this conversion.

Consider creating a tracking issue for the remaining TypeScript migrations in the codebase to maintain consistency.

packages/desktop-client/src/components/budget/index.tsx (1)

Line range hint 1-1: Consider removing @ts-strict-ignore

Since this PR aims to convert to TypeScript, consider addressing the type issues that necessitate @ts-strict-ignore. This would improve type safety across the component.

Some suggestions:

  1. Add explicit type for onApplyBudgetTemplatesInGroup:
type BudgetTemplateHandler = (categories: Array<string>) => Promise<void>;

interface DynamicBudgetTableProps {
  // ... existing props
  onApplyBudgetTemplatesInGroup: BudgetTemplateHandler;
}
  1. Consider splitting the large component into smaller typed components to make type checking more manageable.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

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

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3899.md is excluded by !**/*.md
📒 Files selected for processing (5)
  • packages/desktop-client/src/components/budget/BudgetTable.tsx (8 hunks)
  • packages/desktop-client/src/components/budget/DynamicBudgetTable.tsx (2 hunks)
  • packages/desktop-client/src/components/budget/MonthPicker.tsx (1 hunks)
  • packages/desktop-client/src/components/budget/MonthsContext.tsx (2 hunks)
  • packages/desktop-client/src/components/budget/index.tsx (2 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/desktop-client/src/components/budget/index.tsx (1)
Learnt from: UnderKoen
PR: actualbudget/actual#3381
File: packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx:274-274
Timestamp: 2024-11-10T16:45:25.627Z
Learning: UnderKoen prefers not to include changes that would significantly alter many files in a PR focusing on specific functionality.
🪛 Biome (1.9.4)
packages/desktop-client/src/components/budget/BudgetTable.tsx

[error] 179-179: Unnecessary continue statement

Unsafe fix: Delete the unnecessary continue statement

(lint/correctness/noUnnecessaryContinue)

🔇 Additional comments (6)
packages/desktop-client/src/components/budget/MonthsContext.tsx (1)

6-9: Verify all usages of the renamed type.

The type rename from BoundsProps to MonthBounds might affect other components. Let's verify all usages have been updated.

Also applies to: 32-32

✅ Verification successful

Type rename has been properly implemented across the codebase

The search results show that:

  • There are no remaining references to the old BoundsProps type
  • The new MonthBounds type is consistently used across all relevant files:
    • Defined in MonthsContext.tsx
    • Imported and used in BudgetTable.tsx
    • Imported and used in MonthPicker.tsx
    • Referenced in utility functions in util.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of BoundsProps
echo "Checking for remaining BoundsProps usage..."
rg "BoundsProps" --type ts --type tsx

# Search for MonthBounds usage to verify correct adoption
echo "Checking MonthBounds usage..."
rg "MonthBounds" --type ts --type tsx

Length of output: 297


Script:

#!/bin/bash
# Search for any remaining usage of BoundsProps without file type restrictions
echo "Checking for remaining BoundsProps usage..."
rg "BoundsProps"

# Search for MonthBounds usage
echo "Checking MonthBounds usage..."
rg "MonthBounds"

# Alternative: Use ast-grep to find type declarations and usages
echo "Checking type declarations and usages with ast-grep..."
ast-grep --pattern 'type BoundsProps'
ast-grep --pattern 'type MonthBounds'
ast-grep --pattern ': BoundsProps'
ast-grep --pattern ': MonthBounds'

Length of output: 1600

packages/desktop-client/src/components/budget/DynamicBudgetTable.tsx (1)

Line range hint 134-140: LGTM! Props are correctly passed to BudgetTable

The props are well-structured with explicit props before the spread operator, and all required props including the new type prop are properly passed.

packages/desktop-client/src/components/budget/MonthPicker.tsx (2)

10-15: LGTM! Improved type naming.

The rename from BoundsProps to MonthBounds is a good change as it better describes the purpose of the type. The type is appropriately imported and used in the props interface.


Line range hint 1-1: Consider addressing TypeScript strict mode issues.

The @ts-strict-ignore directive suggests there might be type-safety improvements possible. As part of the TypeScript migration effort, it would be beneficial to resolve these issues and enable strict mode checks.

packages/desktop-client/src/components/budget/BudgetTable.tsx (1)

1-21: LGTM: Well-organized type imports

The TypeScript conversion properly imports necessary types and maintains good organization between different import categories.

packages/desktop-client/src/components/budget/index.tsx (1)

358-358: LGTM: Consistent implementation of budget template functionality

The onApplyBudgetTemplatesInGroup prop is correctly added to both budget types, maintaining consistency across the application.

Also applies to: 385-385

@@ -355,6 +355,7 @@ function BudgetInner(props: BudgetInnerProps) {
onShowActivity={onShowActivity}
onReorderCategory={onReorderCategory}
onReorderGroup={onReorderGroup}
onApplyBudgetTemplatesInGroup={onApplyBudgetTemplatesInGroup}
Copy link
Contributor

Choose a reason for hiding this comment

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

Nice catch 🥳

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