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(OverflowTooltipText): add new component #1461

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

Conversation

JoannaSikora
Copy link
Contributor

@JoannaSikora JoannaSikora commented Dec 19, 2024

Resolves: #1458

Description

This pull request introduces the OverflowTooltipText component to the react-components package. The component displays a text element with a tooltip that appears when the text overflows its container, enhancing readability and providing additional context in space-constrained layouts. The changes include the implementation of the component and necessary hooks.

Hooks:

Storybook

https://feature-1458--613a8e945a5665003a05113b.chromatic.com

Checklist

Obligatory:

  • Self review (use this as your final check for proposed changes before requesting the review)
  • Add correct label
  • Assign pull request with the correct issue

Summary by CodeRabbit

  • New Features

    • Introduced the OverflowTooltipText component for displaying text with tooltips when overflowing.
    • Added comprehensive documentation for the OverflowTooltipText component.
    • Created multiple story variations in Storybook to demonstrate different usages of the component.
  • Style

    • Implemented new CSS styles for better text overflow handling and tooltip presentation.
  • Chores

    • Updated main entry point to include the new OverflowTooltipText component for easier imports.

Copy link
Contributor

coderabbitai bot commented Dec 19, 2024

Walkthrough

The pull request introduces a new OverflowTooltipText component in the React components library. This component is designed to handle text overflow by displaying a tooltip when text exceeds its container's width. The implementation includes a comprehensive set of files: TypeScript component, styles, Storybook stories, documentation, and supporting hooks to manage hover and overflow detection.

Changes

File Change Summary
.../OverflowTooltipText.mdx New Storybook documentation file
.../OverflowTooltipText.module.scss Added .tooltipContent and .text CSS classes for text overflow handling
.../OverflowTooltipText.stories.css Added .text-container class
.../OverflowTooltipText.stories.tsx Created Storybook stories with various text scenarios
.../OverflowTooltipText.tsx New React component for overflow tooltip functionality
.../index.ts Added export for OverflowTooltipText
.../types.ts Defined OverflowTooltipTextProps interface
../hooks/index.ts Exported new hooks useOnHover and useIsOverflow
../hooks/types.ts Updated NODE type and added IUseOnHover interface
../hooks/useIsOverflow.ts New hook to detect element overflow
../hooks/useOnHover.ts New hook to manage hover state
../index.ts Added export for OverflowTooltipText

Assessment against linked issues

Objective Addressed Explanation
Create component to check overflown text
Display ellipsis for overflown text
Show full text in tooltip on hover

Suggested reviewers

  • vladko-uxds
  • marcinsawicki

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.


🪧 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.

@JoannaSikora JoannaSikora marked this pull request as ready for review December 20, 2024 11:54
@JoannaSikora JoannaSikora added the feature New feature or request label Dec 20, 2024
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

🧹 Nitpick comments (7)
packages/react-components/src/components/OverflowTooltipText/types.ts (1)

1-3: Consider adding common tooltip customization props

The interface could benefit from additional props like:

  • placement?: 'top' | 'bottom' | 'left' | 'right'
  • showDelay?: number
  • className?: string
packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.module.scss (1)

1-3: Consider adding max-width to tooltip content

To prevent excessively wide tooltips, consider adding a max-width constraint:

.tooltipContent {
  word-break: break-word;
+ max-width: 300px;
}
packages/react-components/src/hooks/useOnHover.ts (1)

5-16: Consider memoizing event handlers

The implementation is clean, but handlers could be memoized with useCallback to prevent unnecessary re-renders in child components.

 export const useOnHover = (initialState = false): IUseOnHover => {
   const [isHovered, setIsHovered] = useState(initialState);
 
-  const handleMouseOver = (): void => setIsHovered(true);
-  const handleMouseOut = (): void => setIsHovered(false);
+  const handleMouseOver = useCallback((): void => setIsHovered(true), []);
+  const handleMouseOut = useCallback((): void => setIsHovered(false), []);
 
   return {
     isHovered,
     handleMouseOver,
     handleMouseOut,
   };
 };
packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.tsx (1)

29-38: Consider memoizing the tooltip content

For performance optimization with long text strings:

