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

Add useOverlayPortalController #450

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

offich
Copy link

@offich offich commented Dec 10, 2024

Fixes #449

Added useOverlayPortalController. I edited readme or changelog like other pull requests. Please let me know if there should be other changes needed.

Summary by CodeRabbit

  • New Features
    • Introduced the useOverlayPortalController hook for managing overlay portals in Flutter applications.
  • Documentation
    • Updated the README to include details about the new useOverlayPortalController hook.
    • Added a new entry in the changelog for the flutter_hooks package regarding the useOverlayPortalController hook.
  • Tests
    • Added a suite of widget tests for the useOverlayPortalController to validate its functionality and state management.

Copy link

coderabbitai bot commented Dec 10, 2024

Walkthrough

The changes in this pull request introduce a new hook, useOverlayPortalController, to the Flutter Hooks library. This hook is documented in the README.md and included in the changelog. The implementation consists of a new part file, overlay_portal_controller.dart, which defines the hook and its associated state management classes. Additionally, a comprehensive test suite is created to validate the functionality of the new hook, ensuring it behaves as expected in various scenarios.

Changes

File Change Summary
README.md Added documentation for useOverlayPortalController in "Misc hooks".
packages/flutter_hooks/CHANGELOG.md Updated changelog to include entry for useOverlayPortalController.
packages/flutter_hooks/lib/src/hooks.dart Added new part file: overlay_portal_controller.dart.
packages/flutter_hooks/lib/src/overlay_portal_controller.dart Introduced useOverlayPortalController, _OverlayPortalControllerHook, and _OverlayPortalControllerHookState classes.
packages/flutter_hooks/test/use_overlay_portal_controller_test.dart Added tests for useOverlayPortalController functionality.

Assessment against linked issues

Objective Addressed Explanation
Add useOverlayPortalController hook (#449)

🐇 In the meadow, I hop and play,
New hooks are here to brighten the day!
With portals to overlay, oh what a sight,
Flutter's magic shines ever so bright!
Let's code and create, with joy in our hearts,
For every new feature, a masterpiece starts! 🌼

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. This feature will be included in our Pro Plan when released.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db9a63f and f0faeff.

📒 Files selected for processing (1)
  • README.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • README.md

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.

@offich offich force-pushed the feat/use-overlay-portal-controller branch from a990178 to 51e3c56 Compare December 10, 2024 15:29
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: 2

🧹 Outside diff range and nitpick comments (2)
packages/flutter_hooks/lib/src/overlay_portal_controller.dart (1)

3-11: Enhance the hook documentation

The current documentation could be more descriptive. Consider adding:

  • A brief description of what an OverlayPortalController is used for
  • Example usage
  • Description of the optional keys parameter

Example enhancement:

 /// Creates a [OverlayPortalController] that will be disposed automatically.
+/// 
+/// The [OverlayPortalController] is used to control the visibility of content in an [OverlayPortal].
+/// This hook ensures proper lifecycle management of the controller.
+/// 
+/// The optional [keys] parameter can be used to preserve the controller's state across rebuilds
+/// when the specified keys remain unchanged.
+/// 
+/// Example usage:
+/// ```dart
+/// final controller = useOverlayPortalController();
+/// return OverlayPortal(
+///   controller: controller,
+///   overlayChildBuilder: (context) => const Text('Overlay Content'),
+///   child: const Text('Anchor Widget'),
+/// );
+/// ```
 ///
 /// See also:
 /// - [OverlayPortalController]
packages/flutter_hooks/test/use_overlay_portal_controller_test.dart (1)

34-61: Simplify the test structure

The test could be simplified while maintaining the same verification:

 testWidgets('initial values matches with real constructor', (tester) async {
   late OverlayPortalController controller;
   final controller2 = OverlayPortalController();

-  await tester.pumpWidget(MaterialApp(
-    home: Scaffold(
-      body: HookBuilder(builder: (context) {
-        controller = useOverlayPortalController();
-        return Column(
-          children: [
-            OverlayPortal(
-              controller: controller,
-              overlayChildBuilder: (context) =>
-                  const Text('Overlay Portal'),
-            ),
-            OverlayPortal(
-              controller: controller2,
-              overlayChildBuilder: (context) =>
-                  const Text('Overlay Portal 2'),
-            ),
-          ],
-        );
-      }),
-    ),
-  ));
+  await tester.pumpWidget(
+    HookBuilder(builder: (context) {
+      controller = useOverlayPortalController();
+      return const SizedBox();
+    }),
+  );

   expect(controller, isA<OverlayPortalController>());
   expect(controller.isShowing, controller2.isShowing);
+  expect(controller.isShowing, isFalse);
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 319679b and 51e3c56.

📒 Files selected for processing (5)
  • README.md (1 hunks)
  • packages/flutter_hooks/CHANGELOG.md (1 hunks)
  • packages/flutter_hooks/lib/src/hooks.dart (1 hunks)
  • packages/flutter_hooks/lib/src/overlay_portal_controller.dart (1 hunks)
  • packages/flutter_hooks/test/use_overlay_portal_controller_test.dart (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • packages/flutter_hooks/lib/src/hooks.dart
  • packages/flutter_hooks/CHANGELOG.md
  • README.md
🔇 Additional comments (2)
packages/flutter_hooks/lib/src/overlay_portal_controller.dart (1)

13-19: LGTM!

The hook class implementation follows the standard pattern and correctly implements the required methods.

packages/flutter_hooks/test/use_overlay_portal_controller_test.dart (1)

9-31: LGTM!

The test properly verifies the diagnostic representation of the hook.

Comment on lines +21 to +30
class _OverlayPortalControllerHookState
extends HookState<OverlayPortalController, _OverlayPortalControllerHook> {
final controller = OverlayPortalController();

@override
OverlayPortalController build(BuildContext context) => controller;

@override
String get debugLabel => 'useOverlayPortalController';
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add dispose method to clean up resources

The controller should be disposed when the hook is disposed to prevent memory leaks.

Add the dispose method:

 class _OverlayPortalControllerHookState
     extends HookState<OverlayPortalController, _OverlayPortalControllerHook> {
   final controller = OverlayPortalController();

   @override
   OverlayPortalController build(BuildContext context) => controller;

   @override
   String get debugLabel => 'useOverlayPortalController';
+
+  @override
+  void dispose() {
+    controller.dispose();
+    super.dispose();
+  }
 }
📝 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
class _OverlayPortalControllerHookState
extends HookState<OverlayPortalController, _OverlayPortalControllerHook> {
final controller = OverlayPortalController();
@override
OverlayPortalController build(BuildContext context) => controller;
@override
String get debugLabel => 'useOverlayPortalController';
}
class _OverlayPortalControllerHookState
extends HookState<OverlayPortalController, _OverlayPortalControllerHook> {
final controller = OverlayPortalController();
@override
OverlayPortalController build(BuildContext context) => controller;
@override
String get debugLabel => 'useOverlayPortalController';
@override
void dispose() {
controller.dispose();
super.dispose();
}
}

Comment on lines 63 to 82
testWidgets('check show/hide of overlay portal', (tester) async {
late OverlayPortalController controller;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: HookBuilder(builder: (context) {
controller = useOverlayPortalController();
return OverlayPortal(
controller: controller,
overlayChildBuilder: (context) => const Text('Overlay Portal 2'),
);
}),
),
));

expect(controller.isShowing, false);
controller.show();
expect(controller.isShowing, true);
controller.hide();
expect(controller.isShowing, false);
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage for show/hide functionality

The test verifies the controller state but should also verify:

  1. Widget tree updates after show/hide
  2. Actual visibility of the overlay content
 testWidgets('check show/hide of overlay portal', (tester) async {
   late OverlayPortalController controller;
   await tester.pumpWidget(MaterialApp(
     home: Scaffold(
       body: HookBuilder(builder: (context) {
         controller = useOverlayPortalController();
         return OverlayPortal(
           controller: controller,
-          overlayChildBuilder: (context) => const Text('Overlay Portal 2'),
+          overlayChildBuilder: (context) => const Text('Overlay Content'),
         );
       }),
     ),
   ));

   expect(controller.isShowing, false);
+  expect(find.text('Overlay Content'), findsNothing);
+
   controller.show();
+  await tester.pump();
   expect(controller.isShowing, true);
+  expect(find.text('Overlay Content'), findsOneWidget);
+
   controller.hide();
+  await tester.pump();
   expect(controller.isShowing, false);
+  expect(find.text('Overlay Content'), findsNothing);
 });
📝 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
testWidgets('check show/hide of overlay portal', (tester) async {
late OverlayPortalController controller;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: HookBuilder(builder: (context) {
controller = useOverlayPortalController();
return OverlayPortal(
controller: controller,
overlayChildBuilder: (context) => const Text('Overlay Portal 2'),
);
}),
),
));
expect(controller.isShowing, false);
controller.show();
expect(controller.isShowing, true);
controller.hide();
expect(controller.isShowing, false);
});
testWidgets('check show/hide of overlay portal', (tester) async {
late OverlayPortalController controller;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: HookBuilder(builder: (context) {
controller = useOverlayPortalController();
return OverlayPortal(
controller: controller,
overlayChildBuilder: (context) => const Text('Overlay Content'),
);
}),
),
));
expect(controller.isShowing, false);
expect(find.text('Overlay Content'), findsNothing);
controller.show();
await tester.pump();
expect(controller.isShowing, true);
expect(find.text('Overlay Content'), findsOneWidget);
controller.hide();
await tester.pump();
expect(controller.isShowing, false);
expect(find.text('Overlay Content'), findsNothing);
});

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 (4)
packages/flutter_hooks/lib/src/overlay_portal_controller.dart (1)

