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

(typescript) Refactoring the mobile TransactionList component to typescript #4063

Merged
merged 7 commits into from
Jan 16, 2025

Conversation

leoltl
Copy link
Contributor

@leoltl leoltl commented Dec 31, 2024

Refactoring the mobile TransactionList component to typescript.

re: #1483

@actual-github-bot actual-github-bot bot changed the title (typescript) Refactoring the mobile TransactionList component to typescript [WIP] (typescript) Refactoring the mobile TransactionList component to typescript Dec 31, 2024
Copy link

netlify bot commented Dec 31, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit c06df65
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/677e1b99da46bb00088b852a
😎 Deploy Preview https://deploy-preview-4063.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 31, 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.66 MB → 5.66 MB (-160 B) -0.00%
Changeset
File Δ Size
src/components/mobile/transactions/TransactionList.tsx 🆕 +16.07 kB 0 B → 16.07 kB
node_modules/define-data-property/index.js 📉 -9 B (-0.39%) 2.25 kB → 2.24 kB
node_modules/call-bind/index.js 📉 -9 B (-0.84%) 1.05 kB → 1.04 kB
node_modules/has-property-descriptors/index.js 📉 -9 B (-1.55%) 582 B → 573 B
node_modules/es-define-property/index.js 📉 -210 B (-37.50%) 560 B → 350 B
src/components/mobile/transactions/TransactionList.jsx 🔥 -15.99 kB (-100%) 15.99 kB → 0 B
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

No assets were bigger

Smaller

Asset File Size % Changed
static/js/index.js 3.73 MB → 3.73 MB (-160 B) -0.00%

Unchanged

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

Copy link
Contributor

github-actions bot commented Dec 31, 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.33 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.33 MB 0%