+  const tooltipContent = useMemo(
+    () => <div className={styles.tooltipContent}>{text}</div>,
+    [text]
+  );

   return (
     <Tooltip
       kind="invert"
       isVisible={isOverflow && isHovered}
-      triggerRenderer={renderChildren}
+      triggerRenderer={() => children}
     >
-      <div className={styles.tooltipContent}>{text}</div>
+      {tooltipContent}
     </Tooltip>
   );
packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.mdx (1)

13-15: Enhance documentation with accessibility and more examples

Consider adding:

  • Accessibility considerations
  • Examples with different text lengths
  • Use cases with various container widths
packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.stories.tsx (2)

9-17: Consider using a more descriptive class name.

The class name "text-container" could be more specific, like "overflow-tooltip-demo-container" to better indicate its purpose.


19-73: Consider adding more edge cases.

Great coverage of basic scenarios! Consider adding stories for:

  • Different container widths (responsive behavior)
  • RTL text support
  • HTML content within the tooltip
export const RTLText = {
  args: {
    text: 'مرحبا بكم في هذا النص العربي الطويل الذي يتجاوز حدود الحاوية',
  },
};

export const ResponsiveContainer = {
  render: (args: OverflowTooltipTextProps) => (
    <div style={{ width: '50%' }}>
      <OverflowTooltipText {...args} />
    </div>
  ),
  args: {
    text: 'This text will respond to container width changes',
  },
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fe8c5d2 and d88fddd.

📒 Files selected for processing (12)
  • packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.mdx (1 hunks)
  • packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.module.scss (1 hunks)
  • packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.stories.css (1 hunks)
  • packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.stories.tsx (1 hunks)
  • packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.tsx (1 hunks)
  • packages/react-components/src/components/OverflowTooltipText/index.ts (1 hunks)
  • packages/react-components/src/components/OverflowTooltipText/types.ts (1 hunks)
  • packages/react-components/src/hooks/index.ts (1 hunks)
  • packages/react-components/src/hooks/types.ts (2 hunks)
  • packages/react-components/src/hooks/useIsOverflow.ts (1 hunks)
  • packages/react-components/src/hooks/useOnHover.ts (1 hunks)
  • packages/react-components/src/index.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.stories.css
  • packages/react-components/src/components/OverflowTooltipText/index.ts
🔇 Additional comments (8)
packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.module.scss (1)

5-9: LGTM!

Text truncation styles follow best practices.

packages/react-components/src/hooks/index.ts (1)

5-6: LGTM!

Hook exports follow consistent naming and export patterns.

packages/react-components/src/hooks/types.ts (2)

3-3: Good improvement on NODE type

Broadening to HTMLElement makes the type more reusable across different HTML elements.


30-34: LGTM! Clean interface definition

Interface is well-structured with clear purpose and typed handlers.

packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.tsx (1)

1-9: Clean imports with good separation of concerns!

The imports are well-organized, using named imports and custom hooks for specific functionality.

packages/react-components/src/index.ts (1)

37-37: Export is correctly placed and follows the existing pattern!

packages/react-components/src/components/OverflowTooltipText/OverflowTooltipText.stories.tsx (2)

1-8: LGTM! Clean and well-organized imports.


1-73: Verify consistency with design system patterns.

Let's ensure the component follows similar patterns as other components in the design system.

✅ Verification successful

Based on the shell script results, I can now generate the final response:

Component follows design system patterns correctly

The component follows the established patterns in the design system:

  • Uses Typography components (Text, Heading) consistently like other components
  • Story structure matches other components with similar title format and render patterns
  • Follows the same import patterns for Typography as seen across 50+ other components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if other components follow similar patterns
echo "Checking component structure..."
fd -e tsx -e ts "^[A-Z].*\.stories\.(tsx|ts)$" packages/react-components/src/components -x cat {} \; | grep -A 5 "^export default"

# Check Typography component usage patterns
echo "Checking Typography usage..."
rg -A 3 "import.*Typography" packages/react-components/src/components

Length of output: 34564

Comment on lines +21 to +23
const checkOverflowDebounced = debounce(() => {
checkOverflow();
}, 100);
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

Clean up debounced function on unmount

The debounced function should be cancelled in the cleanup function to prevent memory leaks.

 const checkOverflowDebounced = debounce(() => {
   checkOverflow();
 }, 100);
+
+useEffect(() => {
+  return () => {
+    checkOverflowDebounced.cancel();
+  };
+}, [checkOverflowDebounced]);
📝 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
const checkOverflowDebounced = debounce(() => {
checkOverflow();
}, 100);
const checkOverflowDebounced = debounce(() => {
checkOverflow();
}, 100);
useEffect(() => {
return () => {
checkOverflowDebounced.cancel();
};
}, [checkOverflowDebounced]);

Comment on lines +25 to +38
useLayoutEffect(() => {
checkOverflow();

const node = ref.current;
if (node) {
resizeCallback(node, () => {
checkOverflowDebounced();
});
}

return () => {
resizeCallback(null, () => {});
};
}, [ref, checkOverflowDebounced]);
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

Optimize useLayoutEffect dependencies

The effect's dependency array includes checkOverflowDebounced which changes on every render due to debounce creating a new function.

-  }, [ref, checkOverflowDebounced]);
+  }, [ref, checkOverflow]); // Use checkOverflow instead