3-11: Enhance hook documentation with examples and details

While the basic documentation is present, it would be more helpful to include:

  • Usage examples
  • Common use cases
  • Link to Flutter's OverlayPortalController documentation

Add the following to the documentation:

 /// Creates a [OverlayPortalController] that will be disposed automatically.
 ///
+/// Example usage:
+/// ```dart
+/// final controller = useOverlayPortalController();
+/// return OverlayPortal(
+///   controller: controller,
+///   overlayChildBuilder: (context) => const Text('Overlay Content'),
+/// );
+/// ```
+///
 /// See also:
 /// - [OverlayPortalController]
+/// - [OverlayPortal]
packages/flutter_hooks/test/use_overlay_portal_controller_test.dart (2)

9-31: Enhance debug properties test coverage

Consider adding test cases for different controller states (SHOWING, HIDDEN) to ensure complete debug output coverage.

Add the following test cases:

 testWidgets('debugFillProperties', (tester) async {
   await tester.pumpWidget(
     HookBuilder(builder: (context) {
-      useOverlayPortalController();
+      final controller = useOverlayPortalController();
       return const SizedBox();
     }),
   );

   await tester.pump();

   final element = tester.element(find.byType(HookBuilder));
+  
+  // Test DETACHED state
   expect(
     element
         .toDiagnosticsNode(style: DiagnosticsTreeStyle.offstage)
         .toStringDeep(),
     equalsIgnoringHashCodes(
       'HookBuilder\n'
       ' │ useOverlayPortalController: OverlayPortalController DETACHED\n'
       ' └SizedBox(renderObject: RenderConstrainedBox#00000)\n',
     ),
   );
+  
+  // Test SHOWING state
+  controller.show();
+  await tester.pump();
+  expect(
+    element
+        .toDiagnosticsNode(style: DiagnosticsTreeStyle.offstage)
+        .toStringDeep(),
+    equalsIgnoringHashCodes(
+      'HookBuilder\n'
+      ' │ useOverlayPortalController: OverlayPortalController SHOWING\n'
+      ' └SizedBox(renderObject: RenderConstrainedBox#00000)\n',
+    ),
+  );
 });

34-61: Simplify and focus the initial values test

The test creates unnecessary complexity by using two controllers. The comparison can be simplified to focus on the essential behavior.

