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 non-editable views state issue and conditional row actions for TableView #4969

Merged
merged 3 commits into from
Oct 29, 2024

Conversation

imanjra
Copy link
Contributor

@imanjra imanjra commented Oct 23, 2024

What changes are proposed in this pull request?

fix non-editable views state issue and conditional row actions for TableView

How is this patch tested? If it is not, please explain why.

Using a python panel

Release Notes

Is this a user-facing change that should be mentioned in the release notes?

  • No. You can skip the rest of this section.
  • Yes. Give a description of this change to be included in the release
    notes for FiftyOne users.

(Details in 1-2 sentences. You can just refer to another PR with a description
if this PR is part of a larger change.)

What areas of FiftyOne does this PR affect?

  • App: FiftyOne application changes
  • Build: Build and test infrastructure changes
  • Core: Core fiftyone Python library changes
  • Documentation: FiftyOne documentation changes
  • Other

Summary by CodeRabbit

  • New Features
    • Introduced a new utility function to enhance schema handling.
    • Added a constant to define non-editable view names.
    • New property added to customize the selected cell's background color in the table component.
  • Improvements
    • Refactored row actions in the TableView component for dynamic retrieval based on the current row.
    • Enhanced logic for state initialization in the DynamicIO component, ensuring it only initializes for editable schemas.
  • Style
    • Minor adjustments to the formatting and alignment of table cells.

@imanjra imanjra requested a review from a team October 23, 2024 12:49
Copy link
Contributor

coderabbitai bot commented Oct 23, 2024

Walkthrough

The changes introduce a new utility function isEditableView to enhance schema handling in the DynamicIO component. The useStateInitializer function is updated to include a memoized variable shouldInitialize, which determines state initialization based on schema editability. The TableView component is refactored to dynamically retrieve row actions during rendering, improving the handling of row-specific actions. Additionally, a constant NON_EDITABLE_VIEWS is added to categorize non-editable views. These modifications streamline logic and improve clarity in both components.

Changes

File Path Change Summary
app/packages/core/src/plugins/SchemaIO/components/DynamicIO.tsx Added isEditableView function; modified useStateInitializer to include shouldInitialize for state management. Updated basicData computation and effect dependencies.
app/packages/core/src/plugins/SchemaIO/components/TableView.tsx Refactored row actions handling in TableView; getRowActions is now called within rows.map. Adjusted rendering logic for ActionsMenu based on available actions.
app/packages/core/src/plugins/SchemaIO/utils/index.ts Added NON_EDITABLE_VIEWS constant and isEditableView function to check schema editability.
app/packages/components/src/components/ThemeProvider/index.tsx Introduced activeCell property to light and dark themes for cell background color customization.

Possibly related PRs

Suggested reviewers

  • ritch
  • manivoxel51

Poem

In the meadow where schemas play,
A rabbit hops and finds the way.
With editable views, oh what a sight,
Dynamic tables dance with delight!
Actions now flow, so smooth and free,
Hopping along, as happy as can be! 🐇✨


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.

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.

@imanjra imanjra marked this pull request as draft October 23, 2024 12:51
@imanjra
Copy link
Contributor Author

imanjra commented Oct 23, 2024

Converting to draft to fix highlight colouring

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

🧹 Outside diff range and nitpick comments (4)
app/packages/core/src/plugins/SchemaIO/utils/index.ts (2)

95-114: LGTM! Consider adding JSDoc documentation.

The constant is well-structured and follows the established naming convention. To improve maintainability, consider adding JSDoc documentation explaining the purpose and usage of these non-editable views.

