Skip to content

Commit

Permalink
Merge branch 'bugfix/3202-change-constrainedText-tooltip-behavior' in…
Browse files Browse the repository at this point in the history
…to q/1.0
  • Loading branch information
bert-e committed Feb 24, 2022
2 parents b7247ac + 813b8bb commit 4079515
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 13 deletions.
54 changes: 41 additions & 13 deletions src/lib/components/constrainedtext/Constrainedtext.component.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//@flow
import React from 'react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import type { Node } from 'react';
import styled from 'styled-components';
import Tooltip from '../tooltip/Tooltip.component.js';
import type { Props as TooltipProps } from '../tooltip/Tooltip.component.js';

type Props = {
text: string,
tooltipStyle?: $PropertyType<TooltipProps, 'overlayStyle'>,
Expand All @@ -26,7 +27,10 @@ const ConstrainedTextContainer = styled.div`
-webkit-box-orient: vertical;
`
: `word-wrap: break-word;
white-space: nowrap;`}};
white-space: nowrap;`}
}
;
`;

const BlockTooltip = styled.div`
Expand All @@ -35,26 +39,50 @@ const BlockTooltip = styled.div`
}
`;

function isEllipsisActive(element: HTMLDivElement) {
return element && element.offsetWidth < element.scrollWidth;
}

function getConstrainedTextContainer(constrainedTextRef, lineClamp, text) {
return (
<ConstrainedTextContainer
ref={constrainedTextRef}
className="sc-constrainedtext"
lineClamp={lineClamp}
>
{text}
</ConstrainedTextContainer>
);
}

function ConstrainedText({
text,
tooltipStyle,
tooltipPlacement,
lineClamp = 1,
}: Props): Node {
const [displayToolTip, setDisplayToolTip] = useState(false);

const constrainedTextRef = useCallback(
(element) => {
element && setDisplayToolTip(isEllipsisActive(element) || lineClamp > 1);
},
[lineClamp],
);

return (
<BlockTooltip>
<Tooltip
overlay={text}
overlayStyle={tooltipStyle}
placement={tooltipPlacement}
>
<ConstrainedTextContainer
className="sc-constrainedtext"
lineClamp={lineClamp}
{displayToolTip ? (
<Tooltip
overlay={text}
overlayStyle={tooltipStyle}
placement={tooltipPlacement}
>
{text}
</ConstrainedTextContainer>
</Tooltip>
{getConstrainedTextContainer(constrainedTextRef, lineClamp, text)}
</Tooltip>
) : (
getConstrainedTextContainer(constrainedTextRef, lineClamp, text)
)}
</BlockTooltip>
);
}
Expand Down
4 changes: 4 additions & 0 deletions stories/constrainedtext.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export const Default = () => {
text={'This is a long phrase'}
tooltipStyle={{ width: '100px' }}
/>
<Constrainedtext
text={'This'}
tooltipStyle={{ width: '100px' }}
/>
</div>
<Title>With the ability to customize the style of tooltip</Title>
<div
Expand Down

0 comments on commit 4079515

Please sign in to comment.