Skip to content

feat: sort functionality for runs table data #407

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

Merged
merged 4 commits into from
Jan 29, 2025
Merged

feat: sort functionality for runs table data #407

merged 4 commits into from
Jan 29, 2025

Conversation

RohitR311
Copy link
Collaborator

@RohitR311 RohitR311 commented Jan 27, 2025

Closes: #404

Maxun._.Open.Source.No.Code.Web.Data.Extraction.Platform.-.Brave.2025-01-28.00-50-51.mp4

Summary by CodeRabbit

  • New Features

    • Added interactive sorting functionality to the Runs Table.
    • Introduced tooltips to guide users on how to sort table columns.
  • Localization

    • Added "Click to sort" tooltip translations for multiple languages (German, English, Spanish, Japanese, Chinese).

@RohitR311 RohitR311 self-assigned this Jan 27, 2025
Copy link

coderabbitai bot commented Jan 27, 2025

Walkthrough

This pull request introduces sorting functionality to the RunsTable component across multiple localization files. The changes include adding a new sort_tooltip entry in German, English, Spanish, Japanese, and Chinese localization files, and implementing sorting capabilities in the RunsTable.tsx component. The implementation allows users to sort runs by start and finish times, with a new state management approach for tracking sort configurations per robot meta ID.

Changes

