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

refactor: Make useBpmnEditor return callback ref #14423

Merged
merged 2 commits into from
Jan 15, 2025

Conversation

TomasEng
Copy link
Contributor

@TomasEng TomasEng commented Jan 15, 2025

Description

Made the useBpmnEditor return a callback ref. This will make it easier to trigger initialization and cleanup functions.

Related Issue

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)

Summary by CodeRabbit

  • Refactor

    • Updated the useBpmnEditor hook implementation to use a callback-based approach for canvas reference management
    • Simplified test setup for useBpmnEditor hook
    • Streamlined context handling in test files
  • Tests

    • Improved type safety and organization of test cases for BPMN editor components

Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

📝 Walkthrough

Walkthrough

The pull request involves modifications to the BPMN (Business Process Model and Notation) editor implementation across multiple files. The changes primarily focus on refactoring the useBpmnEditor hook, updating its type signature, and changing how the canvas reference is managed. The modifications simplify the hook's interface, moving from a ref-based approach to a callback-based implementation. The test files have also been updated to accommodate these changes, with adjustments to the mock implementations and test setup.

Changes

File Change Summary
frontend/packages/process-editor/src/hooks/useBpmnEditor.ts - Updated type signature from UseBpmnViewerResult to UseBpmnEditorResult
- Transformed canvasRef to a callback function
- Removed useEffect logging
frontend/packages/process-editor/src/components/Canvas/BPMNEditor/BPMNEditor.tsx - Simplified canvasRef assignment from useBpmnEditor()
- Updated div element to self-closing tag
frontend/packages/process-editor/src/components/Canvas/BPMNEditor/BPMNEditor.test.tsx - Modified mock implementation of useBpmnEditor hook
frontend/packages/process-editor/src/hooks/useBpmnEditor.test.tsx - Removed useBpmnContext import
- Simplified context setup
- Updated test function signatures
- Added new setup function

Suggested labels

area/ui-editor

Suggested reviewers

  • Konrad-Simso
  • ErlingHauan

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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.

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.

@github-actions github-actions bot added area/process Area: Related to app process (e.g. signing, receipt, fill inn, payment, etc). solution/studio/designer Issues related to the Altinn Studio Designer solution. frontend labels Jan 15, 2025
@TomasEng TomasEng added skip-releasenotes Issues that do not make sense to list in our release notes skip-manual-testing PRs that do not need to be tested manually skip-documentation Issues where updating documentation is not relevant labels Jan 15, 2025
@TomasEng TomasEng added quality/code Violations from current rules for code, best practices, etc. Or just bad code. team/studio-domain1 team/studio-core labels Jan 15, 2025
@TomasEng TomasEng force-pushed the make-usebpmneditor-return-callback-ref branch from d24abce to 31c7831 Compare January 15, 2025 08:21
Copy link

codecov bot commented Jan 15, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.66%. Comparing base (15bd10a) to head (53783ba).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14423      +/-   ##
==========================================
- Coverage   95.66%   95.66%   -0.01%     
==========================================
  Files        1880     1880              
  Lines       24447    24445       -2     
  Branches     2810     2810              
==========================================
- Hits        23387    23385       -2     
  Misses        800      800              
  Partials      260      260              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@TomasEng TomasEng force-pushed the make-usebpmneditor-return-callback-ref branch from 31c7831 to c31432e Compare January 15, 2025 09:35
@TomasEng TomasEng marked this pull request as ready for review January 15, 2025 10:24
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 comments (1)
frontend/packages/process-editor/src/hooks/useBpmnEditor.ts (1)

The review suggestion is correct and should be implemented

The BpmnModelerInstance singleton requires proper cleanup when the container ref changes or becomes null. The suggested change ensures proper instance cleanup and prevents potential memory leaks from detached modeler instances.

🔗 Analysis chain

Line range hint 96-120: Verify cleanup handling for dynamic ref updates.

The cleanup logic in useEffect might not handle cases where the callback ref is called multiple times with different elements.

Consider enhancing the cleanup handling:

  const canvasRef = useCallback((div: HTMLDivElement | null) => {
+   if (div === null) {
+     // Cleanup when the ref is detached
+     destroyModeler();
+     return;
+   }
    if (modelerRef.current) return;
    // ... rest of the initialization
  }, []);
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find getModeler and destroyModeler implementations
ast-grep --pattern 'function getModeler($_) { $$$ }'
ast-grep --pattern 'function destroyModeler($_) { $$$ }'
ast-grep --pattern 'const destroyModeler = $_'

