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: enhance OverflowTooltip overflow detection for precise handling of non-integral width or height #806

Merged
merged 6 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions packages/react-docs/pages/components/overflow-tooltip/basic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Box, Divider, OverflowTooltip } from '@tonic-ui/react';
import React from 'react';

const App = () => {
return (
<>
<OverflowTooltip
label="This is a tooltip"
>
This text string will be truncated when exceeding its container width. To see this in action, try resizing your browser viewport. If the text overflows, a tooltip will appear, displaying the full content.
</OverflowTooltip>
<Divider my="4x" />
<Box width={140.7}>
<OverflowTooltip
label="This is a tooltip"
>
This text string is truncted
</OverflowTooltip>
</Box>
<Divider my="4x" />
<OverflowTooltip
label="This is a tooltip"
>
This text string is not truncated
</OverflowTooltip>
</>
);
};

export default App;
21 changes: 21 additions & 0 deletions packages/react-docs/pages/components/overflow-tooltip/facc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Icon, Flex, OverflowTooltip, Text } from '@tonic-ui/react';
import React from 'react';

const App = () => {
return (
<OverflowTooltip
label="This is a tooltip"
>
{({ ref, style }) => (
<Flex alignItems="center" columnGap="2x">
<Icon icon="menu" />
<Text ref={ref} {...style}>
This text string will be truncated when exceeding its container width. To see this in action, try resizing your browser viewport. If the text overflows, a tooltip will appear, displaying the full content.
</Text>
</Flex>
)}
</OverflowTooltip>
);
};

export default App;
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,11 @@ import { OverflowTooltip } from '@tonic-ui/react';

If the text overflows its container, it will be truncated, and an ellipsis will be added. When you hover or focus on the ellipsis text, a tooltip will appear.

```jsx
<OverflowTooltip
label="This is a tooltip"
>
This text string will be truncated when exceeding its container width. To see this in action, try resizing your browser viewport. If the text overflows, a tooltip will appear, displaying the full content.
</OverflowTooltip>
```
{render('./basic')}

In the second example, a function is passed as a child of the `OverflowTooltip` component. The function is called with an object containing a `ref` and a `style` property, which should be spread to the element that needs to be truncated. In this case, a `Text` component is used to display the text, and the `ref` and `style` props are spread to it. This allows the `OverflowTooltip` component to detect when the text overflows and display a tooltip.

```jsx
<OverflowTooltip
label="This is a tooltip"
>
{({ ref, style }) => (
<Flex alignItems="center" columnGap="2x">
<Icon icon="menu" />
<Text ref={ref} {...style}>
This text string will be truncated when exceeding its container width. To see this in action, try resizing your browser viewport. If the text overflows, a tooltip will appear, displaying the full content.
</Text>
</Flex>
)}
</OverflowTooltip>
```
{render('./facc')}

## Commonly Asked Questions

Expand All @@ -45,14 +26,7 @@ By default, the `OverflowTooltip` component positions the tooltip relative to it

To mitigate this issue, you can pass `PopperProps={{ usePortal: true }}` to `OverflowTooltip` to make it positioned on the document root.

```jsx
<OverflowTooltip
PopperProps={{ usePortal: true }}
label="This is a tooltip"
>
This text string will be truncated when exceeding its container width. To see this in action, try resizing your browser viewport. If the text overflows, a tooltip will appear, displaying the full content.
</OverflowTooltip>
```
{render('./use-portal')}

## Props

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Box, Divider, OverflowTooltip, Text } from '@tonic-ui/react';
import React from 'react';

const App = () => {
return (
<>
<Box width={360}>
<OverflowTooltip
label="This is a tooltip"
>
{({ ref, style }) => (
<Text
ref={ref}
style={{
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: 3,
overflow: 'hidden',
}}
>
This text string will be truncated when exceeding its container width. To see this in action, try resizing your browser viewport. If the text overflows, a tooltip will appear, displaying the full content.
</Text>
)}
</OverflowTooltip>
</Box>
<Divider my="4x" />
<Box width={480}>
<OverflowTooltip
label="This is a tooltip"
>
{({ ref, style }) => (
<Text
ref={ref}
style={{
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: 3,
overflow: 'hidden',
}}
>
This text string will be truncated when exceeding its container width. To see this in action, try resizing your browser viewport. If the text overflows, a tooltip will appear, displaying the full content.
</Text>
)}
</OverflowTooltip>
</Box>
</>
);
};

