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

feat: optimize robots and runs table ui #382

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

RohitR311
Copy link
Contributor

@RohitR311 RohitR311 commented Jan 23, 2025

Enhance ui performance of recordings and runs table. Closes: #381

Summary by CodeRabbit

  • Performance Improvements

    • Optimized rendering of recordings and runs tables using React memoization techniques.
    • Enhanced performance of table row rendering and data filtering.
    • Improved loading state management with new loading indicators.
  • New Features

    • Added more pagination options (up to 100 rows per page).
    • Implemented more robust error handling for data fetching.
  • User Experience

    • Refined table interaction and search functionality with debounced input.
    • Improved loading indicator visibility.

Copy link

coderabbitai bot commented Jan 23, 2025

Walkthrough

The pull request introduces performance optimizations and structural modifications to the RecordingsTable and RunsTable components in the React application. Key enhancements include the use of React's memo, useCallback, and useMemo to reduce unnecessary re-renders and improve efficiency. New memoized components are added for rendering table rows and cells, while error handling is implemented for data fetching. The loading state is managed more effectively, and pagination options are expanded to enhance user experience.

Changes

File Change Summary
src/components/robot/RecordingsTable.tsx - Added memoized TableRowMemoized component
- Optimized function declarations with useCallback
- Implemented useMemo for columns, filtered rows, and handlers
- Enhanced error handling in fetchRecordings
- Updated loading state management
- Expanded pagination options
src/components/run/RunsTable.tsx - Introduced useCallback and useMemo for performance optimization
- Memoized translatedColumns and renderTableRows functions
- Enhanced error handling in fetchRuns
- Implemented debounced search functionality
- Improved loading state management and pagination options

Suggested labels

Type: Feature, Scope: UI/UX

Suggested reviewers

  • amhsirak

Possibly related PRs

  • feat(ui): runs & robots loader #358: The changes in this PR enhance the RecordingsTable component by adding a loading indicator, which is relevant to the main PR's updates on managing loading states and rendering logic.
  • feat: much more reliable pagination #331: This PR also involves optimizations related to pagination, which aligns with the main PR's focus on improving the performance and efficiency of the RecordingsTable component, particularly in handling data fetching and rendering.

Poem

🐰 Hop, hop, performance dance!
Memoized rows, a rabbit's chance
Rendering swift, no extra strain
React's magic breaks the chain
Efficiency hops with glee! 🚀


🪧 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

@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: 2

🧹 Nitpick comments (4)
src/components/robot/RecordingsTable.tsx (4)

501-509: Reevaluate memoization of simple components

Memoizing components like TableCell and the action buttons might not yield significant performance benefits, as these components are lightweight and may not cause performance issues. Over-memoization can add unnecessary complexity to the codebase.

Consider removing unnecessary memoization:

- const MemoizedTableCell = memo(TableCell);

- // Memoized action buttons
- const MemoizedInterpretButton = memo(InterpretButton);
- const MemoizedScheduleButton = memo(ScheduleButton);
- const MemoizedIntegrateButton = memo(IntegrateButton);
- const MemoizedSettingsButton = memo(SettingsButton);
- const MemoizedOptionsButton = memo(OptionsButton);

If profiling indicates that these components do not cause performance bottlenecks, it's preferable to use them without memo for cleaner code.


134-136: Include dependencies in 'handleChangePage' useCallback

The handleChangePage function uses setPage, which is not included in the dependency array of the useCallback. While state setters like setPage are stable and don't strictly need to be included, adding them can improve code clarity and prevent potential issues if the function logic changes.

Update the dependencies:

- }, []);
+ }, [setPage]);

148-175: Ensure all dependencies are included in 'fetchRecordings' useCallback

The fetchRecordings function uses setIsLoading, but it's not listed in the dependency array. Although state setter functions are stable, including them can enhance readability and maintain consistency.

Update the dependencies:

 }, [setRecordings, notify, t
+ , setIsLoading
 ]);

255-258: Simplify state management after deletion