# Find similar ref callback patterns
ast-grep --pattern 'const $_ = useCallback((div: HTMLDivElement) => { $$$ }, $_)'

# Search for modeler-related files
fd modeler frontend

Length of output: 5721


Script:

#!/bin/bash
# Check BpmnModelerInstance implementation
cat frontend/packages/process-editor/src/utils/bpmnModeler/BpmnModelerInstance.ts

# Look for instance management patterns
ast-grep --pattern 'class BpmnModelerInstance { $$$ }'

# Search for tests that might reveal instance behavior
cat frontend/packages/process-editor/src/hooks/useBpmnModeler/useBpmnModeler.test.ts

Length of output: 6223

🧹 Nitpick comments (1)
frontend/packages/process-editor/src/hooks/useBpmnEditor.test.tsx (1)

154-163: Consider adding type safety to the setup function parameters.

The spread operator with Parameters type provides type safety, but explicit typing would make the API more clear.

Consider this alternative:

function setup(
  currentEventName: string,
  currentEvent: any,
  bpmnDetails: BpmnDetails = mockBpmnDetails
): ReturnType<typeof renderUseBpmnEditor> {
  const div = document.createElement('div');
  const hook = renderUseBpmnEditor(currentEventName, currentEvent, bpmnDetails);
  hook.result.current(div);
  return hook;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 15bd10a and 53783ba.

📒 Files selected for processing (4)
  • frontend/packages/process-editor/src/components/Canvas/BPMNEditor/BPMNEditor.test.tsx (1 hunks)
  • frontend/packages/process-editor/src/components/Canvas/BPMNEditor/BPMNEditor.tsx (1 hunks)
  • frontend/packages/process-editor/src/hooks/useBpmnEditor.test.tsx (4 hunks)
  • frontend/packages/process-editor/src/hooks/useBpmnEditor.ts (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • frontend/packages/process-editor/src/components/Canvas/BPMNEditor/BPMNEditor.tsx
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
🔇 Additional comments (3)
frontend/packages/process-editor/src/hooks/useBpmnEditor.ts (2)

13-13: LGTM! Type definition is clear and focused.

The new type UseBpmnEditorResult clearly represents the callback ref pattern recommended by React.


96-102: Consider adding missing dependencies to useCallback.

The useCallback's empty dependency array might cause stale closure issues. The callback uses modelerRef, getModeler, and initializeEditor which should be included in the dependencies.

Consider adding the dependencies and handling potential issues:

  }, []); // Missing dependencies are not added to avoid getModeler to be called multiple times
+  }, [modelerRef, getModeler, initializeEditor]); // Add proper dependency management

If multiple calls to getModeler are a concern, consider using a ref to track initialization:

const isInitialized = useRef(false);
const canvasRef = useCallback((div: HTMLDivElement) => {
  if (modelerRef.current || isInitialized.current) return;
  isInitialized.current = true;
  // ... rest of the code
}, [modelerRef, getModeler, initializeEditor]);
frontend/packages/process-editor/src/components/Canvas/BPMNEditor/BPMNEditor.test.tsx (1)

9-9: LGTM! Mock implementation correctly matches the new callback ref pattern.

The mock implementation has been properly updated to return a function, aligning with the refactored hook's return type.

@ErlingHauan ErlingHauan self-assigned this Jan 15, 2025
@ErlingHauan ErlingHauan merged commit 3089d3b into main Jan 15, 2025
12 checks passed
@ErlingHauan ErlingHauan deleted the make-usebpmneditor-return-callback-ref branch January 15, 2025 13:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/process Area: Related to app process (e.g. signing, receipt, fill inn, payment, etc). frontend quality/code Violations from current rules for code, best practices, etc. Or just bad code. skip-documentation Issues where updating documentation is not relevant skip-manual-testing PRs that do not need to be tested manually skip-releasenotes Issues that do not make sense to list in our release notes solution/studio/designer Issues related to the Altinn Studio Designer solution. team/studio-core team/studio-domain1
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

2 participants