export default App;
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { OverflowTooltip } from '@tonic-ui/react';
import React from 'react';

const App = () => {
return (
<OverflowTooltip
PopperProps={{ usePortal: true }}
label="This is a tooltip"
>
This text string will be truncated when exceeding its container width. To see this in action, try resizing your browser viewport. If the text overflows, a tooltip will appear, displaying the full content.
</OverflowTooltip>
);
};

export default App;
12 changes: 1 addition & 11 deletions packages/react-hooks/src/useEventListener.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
import { noop, runIfFn } from '@tonic-ui/utils';
import { useEffect } from 'react';
import useEventCallback from './useEventCallback';

// TODO: move to '@tonic-ui/utils'
const noop = () => {};

// TODO: move to '@tonic-ui/utils'
const runIfFn = (valueOrFn, ...args) => {
if (typeof valueOrFn === 'function') {
return valueOrFn(...args);
}
return valueOrFn;
};

/**
* A custom Hook to manage browser event listeners.
*
Expand Down
4 changes: 1 addition & 3 deletions packages/react-hooks/src/useMediaQuery.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { noop } from '@tonic-ui/utils';
import { useEffect, useState } from 'react';

// TODO: move to '@tonic-ui/utils'
const noop = () => {};

const getInitialState = (query, defaultValue) => {
if (defaultValue !== undefined) {
return defaultValue;
Expand Down
9 changes: 2 additions & 7 deletions packages/react-hooks/src/useOutsideClick.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import { getOwnerDocument, noop } from '@tonic-ui/utils';
import { useEffect } from 'react';
import useEventCallback from './useEventCallback';

// TODO: move to '@tonic-ui/utils'
const noop = () => {};

// TODO: move to '@tonic-ui/utils'
const ownerDocument = (node) => (node?.ownerDocument || document);

const defaultEvents = ['mousedown', 'touchstart'];

/**
Expand All @@ -33,7 +28,7 @@ const useOutsideClick = (

const filteredEvents = (Array.isArray(events) ? events : [])
.filter(x => (typeof x === 'string'));
const doc = ownerDocument(ref?.current);
const doc = getOwnerDocument(ref?.current);

for (const eventName of filteredEvents) {
doc?.addEventListener?.(eventName, savedHandler, true);
Expand Down
46 changes: 39 additions & 7 deletions packages/react/src/tooltip/OverflowTooltip.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,55 @@
ref,
) => {
const contentRef = useRef();
const [isOverflown, setIsOverflown] = useState();
const [isOverflow, setIsOverflow] = useState();
const truncateStyle = useTruncateStyle();

const detectOverflow = useCallback((el, sizeProperty) => {
if (sizeProperty !== 'width' && sizeProperty !== 'height') {
console.error(`Invalid size property: ${sizeProperty}. Use 'width' or 'height'.`);
return false;

Check warning on line 21 in packages/react/src/tooltip/OverflowTooltip.js

View check run for this annotation

Codecov / codecov/patch

packages/react/src/tooltip/OverflowTooltip.js#L20-L21

Added lines #L20 - L21 were not covered by tests
}

const originalSize = el.style[sizeProperty];
const s1 = el.getClientRects()?.[0]?.[sizeProperty];
el.style[sizeProperty] = 'max-content';
const s2 = el.getClientRects()?.[0]?.[sizeProperty];
el.style[sizeProperty] = originalSize; // Revert to original size

if (sizeProperty === 'width') {
return s1 < s2 || el.scrollWidth > el.clientWidth;
}

if (sizeProperty === 'height') {
return s1 < s2 || el.scrollHeight > el.clientHeight;
}

return false;

Check warning on line 38 in packages/react/src/tooltip/OverflowTooltip.js

View check run for this annotation

Codecov / codecov/patch

packages/react/src/tooltip/OverflowTooltip.js#L38

Added line #L38 was not covered by tests
}, []);

const eventTargetFn = useCallback(() => {
return contentRef.current;
}, []);

const onMouseEnter = useCallback((event) => {
const el = event.currentTarget;
setIsOverflown((el.scrollHeight > el.clientHeight) || (el.scrollWidth > el.clientWidth));
}, []);
const isWidthOverflow = detectOverflow(el, 'width');
const isHeightOverflow = detectOverflow(el, 'height');
const isOverflowDetected = isWidthOverflow || isHeightOverflow;
setIsOverflow(isOverflowDetected);
}, [detectOverflow]);

const onMouseLeave = useCallback((event) => {
setIsOverflown(false);
setIsOverflow(false);

Check warning on line 54 in packages/react/src/tooltip/OverflowTooltip.js

View check run for this annotation

Codecov / codecov/patch

packages/react/src/tooltip/OverflowTooltip.js#L54

Added line #L54 was not covered by tests
}, []);

useEventListener(() => contentRef.current, 'mouseenter', onMouseEnter);
useEventListener(() => contentRef.current, 'mouseleave', onMouseLeave);
useEventListener(eventTargetFn, 'mouseenter', onMouseEnter);
useEventListener(eventTargetFn, 'mouseleave', onMouseLeave);

return (
<Tooltip
ref={ref}
disabled={!isOverflown}
disabled={!isOverflow}
{...rest}
>
{(typeof children === 'function') ? (
Expand Down
76 changes: 76 additions & 0 deletions packages/react/src/tooltip/__tests__/OverflowTooltip.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { render } from '@tonic-ui/react/test-utils/render';
import { Box, OverflowTooltip } from '@tonic-ui/react/src';
import React from 'react';

describe('OverflowTooltip', () => {
it('should display an overflow tooltip tooltip if the clientWidth is less than the scrollWidth', async () => {
const user = userEvent.setup();
const textContent = 'This text string will be truncated when exceeding its container width. To see this in action, try resizing your browser viewport. If the text overflows, a tooltip will appear, displaying the full content.';
const tooltipLabel = 'tooltip label';

// Define the scrollWidth, offsetWidth, and clientWidth of the textContent
const scrollWidth = 1193;
const offsetWidth = 900;
const clientWidth = 900;
const maxWidth = scrollWidth;

render(
<Box maxWidth={maxWidth}>
<OverflowTooltip label={tooltipLabel}>
{textContent}
</OverflowTooltip>
</Box>
);

const text = screen.getByText(textContent);

// Mock scrollWidth, offsetWidth, and clientWidth to simulate overflow
Object.defineProperty(text, 'scrollWidth', { configurable: true, value: scrollWidth });
Object.defineProperty(text, 'offsetWidth', { configurable: true, value: offsetWidth });
Object.defineProperty(text, 'clientWidth', { configurable: true, value: clientWidth });

await user.hover(text);

await waitFor(() => {
expect(screen.queryByText(tooltipLabel)).toBeInTheDocument();
});
});

it('should display an overflow tooltip when the `clientRect` varies while setting the width to `max-content`', async () => {
const user = userEvent.setup();
const textContent = 'This is a string to test overflow tooltip';
const tooltipLabel = 'tooltip label';

// Define the clientRects of the textContent
const contentWidth = 120;
const contentHeight = 20;
const maxContentWidth = 120.84;
const maxContentHeight = 20;

render(
<Box width={contentWidth}>
<OverflowTooltip label={tooltipLabel}>
{textContent}
</OverflowTooltip>
</Box>
);

const text = screen.getByText(textContent);

// Mock the getClientRects() function to simulate overflow
text.getClientRects = jest.fn();
text.getClientRects
.mockReturnValueOnce([{ x: 0, y: 0, top: 0, bottom: contentHeight, left: 0, right: contentWidth, width: contentWidth, height: contentHeight }])
.mockReturnValueOnce([{ x: 0, y: 0, top: 0, bottom: contentHeight, left: 0, right: maxContentWidth, width: maxContentWidth, height: contentHeight }])
.mockReturnValueOnce([{ x: 0, y: 0, top: 0, bottom: contentHeight, left: 0, right: contentWidth, width: contentWidth, height: contentHeight }])
.mockReturnValueOnce([{ x: 0, y: 0, top: 0, bottom: maxContentHeight, left: 0, right: contentWidth, width: contentWidth, height: maxContentHeight }]);

await user.hover(text);

await waitFor(() => {
expect(screen.queryByText(tooltipLabel)).toBeInTheDocument();
});
});
});
Loading
Loading