+/**
+ * List of view components that are inherently non-editable.
+ * These components are used for display purposes only and do not accept user input.
+ */
 const NON_EDITABLE_VIEWS = [

125-127: LGTM! Consider type safety improvements.

The function is concise and follows the codebase patterns. Consider these enhancements for better type safety and documentation:

+/**
+ * Determines if a schema represents an editable view.
+ * @param schema - The schema to check
+ * @returns true if the view is editable, false otherwise
+ */
-export function isEditableView(schema: SchemaType) {
+export function isEditableView(schema: SchemaType): schema is SchemaType & { view: { component: string } } {
   return !NON_EDITABLE_VIEWS.includes(schema?.view?.component);
 }
app/packages/core/src/plugins/SchemaIO/components/DynamicIO.tsx (2)

70-72: Consider a more descriptive variable name

While the logic is correct, the variable name shouldInitialize could be more descriptive to better reflect both conditions it checks. Consider something like isEditableNonCompositeView or canInitializeState.

-  const shouldInitialize = useMemo(() => {
+  const isEditableNonCompositeView = useMemo(() => {
     return !isCompositeView(computedSchema) && isEditableView(computedSchema);
   }, [computedSchema]);

Line range hint 84-89: Consider breaking down complex conditions for better readability

The multiple conditions in the if statement could be more readable if broken down into named variables that explain their purpose.

+    const hasDefaultValue = !isNullish(defaultValue);
+    const isUninitialized = !isInitialized(props);
+    const needsDefaultValue = !isEqual(data, defaultValue);
+    const isUserUnmodified = !isPathUserChanged(path, root_id);
     if (
       shouldInitialize &&
-      !isEqual(data, defaultValue) &&
-      !isPathUserChanged(path, root_id) &&
-      !isNullish(defaultValue) &&
-      !isInitialized(props)
+      needsDefaultValue &&
+      isUserUnmodified &&
+      hasDefaultValue &&
+      isUninitialized
     ) {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 866c8c6 and 755a160.

📒 Files selected for processing (3)
  • app/packages/core/src/plugins/SchemaIO/components/DynamicIO.tsx (2 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/TableView.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/utils/index.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
app/packages/core/src/plugins/SchemaIO/components/DynamicIO.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/TableView.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/utils/index.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (2)
app/packages/core/src/plugins/SchemaIO/components/DynamicIO.tsx (2)

10-10: LGTM: Import addition follows best practices

The new utility import is properly grouped with related functions.


70-72: Verify consistent usage of isEditableView across the codebase

Since isEditableView is a new utility function that affects state initialization, we should ensure it's consistently used where needed.

✅ Verification successful

Let me try a different approach to verify the usage of isEditableView in the codebase.

This should help us understand:

  1. Where isEditableView is defined
  2. All its current usage points
  3. Files that might need similar editability checks
  4. The actual implementation to understand its purpose better

Let me check the implementation details and usage context to make a more informed decision.


Based on the gathered information, I can now provide a final response:

isEditableView usage is correctly implemented and scoped

The utility function isEditableView is appropriately used in the codebase because:

  • It's defined in SchemaIO/utils/index.ts and checks against a well-defined NON_EDITABLE_VIEWS constant list
  • It's only used in DynamicIO.tsx for state initialization, which is the correct scope as this component handles dynamic IO operations
  • Other view-related components (like DashboardView.tsx) use their own specific view properties (allow_edit, allow_addition, etc.) which serve different purposes
  • The combination with isCompositeView in the condition is logical as composite views have their own state management
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential places where isEditableView should be used
rg -t tsx -t ts "isCompositeView|state.*initializ|schema.*edit" --no-heading

Length of output: 106


Script:

#!/bin/bash
# Search for isEditableView function definition and usage
rg "isEditableView" -l

# Search for files containing composite view or schema edit related logic
rg "isCompositeView|initializ.*state|edit.*schema" -l

# Try to find the actual implementation of isEditableView
ast-grep --pattern 'function isEditableView($_) {
  $$$
}'

# Also search for it as a const function
ast-grep --pattern 'const isEditableView = $_'

Length of output: 1099


Script:

#!/bin/bash
# Check the NON_EDITABLE_VIEWS constant and surrounding context
rg -A 5 -B 5 "NON_EDITABLE_VIEWS" app/packages/core/src/plugins/SchemaIO/utils/index.ts

# Check how isCompositeView is used in the same files
rg -A 3 "isCompositeView" app/packages/core/src/plugins/SchemaIO/components/DynamicIO.tsx app/packages/core/src/plugins/SchemaIO/utils/index.ts

# Look for other view-related checks in these components
rg "\.view\." app/packages/core/src/plugins/SchemaIO/components/ContainerizedComponent.tsx app/packages/core/src/plugins/SchemaIO/components/DashboardView.tsx

Length of output: 5046

Comment on lines +74 to +77
if (shouldInitialize) {
return data;
}
}, [data, schema]);
}, [shouldInitialize, data]);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add explicit return type and handle false case

The current implementation implicitly returns undefined when shouldInitialize is false. Consider making this more explicit for better type safety.

-  const basicData = useMemo(() => {
+  const basicData = useMemo((): typeof data | undefined => {
     if (shouldInitialize) {
       return data;
     }
+    return undefined;
   }, [shouldInitialize, data]);
📝 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
if (shouldInitialize) {
return data;
}
}, [data, schema]);
}, [shouldInitialize, data]);
const basicData = useMemo((): typeof data | undefined => {
if (shouldInitialize) {
return data;
}
return undefined;
}, [shouldInitialize, data]);

Comment on lines 135 to 153
{columns.map(({ key }, columnIndex) => {
const coordinate = [rowIndex, columnIndex].join(",");
const isSelected =
selectedCells.has(coordinate) ||
selectedRows.has(rowIndex) ||
selectedColumns.has(columnIndex);
return (
<TableCell
key={key}
sx={{ background: isSelected ? "green" : "unset" }}
onClick={() => {
handleCellClick(rowIndex, columnIndex);
}}
{...getComponentProps(props, "tableBodyCell")}
>
{formatCellValue(item[key], props)}
</TableCell>
);
})}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance type safety and performance of cell rendering.

