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(ui): project variable support #692

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open

Conversation

KaWaite
Copy link
Member

@KaWaite KaWaite commented Dec 12, 2024

Overview

Project var (string) support with MOCK_DATA. Not hooked up to gql yet (waiting on that PR to be merged)

What I've done

What I haven't done

  • Support for multiple var types (array, number, etc)
  • Data persistence
  • Use inside of a node

How I tested

Screenshot

Which point I want you to review particularly

Memo

Copy link
Contributor

coderabbitai bot commented Dec 12, 2024

Walkthrough

This pull request introduces a comprehensive feature for managing project variables within the user interface. The changes include creating new React components for displaying and editing project variables, updating localization files across multiple languages, and defining type definitions for project variables. The implementation allows users to view, add, delete, and reorder project variables through a dialog interface, enhancing the project configuration capabilities of the application.

Changes

File Path Change Summary
ui/src/features/Editor/components/LeftPanel/... Added new components for Project Variables: ProjectVarDialog.tsx, ProjectVariable.tsx, updated index.tsx and LeftPanel/index.tsx
ui/src/lib/i18n/locales/*.json Added localization keys for project variables in English, Spanish, French, Japanese, and Chinese
ui/src/mock_data/projectVars.ts Created mock data for project variables
ui/src/types/index.ts Updated module exports
ui/src/types/projectVar.ts Added type definitions for project variables

Sequence Diagram

sequenceDiagram
    participant User
    participant LeftPanel
    participant ProjectVariables
    participant ProjectVarDialog
    
    User->>LeftPanel: Click "Project Variables" tab
    LeftPanel->>ProjectVariables: Render variables
    User->>ProjectVariables: Click "Edit" button
    ProjectVariables->>ProjectVarDialog: Open dialog
    User->>ProjectVarDialog: Add/Delete/Reorder variables
    User->>ProjectVarDialog: Click "Save"
    ProjectVarDialog->>ProjectVariables: Update variables
    ProjectVariables->>LeftPanel: Refresh display
Loading

Poem

🐰 Hop, hop, hooray! Project vars are here to play!
With dialogs bright and buttons light,
We'll manage variables day and night.
Add, delete, move with rabbit's might,
Our code now dances with pure delight! 🚀

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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.

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

netlify bot commented Dec 12, 2024

Deploy Preview for reearth-flow ready!

Name Link
🔨 Latest commit 72be679
🔍 Latest deploy log https://app.netlify.com/sites/reearth-flow/deploys/675a8267d7d8e20008f1dd8d
😎 Deploy Preview https://deploy-preview-692--reearth-flow.netlify.app
📱 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

netlify bot commented Dec 12, 2024

Deploy Preview for reearth-flow ready!

Name Link
🔨 Latest commit be8b7f3
🔍 Latest deploy log https://app.netlify.com/sites/reearth-flow/deploys/67620b4ae69fb6000866a1a9
😎 Deploy Preview https://deploy-preview-692--reearth-flow.netlify.app
📱 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.

@KaWaite KaWaite marked this pull request as ready for review December 17, 2024 23:38
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

🧹 Nitpick comments (8)
ui/src/features/Editor/components/LeftPanel/components/ProjectVariables/ProjectVarDialog.tsx (1)

159-161: Provide user feedback when removing whitespace from variable names

Currently, whitespace in variable names is automatically removed without user feedback, which might confuse users. Instead of silently modifying the input, consider preventing whitespace entry or displaying a validation message.

You could update the input to prevent whitespace characters:

 <Input
   value={variable.name}
   onClick={(e) => e.stopPropagation()}
   onChange={(e) => {
     setProjectVariables((pvs) => {
       const newPvs = [...pvs];
-      const newValue = e.target.value;
-      newPvs[idx].name = newValue.split(/\s+/).join("");
+      const newValue = e.target.value.replace(/\s/g, "");
+      newPvs[idx].name = newValue;
       return newPvs;
     });
   }}
 />

And optionally, inform the user that whitespace is not allowed in variable names.

ui/src/types/projectVar.ts (1)

12-13: Specify a stricter type for definition and address the TODO

Currently, definition is typed as any, which can lead to type safety issues. Consider defining definition based on VarType to enhance type safety. Additionally, there's a TODO to use ParameterType; implementing this would improve consistency.

Would you like assistance in defining ParameterType and updating the ProjectVar type accordingly?

ui/src/features/Editor/components/LeftPanel/components/ProjectVariables/ProjectVariable.tsx (1)

10-15: Add accessibility improvements

The component lacks proper accessibility attributes for better screen reader support.

-    <div className={`flex items-center rounded p-1 ${className}`}>
+    <div 
+      className={`flex items-center rounded p-1 ${className}`}
+      role="listitem"
+      aria-label={`Project variable ${variable.name}`}>
       <p className="flex-1 truncate text-sm">{variable.name}</p>
       <p className="flex-1 truncate text-sm dark:font-extralight">
         {JSON.stringify(variable.definition)}
       </p>
     </div>
ui/src/mock_data/projectVars.ts (1)

5-8: Improve mock data quality and readability

The mock data contains unnecessarily long values and random-looking IDs which reduce readability and maintainability.

-    id: "asdfasfsdasdffsdf",
-    name: "project_name",
-    definition: "My Projectjlasjdflakjsdflkjsadflkjasdflkjasdlkjafsdlk",
+    id: "project_name_001",
+    name: "project_name",
+    definition: "Sample Project",
ui/src/features/Editor/components/LeftPanel/components/ProjectVariables/index.tsx (2)

15-17: Plan GraphQL implementation

The TODO comment indicates missing GraphQL integration. This should be tracked and implemented to replace the mock data.

Would you like me to help create a GitHub issue to track the GraphQL implementation task? I can provide a template with the necessary requirements and implementation steps.


27-64: Add loading state handling

The component should handle loading states when fetching project variables (future GraphQL implementation).

 const ProjectVariables: React.FC = () => {
   const t = useT();
   const [isOpen, setIsOpen] = useState(false);
+  const [isLoading, setIsLoading] = useState(false);

   // TODO: get project variables from gql
   const [currentProjectVars, setCurrentProjectVars] =
     useState<ProjectVar[]>(MOCK_DATA);

   // ... existing code ...

   return (
     <>
       <div className="flex h-full flex-col gap-4 p-1">
         <div className="flex-1">
           <div className="flex items-center pb-2">
             <p className="flex-1 text-sm font-thin">{t("Key")}</p>
             <p className="flex-1 text-sm font-thin">{t("Value")}</p>
           </div>
           <ScrollArea>
+            {isLoading ? (
+              <div className="flex justify-center p-4">
+                <LoadingSpinner />
+              </div>
+            ) : (
             <div className="flex flex-col gap-1 overflow-y-auto">
               {currentProjectVars.map((variable, idx) => (
                 <ProjectVariable
                   key={variable.id}
                   className={`${idx % 2 !== 0 ? "bg-card" : "bg-primary"}`}
                   variable={variable}
                 />
               ))}
             </div>
+            )}
           </ScrollArea>
         </div>
ui/src/features/Editor/components/LeftPanel/index.tsx (1)

99-115: Consider the tab ordering logic.

While the implementation is correct, consider if the current tab order (project-vars → resources → actions-list) provides the most intuitive user experience. Common patterns typically group similar functionality together.

A potential alternative order could be:

  • navigator (current first)
  • actions-list (related to canvas actions)
  • resources (project resources)
  • project-vars (project configuration)
ui/src/lib/i18n/locales/es.json (1)

21-24: Consider using more technical terminology for "Key" in Spanish.

While the translations are generally good, consider using "Llave" instead of "Clave" for "Key" as it's more commonly used in programming contexts in Spanish.

Current translations:

  • "Key" → "Clave" (consider: "Llave")
  • "Value" → "Valor"
  • "Project Variables" → "Variables del proyecto"
  • "Edit Project Variables" → "Editar variables del proyecto"
  • "Resources" → "Recursos"

Also applies to: 27-28

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ed959cf and be8b7f3.

📒 Files selected for processing (13)
  • ui/src/features/Editor/components/LeftPanel/components/ProjectVariables/ProjectVarDialog.tsx (1 hunks)
  • ui/src/features/Editor/components/LeftPanel/components/ProjectVariables/ProjectVariable.tsx (1 hunks)
  • ui/src/features/Editor/components/LeftPanel/components/ProjectVariables/index.tsx (1 hunks)
  • ui/src/features/Editor/components/LeftPanel/components/index.ts (1 hunks)
  • ui/src/features/Editor/components/LeftPanel/index.tsx (4 hunks)
  • ui/src/lib/i18n/locales/en.json (1 hunks)
  • ui/src/lib/i18n/locales/es.json (1 hunks)
  • ui/src/lib/i18n/locales/fr.json (1 hunks)
  • ui/src/lib/i18n/locales/ja.json (1 hunks)
  • ui/src/lib/i18n/locales/zh.json (1 hunks)
  • ui/src/mock_data/projectVars.ts (1 hunks)
  • ui/src/types/index.ts (1 hunks)
  • ui/src/types/projectVar.ts (1 hunks)
🔇 Additional comments (9)
ui/src/features/Editor/components/LeftPanel/components/index.ts (1)

3-3: LGTM!

The export statement correctly includes the ProjectVariables component.

ui/src/types/index.ts (1)

10-10: LGTM!

The export statement correctly adds projectVar types to the exports.

ui/src/mock_data/projectVars.ts (1)

32-37: Consider implementing object type support

The commented-out object type configuration suggests incomplete feature implementation. If object type support is planned, it should be properly implemented or removed to avoid confusion.

Let's check if object type is supported in the codebase:

ui/src/features/Editor/components/LeftPanel/components/ProjectVariables/index.tsx (1)

22-25: 🛠️ Refactor suggestion

Add error handling for state updates

The handleSubmit function lacks error handling for the state update operation.

   const handleSubmit = (newProjectVars: ProjectVar[]) => {
+    try {
       setCurrentProjectVars(newProjectVars);
       handleDialogClose();
+    } catch (error) {
+      console.error('Failed to update project variables:', error);
+      // TODO: Add error notification
+    }
   };

Likely invalid or redundant comment.

ui/src/features/Editor/components/LeftPanel/index.tsx (2)

2-2: LGTM: Clean import additions and type definition.

The new imports and type extension for project variables support are well-organized and follow the existing pattern.

Also applies to: 19-19, 21-21


160-160: LGTM: Improved layout structure.

The flex layout modifications and overflow handling enhance the panel's responsiveness and scrolling behavior.

Also applies to: 167-167

ui/src/lib/i18n/locales/zh.json (1)

21-28: LGTM: Complete and accurate Chinese translations.

All new keys have appropriate Chinese translations that are semantically correct and maintain consistency with the existing translations.

ui/src/lib/i18n/locales/ja.json (1)

21-24: LGTM! Japanese translations are accurate and natural.

The translations for project variables feature are well-implemented with appropriate Japanese terminology:

  • "Key" → "キー"
  • "Value" → "値"
  • "Project Variables" → "プロジェクト変数"
  • "Edit Project Variables" → "プロジェクト変数を編集"
  • "Resources" → "リソース"

Also applies to: 27-28

ui/src/lib/i18n/locales/fr.json (1)

21-24: LGTM! French translations are accurate and consistent.

The translations for project variables feature are well-implemented with appropriate French terminology:

  • "Key" → "Clé"
  • "Value" → "Valeur"
  • "Project Variables" → "Variables du projet"
  • "Edit Project Variables" → "Modifier les variables du projet"
  • "Resources" → "Ressources"

Also applies to: 27-28

Comment on lines +42 to +43
const [projectVariables, setProjectVariables] =
useState<ProjectVar[]>(currentProjectVars);
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

Ensure projectVariables state updates when currentProjectVars prop changes

Currently, if the currentProjectVars prop changes, the projectVariables state won't update because useState doesn't synchronize with prop changes after the initial render. To keep projectVariables in sync with currentProjectVars, consider adding a useEffect hook.

Apply this diff to fix the issue:

+import { useState, useEffect } from "react";
 
 const [projectVariables, setProjectVariables] =
   useState<ProjectVar[]>(currentProjectVars);

+useEffect(() => {
+  setProjectVariables(currentProjectVars);
+}, [currentProjectVars]);

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

Comment on lines +118 to +119
const handleSubmit = () => onSubmit(projectVariables);

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 validation before submitting project variables

Currently, there is no validation to ensure that each project variable has a non-empty name. Submitting variables with empty names might cause issues downstream. Consider adding validation to check for empty names and prevent submission if validation fails.

You can update the handleSubmit function to include validation:

 const handleSubmit = () => {
+  const isValid = projectVariables.every(
+    (variable) => variable.name.trim() !== ""
+  );
+  if (!isValid) {
+    // Optionally, show an error message to the user.
+    return;
+  }
   onSubmit(projectVariables);
 };

Additionally, you might want to disable the "Save" button when validation fails.

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

Comment on lines +12 to +14
<p className="flex-1 truncate text-sm dark:font-extralight">
{JSON.stringify(variable.definition)}
</p>
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

Improve the display format of variable definitions

The direct use of JSON.stringify for displaying the variable definition might lead to poor readability, especially for complex types. Consider implementing a more user-friendly format display.

-      <p className="flex-1 truncate text-sm dark:font-extralight">
-        {JSON.stringify(variable.definition)}
-      </p>
+      <p className="flex-1 truncate text-sm dark:font-extralight">
+        {formatDefinition(variable.definition, variable.type)}
+      </p>

Consider adding a helper function like:

const formatDefinition = (definition: any, type: string) => {
  switch (type) {
    case "array":
      return Array.isArray(definition) ? definition.join(", ") : String(definition);
    case "boolean":
      return definition ? "true" : "false";
    default:
      return String(definition);
  }
};

Comment on lines +37 to +43
{currentProjectVars.map((variable, idx) => (
<ProjectVariable
key={variable.name + idx}
className={`${idx % 2 !== 0 ? "bg-card" : "bg-primary"}`}
variable={variable}
/>
))}
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

Fix potential key uniqueness issue

Using array index in combination with variable name as key could lead to issues if variables with the same name exist at different indices.

-                <ProjectVariable
-                  key={variable.name + idx}
-                  className={`${idx % 2 !== 0 ? "bg-card" : "bg-primary"}`}
-                  variable={variable}
-                />
+                <ProjectVariable
+                  key={variable.id}
+                  className={`${idx % 2 !== 0 ? "bg-card" : "bg-primary"}`}
+                  variable={variable}
+                />

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

Comment on lines +21 to +28
"Key": "",
"Value": "",
"Edit Project Variables": "",
"Save": "Save",
"Transformers": "Transformers",
"Canvas Navigation": "Canvas Navigation",
"Project Variables": "",
"Resources": "",
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 missing translations for new keys.

Several new keys have empty string values:

  • "Key"
  • "Value"
  • "Edit Project Variables"
  • "Project Variables"
  • "Resources"

These should be populated with appropriate English translations to ensure proper UI text display.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant