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: add opened and closed events for dialog #4775

Merged
merged 1 commit into from
Oct 31, 2024

Conversation

mynetfan
Copy link
Collaborator

@mynetfan mynetfan commented Oct 31, 2024

Description

为Dialog新增openedclosed事件,在打开和关闭的动画播放完毕后触发

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features
    • Introduced new event handlers onClosed and onOpened for improved modal lifecycle management.
    • Enhanced user feedback with messages indicating the completion of modal open and close animations.
  • Documentation
    • Updated documentation for the Vben Modal component to clarify new event handlers and their functionalities.
  • Tests
    • Added test cases to ensure the new onClosed and onOpened callbacks are functioning correctly.

@mynetfan mynetfan requested review from anncwb, vince292007 and a team as code owners October 31, 2024 06:09
Copy link

changeset-bot bot commented Oct 31, 2024

⚠️ No Changeset found

Latest commit: 7c44e12

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Walkthrough

The pull request introduces enhancements to the Vben Modal component's documentation and functionality. It adds two new event handlers, onClosed and onOpened, to the modal's API, along with corresponding updates to the ModalApi class and its options interface. The documentation has been revised to clarify these changes and include version constraints. Additionally, new test cases have been added to ensure the correct invocation of these callbacks. The changes improve the modal's interaction capabilities and documentation clarity.

Changes

File Change Summary
docs/src/components/common-ui/vben-modal.md Updated documentation to include onClosed and onOpened events; added version constraints and expanded modalApi description.
packages/@core/ui-kit/popup-ui/src/modal/modal-api.ts Added onClosed and onOpened methods to ModalApi; updated constructor to accept new callbacks; modified type definitions.
packages/@core/ui-kit/popup-ui/src/modal/modal.ts Added optional onClosed and onOpened properties to ModalApiOptions interface.
packages/@core/ui-kit/popup-ui/src/modal/modal.vue Introduced event listeners for onClosed and onOpened in DialogContent component.
packages/@core/ui-kit/shadcn-ui/src/ui/dialog/DialogContent.vue Expanded emits to include closed and opened; added onAnimationEnd function for handling animation events.
packages/@core/ui-kit/popup-ui/src/modal/__tests__/modal-api.test.ts Added tests for onClosed and onOpened callbacks in modalApi.
playground/src/views/examples/modal/base-demo.vue Added onClosed and onOpened methods to useVbenModal configuration for user feedback.

Possibly related PRs

Suggested reviewers

  • vince292007

Poem

In the modal's dance, oh what a sight,
New callbacks added, bringing delight.
When it opens wide, or softly closes,
Events now trigger, like blooming roses.
With docs updated, clarity's the key,
Hopping along, come celebrate with me! 🐇✨


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

🧹 Outside diff range and nitpick comments (5)
playground/src/views/examples/modal/base-demo.vue (1)

10-12: Consider internationalizing the messages.

The implementation of the new event handlers looks good and aligns with the PR objectives. However, the messages are hardcoded in Chinese. Consider using i18n translations to support multiple languages.

Example approach:

-    message.info('onClosed:关闭动画结束');
+    message.info(t('modal.onClosedMessage'));

-    message.info('onOpened:打开动画结束');
+    message.info(t('modal.onOpenedMessage'));

Also applies to: 17-19

packages/@core/ui-kit/popup-ui/src/modal/modal.ts (2)

142-146: LGTM! Consider adding English documentation.

The onClosed callback is well-defined and properly integrated. However, since this appears to be an international project, consider adding English documentation alongside the Chinese comments.

  /**
-   * 弹窗关闭动画结束的回调
+   * Callback triggered after the modal close animation ends
+   * 弹窗关闭动画结束的回调
   * @returns
   */
  onClosed?: () => void;

157-161: LGTM! Consider adding English documentation.

