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

1.18 ports7 #7221

Merged
merged 8 commits into from
Nov 22, 2024
Merged

1.18 ports7 #7221

merged 8 commits into from
Nov 22, 2024

Conversation

arkadius
Copy link
Member

@arkadius arkadius commented Nov 22, 2024

Describe your changes

Checklist before merge

  • Related issue ID is placed at the beginning of PR title in [brackets] (can be GH issue or Nu Jira issue)
  • Code is cleaned from temporary changes and commented out lines
  • Parts of the code that are not easy to understand are documented in the code
  • Changes are covered by automated tests
  • Showcase in dev-application.conf added to demonstrate the feature
  • Documentation added or updated
  • Added entry in Changelog.md describing the change from the perspective of a public distribution user
  • Added MigrationGuide.md entry in the appropriate subcategory if introducing a breaking change
  • Verify that PR will be squashed during merge

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced validation feedback with loading indicators in the editor components.
    • Introduced a custom hook for managing Enter key actions based on specific conditions.
  • Improvements

    • Updated components to allow for richer content rendering by accepting complex React elements.
    • Improved loading indicators and user interactions in the ScenarioLabels and UserDefinedListInput components.
  • Documentation

    • Updated changelog and migration guide to reflect recent changes and enhancements.
    • Clarified content in the SpEL documentation for better readability and understanding.