After successfully deleting a recording, the code calls setRows([]); followed by fetchRecordings();. Clearing rows before refetching may cause an unnecessary intermediate render. Since fetchRecordings updates rows, you can remove the setRows([]); call to streamline the code.

Apply this diff to simplify:

           const success = await deleteRecordingFromStorage(id);
           if (success) {
-            setRows([]);
             notify('success', t('recordingtable.notifications.delete_success'));
             fetchRecordings();
           }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 468f401 and 1ae738e.

📒 Files selected for processing (1)
  • src/components/robot/RecordingsTable.tsx (6 hunks)

Comment on lines 227 to 232
const filteredRows = useMemo(() => {
const searchLower = searchTerm.toLowerCase();
return searchTerm
? rows.filter(row => row.name.toLowerCase().includes(searchLower))
: rows;
}, [rows, debouncedSearchTerm]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use debounced search term for consistent filtering

In the filteredRows computation, the filtering logic uses searchTerm instead of debouncedSearchTerm. This can cause the filter to react to every keystroke, negating the intended debounce effect. To ensure the filter updates correspond with the debounced input, use debouncedSearchTerm in your filtering logic.

Apply this diff to fix the issue:

 const filteredRows = useMemo(() => {
-  const searchLower = searchTerm.toLowerCase();
-  return searchTerm
+  const searchLower = debouncedSearchTerm.toLowerCase();
+  return debouncedSearchTerm
     ? rows.filter(row => row.name.toLowerCase().includes(searchLower))
     : rows;
- }, [rows, debouncedSearchTerm]);
+ }, [rows, debouncedSearchTerm]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const filteredRows = useMemo(() => {
const searchLower = searchTerm.toLowerCase();
return searchTerm
? rows.filter(row => row.name.toLowerCase().includes(searchLower))
: rows;
}, [rows, debouncedSearchTerm]);
const filteredRows = useMemo(() => {
const searchLower = debouncedSearchTerm.toLowerCase();
return debouncedSearchTerm
? rows.filter(row => row.name.toLowerCase().includes(searchLower))
: rows;
}, [rows, debouncedSearchTerm]);