The onOpened callback is well-defined and properly integrated. However, since this appears to be an international project, consider adding English documentation alongside the Chinese comments.

  /**
-   * 弹窗打开动画结束的回调
+   * Callback triggered after the modal open animation ends
+   * 弹窗打开动画结束的回调
   * @returns
   */
  onOpened?: () => void;
docs/src/components/common-ui/vben-modal.md (1)

117-117: Consider enhancing the event descriptions.

While the descriptions are accurate, they could be more detailed to help developers understand the exact timing and common use cases. Consider expanding them like this:

-| onClosed | 关闭动画播放完毕时触发 | `()=>void` | >5.4.3 |
+| onClosed | 关闭动画播放完毕时触发。适用于需要在对话框完全关闭后执行清理或后续操作的场景 | `()=>void` | >5.4.3 |
-| onOpened | 打开动画播放完毕时触发 | `()=>void` | >5.4.3 |
+| onOpened | 打开动画播放完毕时触发。适用于需要在对话框完全展示后执行初始化或聚焦等操作的场景 | `()=>void` | >5.4.3 |

Also applies to: 120-120

packages/@core/ui-kit/popup-ui/src/modal/modal.vue (1)

191-196: Well-designed event handling enhancement.

The addition of opened and closed events follows a clean and consistent pattern:

  1. Events are properly integrated with existing event handlers
  2. Implementation uses safe optional chaining
  3. Changes are minimal and focused
  4. No breaking changes introduced

This enhancement provides valuable hooks for animation completion while maintaining the component's existing behavior.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 353e8be and 7c44e12.

📒 Files selected for processing (7)
  • docs/src/components/common-ui/vben-modal.md (1 hunks)
  • packages/@core/ui-kit/popup-ui/src/modal/__tests__/modal-api.test.ts (1 hunks)
  • packages/@core/ui-kit/popup-ui/src/modal/modal-api.ts (4 hunks)
  • packages/@core/ui-kit/popup-ui/src/modal/modal.ts (2 hunks)
  • packages/@core/ui-kit/popup-ui/src/modal/modal.vue (1 hunks)
  • packages/@core/ui-kit/shadcn-ui/src/ui/dialog/DialogContent.vue (3 hunks)
  • playground/src/views/examples/modal/base-demo.vue (1 hunks)
🔇 Additional comments (13)
playground/src/views/examples/modal/base-demo.vue (1)

10-19: Verify integration with useVbenModal API.

The new event handlers are correctly implemented. Let's verify that the useVbenModal API properly supports these callbacks.

✅ Verification successful

The useVbenModal API fully supports the onClosed and onOpened callbacks

The verification shows complete integration:

  • Type definitions exist in packages/@core/ui-kit/popup-ui/src/modal/modal.ts
  • Implementation in packages/@core/ui-kit/popup-ui/src/modal/modal-api.ts properly handles both callbacks
  • Unit tests in modal-api.test.ts verify the functionality
  • The modal component in modal.vue correctly triggers these callbacks
  • Documentation in vben-modal.md confirms these are supported since version 5.4.3
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that useVbenModal API supports the new callbacks

# Test: Search for the type definitions and implementation
ast-grep --pattern 'interface ModalApiOptions {
  $$$
  onClosed?: $_
  onOpened?: $_
  $$$
}'

# Test: Search for any existing usage patterns
rg -A 2 'onClosed|onOpened'

Length of output: 5544

packages/@core/ui-kit/popup-ui/src/modal/modal.ts (1)

Line range hint 142-161: Verify callback implementation in ModalApi.

Let's verify that these callbacks are properly implemented in the ModalApi class.

✅ Verification successful

Let me try a different approach to find the callback implementations.


Callbacks are properly implemented and verified through tests

The implementation in modal-api.ts correctly handles all callbacks:

  • onOpenChange: Called when modal's open state changes (verified by test)
  • onOpened: Called after modal opens and animation completes (verified by test)
  • onClosed: Called after modal closes (verified by test)
  • onConfirm: Called when confirm action is triggered