arkadius and others added 8 commits November 22, 2024 11:54
Revert to shorter tooltip for labels
… enter until validation finish (#7215)

* NU-1888 change typing text to spinner and provide delayed adding on enter

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Dzuming <[email protected]>
Copy link

coderabbitai bot commented Nov 22, 2024

📝 Walkthrough

Walkthrough

The pull request introduces several modifications across various components in the Nussknacker application, primarily focusing on enhancing type flexibility and improving user interaction. The EditableEditor component's validationLabelInfo property type has been updated from string to ReactNode, allowing for more complex React elements. This change is reflected in the Editor component, where the expressionInfo property is similarly updated.

Additionally, the UserDefinedListInput component has been enhanced to utilize a useRef hook for managing the AceEditor instance and incorporates a CircularProgress component to indicate loading states during user input. The ScenarioLabels component also sees improvements with the addition of a loading indicator and optimizations through the useCallback hook. A new custom hook, useDelayedEnterAction, has been introduced to manage actions triggered by the Enter key based on specific conditions.

Overall, these changes reflect a concerted effort to improve the handling of validation information, user feedback during input, and the overall structure and type definitions within the components.

Possibly related PRs

  • [NU-1836] Add casting and conversions docs #7124: The changes in the main PR regarding the validationLabelInfo prop type update from string to ReactNode are related to the changes in the Editor.ts file where the expressionInfo prop type is also updated from string to ReactNode, indicating a consistent approach to handling validation information across components.

  • Fix scenario tests with fragment input validation #7159: The modifications in the main PR that enhance the EditableEditor component's handling of validation information are relevant to the changes in the Editor.ts file, where the expressionInfo prop is similarly updated to allow for more complex React elements, suggesting a direct relationship in how validation information is processed in both components.

  • [NU-1800] Add TemplateEvaluationResult to evaluate SpEL expression parts in LazyParameter #7162: The changes in the main PR that involve the EditableEditor and Editor components are related to the introduction of the useDelayedEnterAction hook in the UserDefinedListInput.tsx, which also aims to improve user interaction and validation handling, indicating a broader effort to enhance input handling across components.

  • Template parts handling approach change: expression level instead of LazyParameter level #7174: The main PR's updates to the EditableEditor and Editor components to support more complex validation information are connected to the changes in the TemplateEvaluationResult class, which is introduced in the context of rendering templates and validation, highlighting a cohesive approach to managing validation across the application.

  • [NU-1888] change typing text to spinner and provide delayed adding on enter until validation finish #7215: The changes in the main PR that modify the validationLabelInfo prop to support ReactNode are relevant to the updates in the EditableEditor and Editor components, which also focus on enhancing the rendering of validation information, indicating a consistent strategy for validation across different components.

  • [NU-1836] Adjust SpeL conversion docs #7216: The adjustments made in the main PR to improve the handling of validation information in the EditableEditor component are related to the documentation changes in Spel.md, which clarify the conversion processes and types, ensuring that users understand how to effectively utilize these components in conjunction with SpEL.

Suggested labels

docs, ui, client


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.

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

🧹 Outside diff range and nitpick comments (10)
designer/client/src/components/toolbars/scenarioDetails/useDelayedEnterAction.tsx (2)

3-7: Add JSDoc documentation to the Props interface.

Adding documentation would improve code maintainability and help other developers understand the purpose of each prop.

+/**
+ * Props for the useDelayedEnterAction hook
+ */
 interface Props {
+    /** Indicates if the user is currently typing */
     inputTyping: boolean;
+    /** Number of validation errors */
     errorsLength: number;
+    /** Callback function to execute when conditions are met */
     action: () => void;
 }

9-9: Consider renaming the hook for better clarity.

The current name useDelayedEnterAction suggests it specifically handles Enter key actions, but it's actually a generic conditional action hook. Consider renaming it to better reflect its purpose, such as useConditionalAction or useValidatedAction.

designer/client/src/components/graph/node-modal/editors/EditableEditor.tsx (1)

Line range hint 31-49: Consider memoizing Editor component selection

The Editor component selection logic could benefit from memoization to prevent unnecessary recalculations.

Consider this optimization:

-const editorType = useMemo(() => (isEmpty(param) ? EditorType.RAW_PARAMETER_EDITOR : param.editor.type), [param]);
-
-const Editor: SimpleEditor | ExtendedEditor = useMemo(() => editors[editorType], [editorType]);

+const Editor: SimpleEditor | ExtendedEditor = useMemo(() => {
+    const type = isEmpty(param) ? EditorType.RAW_PARAMETER_EDITOR : param.editor.type;
+    return editors[type];
+}, [param]);
designer/client/src/components/graph/node-modal/fragment-input-definition/settings/variants/fields/UserDefinedListInput.tsx (2)

Line range hint 104-143: Consider extracting validation logic.

The handleAddNewListItem function handles multiple responsibilities: enter key state, validation checks, and list updates. Consider extracting the validation logic into a separate function for better maintainability.

+const validateNewListItem = (temporaryListItem: string, fixedValuesList: FixedValuesOption[]): NodeValidationError[] => {
+    const errors: NodeValidationError[] = [];
+    if (!mandatoryValueValidator.isValid(temporaryListItem)) {
+        errors.push({
+            errorType: "SaveAllowed",
+            fieldName: temporaryItemName,
+            typ: temporaryListItemTyp.refClazzName,
+            description: mandatoryValueValidator.description(),
+            message: mandatoryValueValidator.message(),
+        });
+    }
+    
+    const isUniqueValueValidator = uniqueValueValidator(fixedValuesList.map(item => item.label));
+    if (!isUniqueValueValidator.isValid(temporaryListItem)) {
+        errors.push({
+            errorType: "SaveAllowed",
+            fieldName: temporaryItemName,
+            typ: temporaryListItemTyp.refClazzName,
+            description: isUniqueValueValidator.description(),
+            message: isUniqueValueValidator.message(),
+        });
+    }
+    return errors;
+};

 const handleAddNewListItem = () => {
     if (temporaryValuesTyping) {
         setIsEnterPressed(true);
         return;
     }

-    const isUniqueValueValidator = uniqueValueValidator(fixedValuesList.map((fixedValuesList) => fixedValuesList.label));
-
-    if (!mandatoryValueValidator.isValid(temporaryListItem)) {
-        setTemporaryValueErrors((prevState) => [
-            ...prevState,
-            {
-                errorType: "SaveAllowed",
-                fieldName: temporaryItemName,
-                typ: temporaryListItemTyp.refClazzName,
-                description: mandatoryValueValidator.description(),
-                message: mandatoryValueValidator.message(),
-            },
-        ]);
-        return;
-    }
-
-    if (!isUniqueValueValidator.isValid(temporaryListItem)) {
-        setTemporaryValueErrors((prevState) => [
-            ...prevState,
-            {
-                errorType: "SaveAllowed",
-                fieldName: temporaryItemName,
-                typ: temporaryListItemTyp.refClazzName,
-                description: isUniqueValueValidator.description(),
-                message: isUniqueValueValidator.message(),
-            },
-        ]);
-        return;
-    }
+    const validationErrors = validateNewListItem(temporaryListItem, fixedValuesList);
+    if (validationErrors.length > 0) {
+        setTemporaryValueErrors(validationErrors);
+        return;
+    }

     if (temporaryValueErrors.length === 0) {
         const updatedList = [...fixedValuesList, { expression: temporaryListItem, label: temporaryListItem }];
         handleChangeFixedValuesList(updatedList);
         setTemporaryListItem("");
     }
 };

191-205: Consider adding error handling for editor initialization.

The editor setup looks good, but consider adding error handling for cases where the editor initialization fails.

 ref={(ref: AceEditor | null) => {
+    try {
         if (ref?.editor) {
             editorRef.current = ref.editor;
             ref.editor.commands.addCommand(aceEditorEnterCommand);
         }
+    } catch (error) {
+        console.error('Failed to initialize editor:', error);
+    }
 }}
designer/client/src/components/toolbars/scenarioDetails/ScenarioLabels.tsx (1)

225-238: Consider simplifying keyboard event simulation

The current implementation creates and dispatches a synthetic keyboard event, which is a complex approach that might be fragile across different browsers.

Consider simplifying this by directly calling the Autocomplete's internal methods or using MUI's API:

-    const { setIsEnterPressed } = useDelayedEnterAction({
-        action: () => {
-            const enterEvent = new KeyboardEvent("keydown", {
-                key: "Enter",
-                keyCode: 13,
-                code: "Enter",
-                bubbles: true,
-                cancelable: true,
-            });
-            autocompleteRef.current.dispatchEvent(enterEvent);
-        },
-        errorsLength: inputErrors.length,
-        inputTyping,
-    });
+    const { setIsEnterPressed } = useDelayedEnterAction({
+        action: () => {
+            // Use MUI's Autocomplete ref methods directly
+            if (autocompleteRef.current) {
+                const api = autocompleteRef.current;
+                api.blur(); // or other appropriate method
+            }
+        },
+        errorsLength: inputErrors.length,
+        inputTyping,
+    });
docs/scenarios_authoring/Spel.md (1)

Line range hint 271-307: Consider adding error handling examples.

While the conversion documentation is comprehensive, it would be helpful to include examples of how errors are handled in each case, especially for the to prefix which propagates exceptions.

Consider adding examples like:

 | `'abc'.toDoubleOrNull`                                                   | null                        | Double            |
+| `'abc'.toDouble`                                                         | NumberFormatException       | -                 |
+| `'123.45'.to('Integer')`                                                | NumberFormatException       | -                 |
 | `'123'.canBe('Double')`                                                  | true                        | Boolean           |
docs/MigrationGuide.md (3)

13-13: Consider adding release date for version 1.19.0

For better tracking and clarity, consider adding the expected release date or marking it as "Upcoming" for version 1.19.0.


Line range hint 13-19: Breaking change warning needed for Kafka state restoration

The breaking change regarding Kafka source/sink components and state restoration should be highlighted more prominently, perhaps with a warning box or bold text, as this could significantly impact production systems.

### ⚠️ Breaking Changes

* We lost support for old ConsumerRecord constructor supported by Flink 1.14 / 1.15 
* If you used Kafka source/sink components in your scenarios then state of these scenarios won't be restored

Line range hint 1-11: Add table of contents for better navigation

For a long migration guide like this, consider adding a table of contents at the beginning to help users quickly find relevant sections.

# Migration guide

## Table of Contents
- [Version 1.19.0](#in-version-1190-not-released-yet)
- [Version 1.18.0](#in-version-1180)
- [Version 1.17.0](#in-version-1170)
...

To see the biggest differences please consult the [changelog](Changelog.md).
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5e5bf70 and 80fe7a9.

⛔ Files ignored due to path filters (1)
  • designer/client/cypress/e2e/__image_snapshots__/electron/Linux/Fragment should allow adding input parameters and display used fragment graph in modal #1.png is excluded by !**/*.png
📒 Files selected for processing (9)
  • designer/client/src/components/graph/node-modal/editors/EditableEditor.tsx (2 hunks)
  • designer/client/src/components/graph/node-modal/editors/expression/Editor.ts (2 hunks)
  • designer/client/src/components/graph/node-modal/fragment-input-definition/settings/variants/fields/UserDefinedListInput.tsx (5 hunks)
  • designer/client/src/components/toolbars/scenarioDetails/ScenarioLabels.tsx (9 hunks)
  • designer/client/src/components/toolbars/scenarioDetails/useDelayedEnterAction.tsx (1 hunks)
  • designer/submodules/packages/components/src/common/labelChip.tsx (1 hunks)
  • docs/Changelog.md (2 hunks)
  • docs/MigrationGuide.md (1 hunks)
  • docs/scenarios_authoring/Spel.md (3 hunks)
🔇 Additional comments (19)
designer/client/src/components/toolbars/scenarioDetails/useDelayedEnterAction.tsx (1)

12-17: Verify the action execution timing.

The current implementation might execute the action multiple times if the dependencies change rapidly. Consider implementing debouncing to prevent this.

designer/submodules/packages/components/src/common/labelChip.tsx (2)

31-31: Consider UX impact of simplified tooltip

The change from a dynamic tooltip that showed the full label value to a static "Label" text might reduce user experience, especially for:

  • Users relying on tooltips for additional context
  • Screen reader users who benefit from more descriptive tooltips
  • Cases where the label text is truncated and tooltip provided the full text

Let's check if this change is consistent with other similar components:

Consider one of these alternatives:

-            title={t("scenariosList.tooltip.label", "Label")}
+            title={t("scenariosList.tooltip.label", "Scenario label: {{label}}", { label: value })}

or at minimum:

-            title={t("scenariosList.tooltip.label", "Label")}
+            title={value}

Line range hint 31-38: Verify accessibility compliance

The component uses good accessibility practices with:

  • Proper tabIndex
  • Click handling
  • Visual feedback through color changes

However, the simplified tooltip might not provide sufficient context for screen readers.

Let's check other accessibility attributes in similar components:

Consider adding explicit aria attributes:

             title={t("scenariosList.tooltip.label", "Label")}
             key={id}
             color={isSelected ? "primary" : "default"}
             size="small"
             variant={"outlined"}
             label={value}
+            aria-label={`${t("scenariosList.tooltip.label", "Label")}: ${value}`}
             tabIndex={0}
             onClick={onClick}
designer/client/src/components/graph/node-modal/editors/EditableEditor.tsx (2)

2-2: LGTM: Import change aligns with the type update.

The addition of ReactNode to the React import is necessary to support the Props interface change.


27-27: ⚠️ Potential issue

Document this breaking change in MigrationGuide.md

Changing validationLabelInfo from string to ReactNode is a breaking change that affects the component's public API. While this change enables more flexible validation label rendering (e.g., progress indicators, rich text), it requires documentation to help users migrate.

Let's verify if this breaking change is documented:

Please ensure you:

  1. Document this change in MigrationGuide.md
  2. Update any string literals being passed to validationLabelInfo
  3. Update the PR checklist to confirm these steps are completed
designer/client/src/components/graph/node-modal/editors/expression/Editor.ts (2)

7-7: LGTM!

The import statement follows TypeScript best practices by explicitly importing the required type.


30-30: Breaking change detected: Document migration steps

Changing expressionInfo from string to ReactNode is a breaking change that allows for richer content rendering. This change requires documentation in the migration guide.

Let's verify the impact:

Please ensure you:

  1. Add an entry to MigrationGuide.md explaining how to migrate string-based expressionInfo to ReactNode
  2. Update relevant documentation
  3. Review and update unit tests to cover ReactNode scenarios
designer/client/src/components/graph/node-modal/fragment-input-definition/settings/variants/fields/UserDefinedListInput.tsx (3)

6-6: LGTM: Import changes and constant definition are well-organized.

The new imports and constant definition are properly structured and necessary for the added functionality.

Also applies to: 18-21, 22-22


188-190: LGTM: Well-implemented loading indicator.

The loading indicator provides good user feedback during typing and follows Material-UI's theming conventions.


49-49: Verify editor command registration.

The delayed enter action executes the ENTER_VALUE_COMMAND on the editor. Ensure that this command is properly registered before it's executed.

Also applies to: 91-97

✅ Verification successful

Let me check the command registration implementation to ensure it's properly set up.


Editor command is properly registered and used

The command is well-implemented:

  • Command constant ENTER_VALUE_COMMAND is defined and consistently used
  • Command registration is done with proper binding to Enter key
  • Command execution is correctly set up to handle new list items
  • The same command name is used in both registration and execution
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all places where editor commands are registered
rg -A 2 "commands\.addCommand" 

Length of output: 937


Script:

#!/bin/bash
# Search for the command definition and its usage
ast-grep --pattern 'const aceEditorEnterCommand = {
  $$$
}'

# Also check for any ENTER_VALUE_COMMAND constant definition
rg "ENTER_VALUE_COMMAND"

Length of output: 1850

designer/client/src/components/toolbars/scenarioDetails/ScenarioLabels.tsx (3)

8-8: LGTM: Import additions enhance component capabilities

The new imports support improved loading states and keyboard interactions:

  • CircularProgress provides better visual feedback
  • useRef enables DOM manipulation for keyboard events
  • useDelayedEnterAction custom hook manages Enter key interactions

Also applies to: 19-19, 26-26


291-291: LGTM: Enhanced user feedback and i18n support

Good improvements:

  • Loading indicator provides better visual feedback
  • Label tooltip properly uses translation key

Also applies to: 377-377


321-321: Ensure comprehensive test coverage for error handling

The error handling logic is complex, covering multiple scenarios:

  • Input validation states
  • Duplicate label detection
  • Loading states
  • Keyboard interaction during errors

Let's verify the test coverage:

Would you like me to help generate additional test cases for these error handling scenarios?

Also applies to: 353-353

docs/scenarios_authoring/Spel.md (3)

271-275: LGTM! Clear introduction to type conversions.

The changes provide a clear and structured introduction to type conversions, properly distinguishing between implicit and explicit conversions. The addition of utility classes alongside built-in functions enhances completeness.


290-293: LGTM! Well-structured explanation of conversion functions.

The explanation of the different conversion function prefixes (canBe, to, toOrNull) is clear and precise. Each prefix's behavior is well-documented, helping users understand when to use each variant.


307-307: LGTM! Good example of LocalDateTime conversion.

The added example demonstrates LocalDateTime string parsing, which is a common use case. It complements the existing examples well.

docs/Changelog.md (2)

37-37: LGTM: Version release date added.

The version date has been properly updated to indicate the official release date.


127-127: LGTM: New changelog entry for UI improvement.

The new entry properly documents a UI enhancement that improves user feedback during validation by replacing static text with a spinner and handling delayed additions until validation completes.

docs/MigrationGuide.md (1)

Line range hint 21-186: LGTM: Version 1.18.0 section is well documented

The version 1.18.0 section is comprehensive and well-structured, covering:

  • Configuration changes
  • Code API changes
  • REST API changes
  • Other changes

The migration steps are clear and include code examples where needed.

Comment on lines +9 to +20
export const useDelayedEnterAction = ({ inputTyping, errorsLength, action }: Props) => {
const [isEnterPressed, setIsEnterPressed] = useState(false);

useEffect(() => {
if (isEnterPressed && !inputTyping && errorsLength === 0) {
action();
setIsEnterPressed(false);
}
}, [errorsLength, inputTyping, isEnterPressed, action]);

return { setIsEnterPressed };
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling and cleanup.

The current implementation could be improved in several ways:

  1. Add error handling around the action execution
  2. Include a cleanup function in useEffect
  3. Consider debouncing to prevent rapid repeated executions

Here's a suggested implementation:

 export const useDelayedEnterAction = ({ inputTyping, errorsLength, action }: Props) => {
     const [isEnterPressed, setIsEnterPressed] = useState(false);
 
     useEffect(() => {
+        let mounted = true;
         if (isEnterPressed && !inputTyping && errorsLength === 0) {
-            action();
-            setIsEnterPressed(false);
+            try {
+                Promise.resolve(action()).then(() => {
+                    if (mounted) {
+                        setIsEnterPressed(false);
+                    }
+                });
+            } catch (error) {
+                console.error('Error executing delayed action:', error);
+                if (mounted) {
+                    setIsEnterPressed(false);
+                }
+            }
         }
+        return () => {
+            mounted = false;
+        };
     }, [errorsLength, inputTyping, isEnterPressed, action]);
 
     return { setIsEnterPressed };
 };

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

Copy link
Contributor

created: #7222
⚠️ Be careful! Snapshot changes are not necessarily the cause of the error. Check the logs.

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.

3 participants