@@ -40,7 +40,7 @@ const ROW_HEIGHT = 60;
type TransactionListItemProps = ComponentPropsWithoutRef<
typeof ListBoxItem<TransactionEntity>
> & {
isNewTransaction: (transaction: TransactionEntity['id']) => boolean;
isNewTransaction?: (transaction: TransactionEntity['id']) => boolean;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't see this prop being used anywhere, I am not sure if I should delete it or leave that as an optional

Copy link
Contributor

Choose a reason for hiding this comment

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

If not used then we can just delete it

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Deleted: 56eba2e

@leoltl leoltl changed the title [WIP] (typescript) Refactoring the mobile TransactionList component to typescript (typescript) Refactoring the mobile TransactionList component to typescript Dec 31, 2024
Copy link
Contributor

coderabbitai bot commented Dec 31, 2024

Walkthrough

The pull request introduces enhancements to type safety in the TransactionList.tsx, TransactionListItem.tsx, and Menu.tsx components of the desktop client. In TransactionList.tsx, new type definitions are established for LoadingProps, TransactionListProps, and SelectedTransactionsFloatingActionBarProps, clarifying the expected properties for these components. The function signatures for Loading, TransactionList, and SelectedTransactionsFloatingActionBar are updated to incorporate these new types. The TransactionListItem.tsx component sees the isNewTransaction property in TransactionListItemProps changed from required to optional, allowing for greater flexibility. Additionally, the Menu.tsx component updates the MenuItemObject type declaration to make it publicly accessible. The changes also include adjustments for type consistency throughout the code.

Possibly related PRs

Suggested labels

#sparkles: Merged, #white_check_mark: Approved

Suggested reviewers

  • joel-jeremy

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 81295e6 and c06df65.

📒 Files selected for processing (1)
  • packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build (macos-latest)
  • GitHub Check: Analyze
  • GitHub Check: build (windows-latest)
  • GitHub Check: Wait for Netlify build to finish
  • GitHub Check: build (ubuntu-latest)

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 (1)
packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx (1)

85-89: Type-safe grouping logic.

Consider typing sections more explicitly, for example:

const sections: Array<{ id: string; date: string; transactions: TransactionEntity[] }> = [];

This would further improve type clarity.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between da613ab and a2efa90.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4063.md is excluded by !**/*.md
📒 Files selected for processing (2)
  • packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx (8 hunks)
  • packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx (1 hunks)
🔇 Additional comments (14)
packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx (1)

43-43: Confirm usage of isNewTransaction before keeping it as optional.

You mentioned it isn't being used anywhere. If that's indeed the case, consider removing it. Otherwise, please document its intended usage.

Here's a script to search the entire codebase for references to isNewTransaction:

#!/bin/bash
# Searches all TS and TSX files for references to isNewTransaction
fd -e ts -e tsx | xargs rg "isNewTransaction"
packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx (13)

7-7: Good addition of type imports.

Importing type CSSProperties from React is a neat way to keep TypeScript aware of prop shapes.


17-17: Nicely scoped type import for TransactionEntity.

Using import { type TransactionEntity } helps enforce type-only imports and clarity.


45-49: Great introduction of LoadingProps.

Defining a dedicated prop type makes the component’s interface clearer.


50-50: Typed Loading component.

Destructuring typed props is a solid approach. This improves maintainability and ensures aria-label is always defined.


67-73: New TransactionListProps type.

Grouping these props is a nice improvement for readability and type safety.


74-74: Enhanced TransactionList signature.

Using TransactionListProps ensures consistent prop usage and helps catch type mismatches.


81-81: Well-structured destructuring of props.

Using the typed props in the function parameters is a good pattern for clarity.


110-119: Typed onTransactionPress handler.

This ensures clarity on the parameters, reduces runtime errors, and properly handles optional conditions. Good work.


210-213: New SelectedTransactionsFloatingActionBarProps.

Explicitly defining the accepted props is a solid approach, improving reusability.


214-214: No issues found.

The type definition ends properly here, aligning with best TypeScript practices.


215-218: Default value for style promotes flexibility.

Allowing an empty object by default is a clean way to simplify usage.


224-224: Sensible dynamic styling.

Extracting a function reference for style objects is helpful for readability and performance.


463-466: Conditional menu item coloring.

This is a concise way to highlight destructive actions (e.g., delete) differently. Looks good.

getItemStyle={item => ({
...getMenuItemStyle(),
...(item.name === 'delete' && { color: theme.errorTextMenu }),
})}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The menu in L348 does not have a delete MenuItem, and typescript was complaining it referencing a value which it has no overlap.
image
So I am extracting that conditional out as an inline function.

Copy link
Contributor

Choose a reason for hiding this comment

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

Would the typescript error be fixed if we explicitly type the item parameter on L348 or type the getMenuItemStyle function?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I have typed the getMenuItemStyle function and seem to made typescript happy
5623c21

function SelectedTransactionsFloatingActionBar({ transactions, style }) {
type SelectedTransactionsFloatingActionBarProps = {
transactions: Readonly<TransactionEntity[]>;
style?: Parameters<typeof FloatingActionBar>[0]['style'];
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
style?: Parameters<typeof FloatingActionBar>[0]['style'];
style?: CSSProperties;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Addressed: 56eba2e

getItemStyle={item => ({
...getMenuItemStyle(),
...(item.name === 'delete' && { color: theme.errorTextMenu }),
})}
Copy link
Contributor

Choose a reason for hiding this comment

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

Would the typescript error be fixed if we explicitly type the item parameter on L348 or type the getMenuItemStyle function?

@@ -40,7 +40,7 @@ const ROW_HEIGHT = 60;
type TransactionListItemProps = ComponentPropsWithoutRef<
typeof ListBoxItem<TransactionEntity>
> & {
isNewTransaction: (transaction: TransactionEntity['id']) => boolean;
isNewTransaction?: (transaction: TransactionEntity['id']) => boolean;
Copy link
Contributor

Choose a reason for hiding this comment

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

If not used then we can just delete it

Copy link
Contributor Author

@leoltl leoltl left a comment

Choose a reason for hiding this comment

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

@joel-jeremy Thanks for reviewing the PR. I have updated my PR to address the few comments

function SelectedTransactionsFloatingActionBar({ transactions, style }) {
type SelectedTransactionsFloatingActionBarProps = {
transactions: Readonly<TransactionEntity[]>;
style?: Parameters<typeof FloatingActionBar>[0]['style'];
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Addressed: 56eba2e

@@ -40,7 +40,7 @@ const ROW_HEIGHT = 60;
type TransactionListItemProps = ComponentPropsWithoutRef<
typeof ListBoxItem<TransactionEntity>
> & {
isNewTransaction: (transaction: TransactionEntity['id']) => boolean;
isNewTransaction?: (transaction: TransactionEntity['id']) => boolean;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Deleted: 56eba2e

getItemStyle={item => ({
...getMenuItemStyle(),
...(item.name === 'delete' && { color: theme.errorTextMenu }),
})}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I have typed the getMenuItemStyle function and seem to made typescript happy
5623c21

function SelectedTransactionsFloatingActionBar({
transactions,
style = {},
}: SelectedTransactionsFloatingActionBarProps) {
const editMenuTriggerRef = useRef(null);
const [isEditMenuOpen, setIsEditMenuOpen] = useState(false);
const moreOptionsMenuTriggerRef = useRef(null);
const [isMoreOptionsMenuOpen, setIsMoreOptionsMenuOpen] = useState(false);
const getMenuItemStyle = useCallback(
Copy link
Contributor

Choose a reason for hiding this comment

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

I think this would also work instead of exporting the type

Suggested change
const getMenuItemStyle = useCallback(
const getMenuItemStyle: ComponentProps<typeof Menu>['getItemStyle'] = useCallback(

Copy link
Contributor Author

@leoltl leoltl Jan 8, 2025

Choose a reason for hiding this comment

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

@joel-jeremy Thanks for the second review and suggestion! Unfortunately the proposed change doesn't seem to work. 😢
image

I believe it is because the type of 'NameType' in the first argument of the Menu's 'getItemStyle' is a generic that bounds to the actual Menu instance (i.e. TS resolving the type from the items the Menu instance was passed). Whereas it is unknown type when it is not bounded to the Menu instance.

I am open to other suggestion, but so far setting this anonymous function with generic type is only way I get typing to work/ agree.

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

🧹 Nitpick comments (2)
packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx (2)

67-73: Consider adding error handling for onLoadMore callback.

While the type definitions are well-structured, consider adding error handling for the onLoadMore callback to handle potential failures when loading additional transactions.

 type TransactionListProps = {
   isLoading: boolean;
   transactions: readonly TransactionEntity[];
   onOpenTransaction?: (transaction: TransactionEntity) => void;
   isLoadingMore: boolean;
-  onLoadMore: () => void;
+  onLoadMore: () => Promise<void>;
+  onLoadMoreError?: (error: Error) => void;
 };

Also applies to: 85-89


210-213: Consider using a more specific type constraint for menu items.

The generic type T extends string could be more specific to better type-check menu item names.

-    <T extends string>(item: MenuItemObject<T>) => ({
+    <T extends 'delete' | 'duplicate' | 'link-schedule' | 'unlink-schedule'>(
+      item: MenuItemObject<T>
+    ) => ({

Also applies to: 224-228

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5623c21 and 81295e6.

📒 Files selected for processing (2)
  • packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx (8 hunks)
  • packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: Analyze
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (2)
packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx (2)

7-7: LGTM! Clean type imports.

The type imports are well-organized and properly sourced from their respective modules.

Also applies to: 16-16, 34-34


45-48: Well-structured type definition with good accessibility consideration!

The LoadingProps type properly enforces accessibility by making aria-label required while keeping style optional.

Also applies to: 50-50

Comment on lines +359 to +360
displayValue =
accountsById[String(value)]?.name ?? value;
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 8, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add type safety checks for number conversion.

The number conversion for integerToCurrency could fail if the value is not a valid number. Consider adding validation:

-  displayValue = integerToCurrency(Number(value));
+  const numValue = Number(value);
+  if (Number.isNaN(numValue)) {
+    throw new Error(`Invalid amount value: ${value}`);
+  }
+  displayValue = integerToCurrency(numValue);

Also applies to: 363-364, 367-367, 370-370

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated: c06df65

Copy link
Contributor

Choose a reason for hiding this comment

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

@leoltl Thank you for implementing the number validation! Your solution to gracefully handle invalid numbers by preserving the original value is even better than throwing an error. The changes look good.

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Get the specific changes in the commit related to number conversion
git show c06df652dbfb813f0a596cb5b78ea6f672d4099d -- 'packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx'

Length of output: 1269


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link
Contributor

@joel-jeremy joel-jeremy left a comment

Choose a reason for hiding this comment

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

LGTM!

@joel-jeremy joel-jeremy merged commit 7ae6442 into actualbudget:master Jan 16, 2025
20 checks passed
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