Key evidence:

  • Implementation in modal-api.ts shows proper callback invocations with appropriate state checks
  • Test file modal-api.test.ts contains specific tests verifying each callback
  • Callbacks are properly typed and included in the ModalApi's options interface
  • State management ensures callbacks are called at the correct lifecycle moments

The implementation follows best practices by:

  • Checking state conditions before invoking callbacks
  • Using TypeScript for type safety
  • Including comprehensive test coverage
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the implementation of onOpened and onClosed callbacks in ModalApi

# Test: Search for the implementation of these callbacks
echo "Searching for callback implementations..."
ast-grep --pattern 'onOpened($$$)' -l ts
ast-grep --pattern 'onClosed($$$)' -l ts

# Test: Check for animation-related code that might trigger these callbacks
echo "Searching for animation-related code..."
rg -l "animation" --type ts

Length of output: 605


Script:

#!/bin/bash
# Search for modal-related files and their content
echo "Searching for modal implementation files..."
fd "modal" -e ts -e tsx

echo "\nChecking modal implementation for callback usage..."
rg "onOpened|onClosed|onConfirm|onOpenChange" -A 5 --type ts

echo "\nSearching for Modal class/interface definitions..."
ast-grep --pattern 'class Modal {
  $$$
}'

ast-grep --pattern 'interface Modal {
  $$$
}'

Length of output: 14398

packages/@core/ui-kit/shadcn-ui/src/ui/dialog/DialogContent.vue (3)

30-32: LGTM: Event definitions are well-typed and follow Vue best practices.

The new events 'closed' and 'opened' are properly defined with TypeScript types while maintaining the existing 'close' event.


68-68: LGTM: Event binding is correctly implemented.

The animationend event is properly bound to the DialogContent component and will capture all animation completions.


49-55: Implementation looks good, but verify animation states.

The animation end handler correctly emits events based on the dialog state. However, we should ensure it works correctly when animations are disabled via CSS.

Let's check if there are any CSS rules that might disable animations:

✅ Verification successful

Let me verify if there are any animation-related styles directly affecting the Dialog component:


Let me check the Dialog component's animation implementation to understand how animations are handled:


Animation handling is properly implemented with fallbacks

The implementation is robust as it uses Vue's <Transition> component with CSS classes for animations (animate-in, animate-out, fade-in-0, etc.) and properly handles animation end states through the @animationend event. Even if animations are disabled via CSS or prefers-reduced-motion, the component will still emit the correct events since the transition end events are guaranteed to fire by Vue's transition system.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for CSS rules that might disable animations
rg -g "*.{css,scss,vue}" "animation.*none|transition.*none|prefers-reduced-motion"

Length of output: 4051


Script:

#!/bin/bash
# Search for animation-related styles in Dialog component files
rg -g "*.{css,scss,vue}" "animation|transition" packages/@core/ui-kit/shadcn-ui/src/ui/dialog/

Length of output: 738


Script:

#!/bin/bash
# Check Dialog component's animation implementation
ast-grep --pattern 'class DialogContent {
  $$$
}'

# Also check for any animation-related CSS classes
rg -g "*.{css,scss,vue}" "animate|fade|slide" packages/@core/ui-kit/shadcn-ui/src/ui/dialog/

Length of output: 960

packages/@core/ui-kit/popup-ui/src/modal/modal-api.ts (4)

9-14: LGTM: API interface updates are well-structured.

The new callback types are properly integrated into the API interface while maintaining alphabetical ordering.


31-34: LGTM: Constructor parameter updates are consistent.

The new callbacks are properly destructured from the options object, maintaining consistency with the API interface.


87-90: LGTM: API initialization is properly implemented.

The new callbacks are correctly initialized in the api object, maintaining consistency with the interface.


127-134: 🛠️ Refactor suggestion

Consider improving the reliability of animation callbacks.

The current implementation of onClosed and onOpened has potential issues:

  1. The state checks might allow multiple callback invocations while the modal remains in the same state.
  2. There's no error handling for callbacks, which could affect the modal's stability.
  3. The documentation could be clearer about the exact timing of these callbacks.

