From 813b8bb63432af7a23760fcb21b8f2e1ec48d7ba Mon Sep 17 00:00:00 2001 From: ASMAA EL MOKHTARI Date: Tue, 22 Feb 2022 14:28:48 +0100 Subject: [PATCH] Change constrainedText tooltip behavior --- .../Constrainedtext.component.js | 54 ++++++++++++++----- stories/constrainedtext.stories.js | 4 ++ 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/src/lib/components/constrainedtext/Constrainedtext.component.js b/src/lib/components/constrainedtext/Constrainedtext.component.js index 7b03c9653c..e702f68c27 100644 --- a/src/lib/components/constrainedtext/Constrainedtext.component.js +++ b/src/lib/components/constrainedtext/Constrainedtext.component.js @@ -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, @@ -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` @@ -35,26 +39,50 @@ const BlockTooltip = styled.div` } `; +function isEllipsisActive(element: HTMLDivElement) { + return element && element.offsetWidth < element.scrollWidth; +} + +function getConstrainedTextContainer(constrainedTextRef, lineClamp, text) { + return ( + + {text} + + ); +} + 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 ( - - - {text} - - + {getConstrainedTextContainer(constrainedTextRef, lineClamp, text)} + + ) : ( + getConstrainedTextContainer(constrainedTextRef, lineClamp, text) + )} ); } diff --git a/stories/constrainedtext.stories.js b/stories/constrainedtext.stories.js index e567e02d82..841345b3e8 100644 --- a/stories/constrainedtext.stories.js +++ b/stories/constrainedtext.stories.js @@ -22,6 +22,10 @@ export const Default = () => { text={'This is a long phrase'} tooltipStyle={{ width: '100px' }} /> + With the ability to customize the style of tooltip