Also, consider using a cleanup pattern that's more resilient to race conditions:

   useLayoutEffect(() => {
+    let mounted = true;
     checkOverflow();
 
     const node = ref.current;
     if (node) {
       resizeCallback(node, () => {
+        if (mounted) {
           checkOverflowDebounced();
+        }
       });
     }
 
     return () => {
+      mounted = false;
       resizeCallback(null, () => {});
     };
   }, [ref, checkOverflow]);
📝 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
useLayoutEffect(() => {
checkOverflow();
const node = ref.current;
if (node) {
resizeCallback(node, () => {
checkOverflowDebounced();
});
}
return () => {
resizeCallback(null, () => {});
};
}, [ref, checkOverflowDebounced]);
useLayoutEffect(() => {
let mounted = true;
checkOverflow();
const node = ref.current;
if (node) {
resizeCallback(node, () => {
if (mounted) {
checkOverflowDebounced();
}
});
}
return () => {
mounted = false;
resizeCallback(null, () => {});
};
}, [ref, checkOverflow]);

Comment on lines +11 to +28
export const OverflowTooltipText: FC<OverflowTooltipTextProps> = ({ text }) => {
const wrapperRef = useRef<HTMLDivElement>(null);
const isOverflow = useIsOverflow(wrapperRef);
const { isHovered, handleMouseOut, handleMouseOver } = useOnHover(isOverflow);

const renderChildren = () => {
return (
<div
onMouseEnter={handleMouseOver}
onMouseLeave={handleMouseOut}
ref={wrapperRef}
className={styles.text}
>
{text}
</div>
);
};

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 accessibility attributes and consider simplifying the code

The component needs accessibility improvements and could be simplified.

Consider these changes:

-  const renderChildren = () => {
-    return (
-      <div
-        onMouseEnter={handleMouseOver}
-        onMouseLeave={handleMouseOut}
-        ref={wrapperRef}
-        className={styles.text}
-      >
-        {text}
-      </div>
-    );
-  };
+  const children = (
+    <div
+      onMouseEnter={handleMouseOver}
+      onMouseLeave={handleMouseOut}
+      ref={wrapperRef}
+      className={styles.text}
+      aria-label={text}
+    >
+      {text}
+    </div>
+  );
📝 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
export const OverflowTooltipText: FC<OverflowTooltipTextProps> = ({ text }) => {
const wrapperRef = useRef<HTMLDivElement>(null);
const isOverflow = useIsOverflow(wrapperRef);
const { isHovered, handleMouseOut, handleMouseOver } = useOnHover(isOverflow);
const renderChildren = () => {
return (
<div
onMouseEnter={handleMouseOver}
onMouseLeave={handleMouseOut}
ref={wrapperRef}
className={styles.text}
>
{text}
</div>
);
};
export const OverflowTooltipText: FC<OverflowTooltipTextProps> = ({ text }) => {
const wrapperRef = useRef<HTMLDivElement>(null);
const isOverflow = useIsOverflow(wrapperRef);
const { isHovered, handleMouseOut, handleMouseOver } = useOnHover(isOverflow);
const children = (
<div
onMouseEnter={handleMouseOver}
onMouseLeave={handleMouseOut}
ref={wrapperRef}
className={styles.text}
aria-label={text}
>
{text}
</div>
);

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

Successfully merging this pull request may close these issues.

feat(TextWithTooltip) - new component
1 participant