Simplify the test:

 testWidgets('initial values matches with real constructor', (tester) async {
   late OverlayPortalController controller;
-  final controller2 = OverlayPortalController();
 
   await tester.pumpWidget(MaterialApp(
     home: Scaffold(
       body: HookBuilder(builder: (context) {
         controller = useOverlayPortalController();
-        return Column(
-          children: [
-            OverlayPortal(
-              controller: controller,
-              overlayChildBuilder: (context) =>
-                  const Text('Overlay Portal'),
-            ),
-            OverlayPortal(
-              controller: controller2,
-              overlayChildBuilder: (context) =>
-                  const Text('Overlay Portal 2'),
-            ),
-          ],
-        );
+        return OverlayPortal(
+          controller: controller,
+          overlayChildBuilder: (context) => const Text('Overlay Portal'),
+        );
       }),
     ),
   ));
   expect(controller, isA<OverlayPortalController>());
-  expect(controller.isShowing, controller2.isShowing);
+  expect(controller.isShowing, false);
 });
packages/flutter_hooks/CHANGELOG.md (1)

1-4: Enhance changelog entry with more details

While the entry follows conventions, it would be helpful to include a brief description of the hook's purpose and use case.

Add more context to the changelog entry:

 ## Unreleased build

-Added `useOverlayPortalController` (thanks to @offich)
+Added `useOverlayPortalController` - A hook that creates and manages an `OverlayPortalController` for controlling overlay visibility in Flutter applications (thanks to @offich)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 319679b and db9a63f.

📒 Files selected for processing (5)
  • README.md (1 hunks)
  • packages/flutter_hooks/CHANGELOG.md (1 hunks)
  • packages/flutter_hooks/lib/src/hooks.dart (1 hunks)
  • packages/flutter_hooks/lib/src/overlay_portal_controller.dart (1 hunks)
  • packages/flutter_hooks/test/use_overlay_portal_controller_test.dart (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/flutter_hooks/lib/src/hooks.dart
🔇 Additional comments (4)
packages/flutter_hooks/lib/src/overlay_portal_controller.dart (2)

13-19: LGTM!

The hook class implementation follows best practices and correctly implements the required methods.


21-30: Add dispose method to clean up resources

The controller should be disposed when the hook is disposed to prevent memory leaks.

packages/flutter_hooks/test/use_overlay_portal_controller_test.dart (1)

63-89: LGTM!

The show/hide test implementation is comprehensive and follows best practices:

  • Verifies controller state changes
  • Checks widget tree updates
  • Validates overlay content visibility
README.md (1)

Line range hint 1-1: Update translations

Since the README has translations in multiple languages (Português, 한국어, 简体中文), consider updating those translation files as well to maintain consistency across all documentation.

Let's check if the translation files exist and need updates:

README.md Outdated
@@ -358,6 +358,7 @@ A series of hooks with no particular theme.
| [useExpansionTileController](https://api.flutter.dev/flutter/material/ExpansionTileController-class.html) | Creates a `ExpansionTileController`. |
| [useDebounced](https://pub.dev/documentation/flutter_hooks/latest/flutter_hooks/useDebounced.html) | Returns a debounced version of the provided value, triggering widget updates accordingly after a specified timeout duration |
| [useDraggableScrollableController](https://api.flutter.dev/flutter/widgets/DraggableScrollableController-class.html) | Creates a `DraggableScrollableController`. |
| [useOverlayPortalController](https://api.flutter.dev/flutter/widgets/OverlayPortalController-class.html) | Creates a `useOverlayPortalController`. |
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve the hook description

The current description "Creates a useOverlayPortalController" is circular and doesn't explain the hook's purpose. Consider revising it to better explain its functionality and relationship with Flutter's OverlayPortalController.

-| [useOverlayPortalController](https://api.flutter.dev/flutter/widgets/OverlayPortalController-class.html)                 | Creates a `useOverlayPortalController`.  |
+| [useOverlayPortalController](https://api.flutter.dev/flutter/widgets/OverlayPortalController-class.html)                 | Creates and manages an `OverlayPortalController` for controlling the visibility of overlay content. The controller will be automatically disposed when no longer needed. |
📝 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
| [useOverlayPortalController](https://api.flutter.dev/flutter/widgets/OverlayPortalController-class.html) | Creates a `useOverlayPortalController`. |
| [useOverlayPortalController](https://api.flutter.dev/flutter/widgets/OverlayPortalController-class.html) | Creates and manages an `OverlayPortalController` for controlling the visibility of overlay content. The controller will be automatically disposed when no longer needed. |

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.

Add OverlayPortalController
1 participant