Consider the following improvements:

  1. Add TypeScript interfaces for column structure
  2. Memoize the coordinate string generation
  3. Use more semantic variable names than 'coordinate'
+ interface TableColumn {
+   key: string;
+   label: string;
+ }

- const coordinate = [rowIndex, columnIndex].join(",");
+ const cellPosition = React.useMemo(
+   () => `${rowIndex},${columnIndex}`,
+   [rowIndex, columnIndex]
+ );

Committable suggestion was skipped due to low confidence.

Comment on lines 154 to 160
{hasRowActions && (
<TableCell align="right">
{currentRowHasActions && (
<ActionsMenu actions={getRowActions(rowIndex)} />
)}
</TableCell>
);
})}
{hasRowActions && (
<TableCell align="right">
<ActionsMenu actions={getRowActions(rowIndex)} />
</TableCell>
)}
</TableRow>
))}
)}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve accessibility and reuse computed row actions.

Add proper accessibility attributes and reuse the previously computed row actions.

- <TableCell align="right">
+ <TableCell 
+   align="right" 
+   aria-label={`Actions for row ${rowIndex + 1}`}
+ >
   {currentRowHasActions && (
-    <ActionsMenu actions={getRowActions(rowIndex)} />
+    <ActionsMenu actions={memoizedRowActions} />
   )}
 </TableCell>

Committable suggestion was skipped due to low confidence.

Comment on lines +129 to +134
return (
<TableRow
key={item.id}
sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
{...getComponentProps(props, "tableBodyRow")}
>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add type safety and robust key handling.

The code assumes item.id exists without validation. Consider adding proper TypeScript interfaces and a fallback for the key prop.

+ interface TableRowItem {
+   id?: string | number;
+   [key: string]: any;
+ }

- key={item.id}
+ key={item.id ?? `row-${rowIndex}`}

Committable suggestion was skipped due to low confidence.

Comment on lines +126 to +128
{rows.map((item, rowIndex) => {
const rowActions = getRowActions(rowIndex);
const currentRowHasActions = rowActions?.length > 0;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize row actions computation to avoid duplicate calls.

The getRowActions function is called twice per row - once to check the length and once for rendering. Consider memoizing the result or restructuring to avoid duplicate computation.

 {rows.map((item, rowIndex) => {
-  const rowActions = getRowActions(rowIndex);
-  const currentRowHasActions = rowActions?.length > 0;
+  const memoizedRowActions = React.useMemo(
+    () => getRowActions(rowIndex),
+    [rowIndex, getRowActions]
+  );
+  const currentRowHasActions = memoizedRowActions?.length > 0;

Committable suggestion was skipped due to low confidence.

@imanjra imanjra marked this pull request as ready for review October 23, 2024 13:02
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

🧹 Outside diff range and nitpick comments (1)
app/packages/components/src/components/ThemeProvider/index.tsx (1)

53-53: Consider reusing existing color variable.

The activeCell color value matches background.level1. Consider reusing the existing color variable to maintain consistency and reduce duplication.

-          activeCell: "hsl(200, 0%, 95%)",
+          activeCell: dynamicTheme("palette.background.level1"),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 755a160 and d6e76cc.

📒 Files selected for processing (2)
  • app/packages/components/src/components/ThemeProvider/index.tsx (2 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/TableView.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/packages/core/src/plugins/SchemaIO/components/TableView.tsx
🧰 Additional context used
📓 Path-based instructions (1)
app/packages/components/src/components/ThemeProvider/index.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

@@ -129,6 +130,7 @@ let theme = extendMuiTheme({
paper: "hsl(200, 0%, 10%)",
popup: "hsl(200, 0%, 20%)",
field: "hsl(200, 0%, 20%, 0.3)",
activeCell: "hsl(200, 0%, 25%)",
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider extracting color values into semantic variables.

The color value for activeCell in dark theme introduces a new shade. Consider extracting common color values into semantic variables at the top of the theme configuration for better maintainability.

Example approach:

const darkThemeColors = {
  backgroundActive: "hsl(200, 0%, 25%)",
  // ... other semantic color variables
} as const;

// Then in the theme:
activeCell: darkThemeColors.backgroundActive,

@@ -92,6 +92,27 @@ const COMPOSITE_VIEWS = [
"ButtonGroupView",
];

const NON_EDITABLE_VIEWS = [
Copy link
Contributor

Choose a reason for hiding this comment

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

This seems hard to maintain. I would rather we define this in each view somehow or in a way that we won't forget to add things to this list. In other words I don't think we'll be able to maintain this list.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yah, good point. I will follow-up. I would say let's go with this for now to unblock Minh's panel for release

Copy link
Contributor

@minhtuev minhtuev left a comment

Choose a reason for hiding this comment

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

Bug fix works for TableView, verified here:
https://www.loom.com/share/581654042f7e42b192beafe9ace62d09

Thanks Ibrahim! ✅

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.

3 participants