Comment on lines +56 to +110
const TableRowMemoized = memo(({ row, columns, handlers }: any) => {
return (
<TableRow hover role="checkbox" tabIndex={-1}>
{columns.map((column: Column) => {
const value: any = row[column.id];
if (value !== undefined) {
return (
<MemoizedTableCell key={column.id} align={column.align}>
{value}
</MemoizedTableCell>
);
} else {
switch (column.id) {
case 'interpret':
return (
<MemoizedTableCell key={column.id} align={column.align}>
<MemoizedInterpretButton handleInterpret={() => handlers.handleRunRecording(row.id, row.name, row.params || [])} />
</MemoizedTableCell>
);
case 'schedule':
return (
<MemoizedTableCell key={column.id} align={column.align}>
<MemoizedScheduleButton handleSchedule={() => handlers.handleScheduleRecording(row.id, row.name, row.params || [])} />
</MemoizedTableCell>
);
case 'integrate':
return (
<MemoizedTableCell key={column.id} align={column.align}>
<MemoizedIntegrateButton handleIntegrate={() => handlers.handleIntegrateRecording(row.id, row.name, row.params || [])} />
</MemoizedTableCell>
);
case 'options':
return (
<MemoizedTableCell key={column.id} align={column.align}>
<MemoizedOptionsButton
handleEdit={() => handlers.handleEditRobot(row.id, row.name, row.params || [])}
handleDuplicate={() => handlers.handleDuplicateRobot(row.id, row.name, row.params || [])}
handleDelete={() => handlers.handleDelete(row.id)}
/>
</MemoizedTableCell>
);
case 'settings':
return (
<MemoizedTableCell key={column.id} align={column.align}>
<MemoizedSettingsButton handleSettings={() => handlers.handleSettingsRecording(row.id, row.name, row.params || [])} />
</MemoizedTableCell>
);
default:
return null;
}
}
})}
</TableRow>
);
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Define explicit types instead of using 'any'

The TableRowMemoized component and its nested components use the any type for props. This practice weakens type safety and can lead to runtime errors that TypeScript is designed to prevent. Defining explicit interfaces for your props enhances code reliability and maintainability.

Apply this diff to define appropriate types:

+ interface TableRowProps {
+   row: Data;
+   columns: Column[];
+   handlers: Handlers;
+ }

- const TableRowMemoized = memo(({ row, columns, handlers }: any) => {
+ const TableRowMemoized = memo(({ row, columns, handlers }: TableRowProps) => {

Similarly, define interfaces for Handlers and ensure all components have proper typings to leverage TypeScript's advantages.

Committable suggestion skipped: line range outside the PR's diff.

@amhsirak amhsirak changed the title feat: optimize recordings and runs table ui feat: optimize robots and runs table ui Jan 23, 2025
@RohitR311 RohitR311 marked this pull request as draft January 23, 2025 13:55
@RohitR311 RohitR311 marked this pull request as ready for review January 23, 2025 14:57
Copy link

@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 (3)
src/components/run/RunsTable.tsx (3)

101-115: Consider using a custom debounce hook

The current implementation has a few areas for improvement:

  1. The Function type is too generic and could lead to type-safety issues
  2. The debounce logic could be extracted into a reusable hook

Consider refactoring to use a custom hook:

interface DebouncedFunction<T extends (...args: any[]) => any> {
  (...args: Parameters<T>): void;
}

function useDebounce<T extends (...args: any[]) => any>(
  fn: T,
  delay: number
): DebouncedFunction<T> {
  const timeoutRef = React.useRef<NodeJS.Timeout>();

  return React.useCallback(
    (...args: Parameters<T>) => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      timeoutRef.current = setTimeout(() => fn(...args), delay);
    },
    [fn, delay]
  );
}

// Usage
const debouncedSetSearch = useDebounce((value: string) => {
  setSearchTerm(value);
  setPage(0);
}, 300);
🧰 Tools
🪛 Biome (1.9.4)

[error] 101-101: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)


117-135: Enhance error handling with specific error messages

While the error handling is good, consider providing more specific error messages based on the error type.

Consider enhancing the error handling:

  } catch (error) {
-   notify('error', t('runstable.notifications.fetch_error'));
+   const errorMessage = error instanceof Error 
+     ? `${t('runstable.notifications.fetch_error')}: ${error.message}`
+     : t('runstable.notifications.fetch_error');
+   notify('error', errorMessage);
  }

179-196: Consider extracting CollapsibleRow as a memoized component

While the renderTableRows memoization is good, the CollapsibleRow component could be memoized separately for better granular control over re-renders.

Consider creating a memoized version of CollapsibleRow:

const MemoizedCollapsibleRow = React.memo(CollapsibleRow, (prev, next) => {
  return (
    prev.row.id === next.row.id &&
    prev.isOpen === next.isOpen &&
    prev.currentLog === next.currentLog &&
    prev.runningRecordingName === next.runningRecordingName
  );
});

Then use it in renderTableRows:

- <CollapsibleRow
+ <MemoizedCollapsibleRow
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f907c09 and 7289dad.

📒 Files selected for processing (1)
  • src/components/run/RunsTable.tsx (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/run/RunsTable.tsx

[error] 101-101: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)

🔇 Additional comments (3)
src/components/run/RunsTable.tsx (3)

72-78: Good use of useMemo for translations!

The memoization of translatedColumns prevents unnecessary recalculations when other state changes occur.


228-228: Good performance optimization with unmountOnExit!

Using unmountOnExit helps reduce the memory footprint by unmounting inactive accordion panels.


138-151: Well-implemented cleanup in useEffect!

Good use of the mounted flag to prevent memory leaks and proper cleanup on component unmount.

@amhsirak amhsirak added the Type: Enhancement Improvements to existing features label Jan 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: Enhancement Improvements to existing features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

feat: improve load times for robots and runs
2 participants