Consider applying these improvements:

  /**
-  * 弹窗关闭动画播放完毕后的回调
+  * Callback fired after the modal's closing animation completes.
+  * This is called exactly once per close transition.
   */
  onClosed() {
-    if (!this.state.isOpen) {
+    try {
      this.api.onClosed?.();
+    } catch (error) {
+      console.error('Error in onClosed callback:', error);
    }
  }

  /**
-  * 弹窗打开动画播放完毕后的回调
+  * Callback fired after the modal's opening animation completes.
+  * This is called exactly once per open transition.
   */
  onOpened() {
-    if (this.state.isOpen) {
+    try {
      this.api.onOpened?.();
+    } catch (error) {
+      console.error('Error in onOpened callback:', error);
    }
  }

The state checks were removed because:

  1. These methods should be called by the animation system exactly once when the respective animation completes
  2. The current state checks don't prevent multiple invocations while in the same state
  3. If timing control is needed, it should be handled by the animation system that calls these methods

Let's verify how these callbacks are invoked:

Also applies to: 143-150

docs/src/components/common-ui/vben-modal.md (1)

113-114: LGTM: Well-structured table format with version tracking.

The addition of the version column is a good practice for tracking API evolution and maintaining backward compatibility awareness.

packages/@core/ui-kit/popup-ui/src/modal/__tests__/modal-api.test.ts (1)

113-127: Test structure and organization looks good!

The new test cases follow the established patterns in the test suite and maintain proper test isolation.

packages/@core/ui-kit/popup-ui/src/modal/modal.vue (2)

191-191: LGTM: Safely implemented closed event handler.

The implementation correctly uses optional chaining and follows Vue.js event handling patterns.


196-196: LGTM: Verify event timing with animation completion.

The implementation is correct. However, let's verify that these events are triggered after the animation completes.

Let's check the DialogContent component implementation to confirm the event timing:

✅ Verification successful

Let me try another search strategy to find the event emission logic.


Let me search for the DialogContent component to verify the animation timing.


Based on the DialogContent component implementation found, I can now provide the final response:

✅ Event timing is correctly implemented with animations

The implementation correctly emits the opened and closed events after animations complete through the onAnimationEnd handler. The component uses CSS animations with proper state transitions (data-[state=open] and data-[state=closed]) and the events are emitted only after these animations finish.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that opened/closed events are emitted after animation completion
# Look for animation-related code and event emission in DialogContent

# Search for animation-related code in DialogContent
rg -A 5 "transition|animation.*opened|animation.*closed" packages/@core/ui-kit/popup-ui/src

# Search for event emission in DialogContent
ast-grep --pattern 'emit($_, "opened")'
ast-grep --pattern 'emit($_, "closed")'

Length of output: 1542


Script:

#!/bin/bash
# Search for opened/closed event handling in modal component and related files
rg -A 5 -B 5 "onOpened|onClosed|@opened|@closed" packages/@core/ui-kit/popup-ui/src

# Search for dialog/modal related components that might handle these events
fd "dialog|modal" packages/@core/ui-kit/popup-ui/src --exec cat {}

Length of output: 32880


Script:

#!/bin/bash
# Search for DialogContent component implementation
fd "DialogContent" packages/@core/ui-kit --exec cat {}

# Search for animation/transition related code in shadcn-ui components
rg -A 5 "transition|animation" packages/@core/shadcn-ui/src

Length of output: 2640

@anncwb anncwb merged commit 06ba7cb into vbenjs:main Oct 31, 2024
14 checks passed
GavinLucky pushed a commit to GavinLucky/vue-vben-admin that referenced this pull request Nov 4, 2024
@mynetfan mynetfan deleted the feat/dialog-opened-closed branch November 5, 2024 02:42
@coderabbitai coderabbitai bot mentioned this pull request Nov 27, 2024
16 tasks
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.

2 participants