File Change Summary
public/locales/*.json Added "sort_tooltip" localization entries for sorting functionality in multiple languages (German, English, Spanish, Japanese, Chinese)
src/components/run/RunsTable.tsx - Added SortDirection type
- Created AccordionSortConfig interface
- Implemented accordionSortConfigs state
- Added handleSort function
- Updated renderTableRows with sorting logic
- Introduced renderSortIcon function

Sequence Diagram

sequenceDiagram
    participant User
    participant RunsTable
    participant SortState
    
    User->>RunsTable: Click column header
    RunsTable->>SortState: Update sort configuration
    SortState-->>RunsTable: Return new sort direction
    RunsTable->>RunsTable: Re-render sorted rows
Loading

Possibly related PRs

  • feat: display loader on robot run #398: The changes in this PR also involve modifications to the public/locales/de.json file, adding a loading message similar to the tooltip additions in the main PR, indicating a focus on enhancing user feedback in the localization files.

Suggested labels

Type: Enhancement, Scope: UI/UX

Suggested reviewers

  • amhsirak

Poem

🐰 Sorting runs with a click so neat,
Columns dance to a rhythmic beat
Tooltips whisper, "Sort with grace!"
Data now finds its perfect place
A rabbit's code, both swift and light 🔍


🪧 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.

@RohitR311 RohitR311 requested a review from amhsirak January 27, 2025 19:25
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

🔭 Outside diff range comments (1)
src/components/run/RunsTable.tsx (1)

Line range hint 209-242: Improve date handling robustness.

The current date string manipulation assumes a specific format and might fail with different locale formats. Consider using a date parsing library like date-fns or moment.js for more robust date handling.

Apply this diff to improve date handling:

-const dateA = new Date(a[sortConfig.field!].replace(/(\d+)\/(\d+)\//, '$2/$1/'));
-const dateB = new Date(b[sortConfig.field!].replace(/(\d+)\/(\d+)\//, '$2/$1/'));
+import { parse } from 'date-fns';
+
+const parseDate = (dateStr: string) => {
+  try {
+    return parse(dateStr, 'dd/MM/yyyy HH:mm:ss', new Date());
+  } catch (error) {
+    console.error(`Failed to parse date: ${dateStr}`, error);
+    return new Date(0); // fallback to epoch
+  }
+};
+
+const dateA = parseDate(a[sortConfig.field!]);
+const dateB = parseDate(b[sortConfig.field!]);
🧹 Nitpick comments (2)
src/components/run/RunsTable.tsx (2)

314-351: Enhance accessibility for sortable columns.

While the implementation is good, consider adding ARIA attributes to improve accessibility for screen readers.

Apply this diff to enhance accessibility:

 <TableCell
   key={column.id}
   align={column.align}
   style={{ 
     minWidth: column.minWidth,
     cursor: column.id === 'startedAt' || column.id === 'finishedAt' ? 'pointer' : 'default'
   }}
+  aria-sort={
+    column.id === 'startedAt' || column.id === 'finishedAt'
+      ? accordionSortConfigs[robotMetaId]?.field === column.id
+        ? accordionSortConfigs[robotMetaId].direction
+        : 'none'
+      : undefined
+  }
+  role="columnheader"
   onClick={() => {
     if (column.id === 'startedAt' || column.id === 'finishedAt') {
       handleSort(column.id, robotMetaId);
     }
   }}

190-195: Optimize search filtering performance.

Consider memoizing the search term transformation to avoid unnecessary string operations on every render.

Apply this diff to optimize performance:

 const filteredRows = useMemo(() => {
+  const searchLower = searchTerm.toLowerCase();
   let result = rows.filter((row) =>
-    row.name.toLowerCase().includes(searchTerm.toLowerCase())
+    row.name.toLowerCase().includes(searchLower)
   );
   return result;
-}, [rows, searchTerm]);
+}, [rows, searchTerm]); 
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4484abf and f8fcc85.

📒 Files selected for processing (6)
  • public/locales/de.json (1 hunks)
  • public/locales/en.json (1 hunks)
  • public/locales/es.json (1 hunks)
  • public/locales/ja.json (1 hunks)
  • public/locales/zh.json (1 hunks)
  • src/components/run/RunsTable.tsx (8 hunks)
🔇 Additional comments (8)
src/components/run/RunsTable.tsx (3)

31-38: Well-structured type definitions for sorting functionality!

The SortDirection type and AccordionSortConfig interface provide a clean and type-safe way to manage sorting states independently for each robot meta ID.


82-100: Clean implementation of sort state management!

The sort handler effectively manages state with proper immutability and includes memoization for performance optimization. The sort direction cycles logically through none -> asc -> desc -> none.


244-268: Excellent implementation of sort icons with visual feedback!

The sort icon rendering provides clear visual feedback with proper opacity transitions and follows Material-UI best practices.

public/locales/zh.json (1)

66-66: Appropriate Chinese translation for sort tooltip!

The translation "点击排序" is concise and accurately conveys the sorting action to Chinese users.

public/locales/ja.json (1)

66-66: Appropriate Japanese translation for sort tooltip!

The translation "クリックして並べ替え" is natural and follows Japanese language conventions.

public/locales/en.json (1)

66-66: Clear and concise English tooltip text!

The text "Click to sort" effectively communicates the action to users.

public/locales/es.json (1)

66-66: LGTM! Spanish translation is accurate and natural.

The tooltip message "Haga clic para ordenar" is grammatically correct and effectively conveys the sorting functionality to Spanish users.

public/locales/de.json (1)

65-65: LGTM! German translation is accurate and natural.

The tooltip message "Zum Sortieren klicken" is grammatically correct and effectively conveys the sorting functionality to German users.

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

🧹 Nitpick comments (1)
src/components/run/RunsTable.tsx (1)

Line range hint 221-254: Optimize sorting performance.

The current implementation sorts the data on every render. Consider memoizing the sorted data to improve performance.

-  const renderTableRows = useCallback((data: Data[], robotMetaId: string) => {
+  const getSortedData = useCallback((data: Data[], robotMetaId: string) => {
     const sortConfig = accordionSortConfigs[robotMetaId];
-    let sortedData = [...data];
     
     if (sortConfig?.field === 'startedAt' || sortConfig?.field === 'finishedAt') {
       if (sortConfig.direction !== 'none') {
-        sortedData.sort((a, b) => {
+        return [...data].sort((a, b) => {
           const dateA = parseDateString(a[sortConfig.field!]);
           const dateB = parseDateString(b[sortConfig.field!]);
           
           return sortConfig.direction === 'asc' 
             ? dateA.getTime() - dateB.getTime() 
             : dateB.getTime() - dateA.getTime();
         });
       }
     }
+    return data;
+  }, [accordionSortConfigs, parseDateString]);
+
+  const sortedDataMap = useMemo(() => {
+    const map = new Map<string, Data[]>();
+    Object.entries(groupedRows).forEach(([robotMetaId, data]) => {
+      map.set(robotMetaId, getSortedData(data, robotMetaId));
+    });
+    return map;
+  }, [groupedRows, getSortedData]);
+
+  const renderTableRows = useCallback((data: Data[], robotMetaId: string) => {
     const start = page * rowsPerPage;
     const end = start + rowsPerPage;
     
-    return sortedData
+    return sortedDataMap.get(robotMetaId)
       .slice(start, end)
       .map((row) => (
         <CollapsibleRow
           key={`row-${row.id}`}
           row={row}
           handleDelete={handleDelete}
           isOpen={runId === row.runId && runningRecordingName === row.name}
           currentLog={currentInterpretationLog}
           abortRunHandler={abortRunHandler}
           runningRecordingName={runningRecordingName}
         />
       ));
-  }, [page, rowsPerPage, runId, runningRecordingName, currentInterpretationLog, abortRunHandler, handleDelete, accordionSortConfigs]);
+  }, [page, rowsPerPage, runId, runningRecordingName, currentInterpretationLog, abortRunHandler, handleDelete, sortedDataMap]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f8fcc85 and 48cbedc.

📒 Files selected for processing (1)
  • src/components/run/RunsTable.tsx (8 hunks)
🔇 Additional comments (5)
src/components/run/RunsTable.tsx (5)

31-38: LGTM! Well-structured type definitions for sorting.

The SortDirection type and AccordionSortConfig interface provide a robust foundation for managing sort states per robot meta ID.


82-82: LGTM! Efficient sort state management.

Using a separate sort configuration per robot meta ID allows for independent sorting of each accordion section.


84-100: LGTM! Well-implemented sort direction cycling.

The handleSort function correctly implements the sort direction cycle (none → asc → desc → none) while maintaining independent sort states for each robot meta ID.


326-363: LGTM! Excellent UI/UX implementation for sorting.

The implementation includes:

  • Clear visual feedback with sort icons
  • Smooth hover transitions
  • Proper accessibility with tooltips
  • Cursor changes only for sortable columns

339-339: Verify sort tooltip translations.

Ensure that the sort_tooltip translation key is present in all language files.

✅ Verification successful

Translation key sort_tooltip is present in all locale files

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for missing sort_tooltip translations
for locale in public/locales/*.json; do
  echo "Checking $locale..."
  if ! grep -q '"sort_tooltip"' "$locale"; then
    echo "Warning: Missing sort_tooltip in $locale"
  fi
done

Length of output: 834

Comment on lines +209 to +219
const parseDateString = (dateStr: string): Date => {
try {
if (dateStr.includes('PM') || dateStr.includes('AM')) {
return new Date(dateStr);
}

return new Date(dateStr.replace(/(\d+)\/(\d+)\//, '$2/$1/'))
} catch {
return new Date(0);
}
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance date parsing robustness.

The current date parsing implementation has potential issues:

  1. The date format detection is fragile
  2. Silently falling back to epoch time (Date(0)) could hide parsing errors

Consider using a robust date parsing library:

-  const parseDateString = (dateStr: string): Date => {
-    try {
-      if (dateStr.includes('PM') || dateStr.includes('AM')) {
-        return new Date(dateStr);
-      }
-      
-      return new Date(dateStr.replace(/(\d+)\/(\d+)\//, '$2/$1/'))
-    } catch {
-      return new Date(0);
-    }
-  };
+  import { parseISO, parse } from 'date-fns';
+  
+  const parseDateString = (dateStr: string): Date => {
+    try {
+      // First try ISO format
+      const isoDate = parseISO(dateStr);
+      if (!isNaN(isoDate.getTime())) return isoDate;
+      
+      // Then try common formats
+      const formats = [
+        'MM/dd/yyyy h:mm a',
+        'dd/MM/yyyy HH:mm',
+      ];
+      
+      for (const format of formats) {
+        const parsedDate = parse(dateStr, format, new Date());
+        if (!isNaN(parsedDate.getTime())) return parsedDate;
+      }
+      
+      throw new Error(`Unable to parse date: ${dateStr}`);
+    } catch (error) {
+      console.error(`Date parsing error: ${error}`);
+      throw error; // Let the caller handle the error
+    }
+  };

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

@amhsirak amhsirak merged commit 98ba962 into develop Jan 29, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

feat: sort functionality for robot runs table
2 participants