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

Fix: Chat - Link in end of line displays tooltip over text and not on link #27817

Closed
wants to merge 5 commits into from

Conversation

ewanmellor
Copy link

@ewanmellor ewanmellor commented Sep 19, 2023

Details

Add a new prop to Tooltip called shouldUseMultilinePositioning. This enables a new algorithm for finding the bounding box target for the tooltip. In the case where the target has wrapped onto multiple lines (e.g. it is a link in a chat window) then the link has multiple bounding boxes, and we want to show the tooltip against the one that the user is hovering over.

As part of this, extend Hoverable to pass the Event to its onHoverIn / onHoverOut callbacks.

Enable this new algorithm from BaseAnchorForCommentsOnly, which is the base class for links that show up in chat.

Fixed Issues

$ #27585
PROPOSAL: #27585 (comment)

Tests

Action Performed:

On a platform with a mouse (i.e. not mobile):

  1. Open the app
  2. Open any report
  3. Type in some text and at the end of line, add link with long text eg: Test test test test test test test test test test
  4. Send the text, text should have text and link in first line and link should be continued in second line too. Adjust the window size to force the text to wrap if necessary.
  5. Hover on link and observe that tooltip is displayed over text

Expected Result:
App should display tooltip over link on hover. The tooltip should appear over the same section of the link that the user is hovering over.

  • Verify that no errors appear in the JS console

Offline tests

N/A. There is no network interaction in this change.

QA Steps

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android / native
    • Android / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
    • MacOS / Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I verified the translation was requested/reviewed in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is approved by marketing by adding the Waiting for Copy label for a copy review on the original GH to get the correct copy.
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(themeColors.componentBG))
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR author checklist, including those that don't apply to this PR.

Screenshots/Videos

Web Screenshot 2023-09-19 at 3 38 28 PM Screenshot 2023-09-19 at 3 38 23 PM
Mobile Web - Chrome
Mobile Web - Safari
Desktop
iOS
Android

… link

Add a new prop to Tooltip called shouldUseMultilinePositioning. This
enables a new algorithm for finding the bounding box target for the
tooltip. In the case where the target has wrapped onto multiple lines
(e.g. it is a link in a chat window) then the link has multiple bounding
boxes, and we want to show the tooltip against the one that the user is
hovering over.

As part of this, extend Hoverable to pass the Event to its onHoverIn /
onHoverOut callbacks.

Enable this new algorithm from BaseAnchorForCommentsOnly, which is the
base class for links that show up in chat.
@ewanmellor ewanmellor requested a review from a team as a code owner September 19, 2023 23:05
@melvin-bot melvin-bot bot requested review from s77rt and removed request for a team September 19, 2023 23:05
@melvin-bot
Copy link

melvin-bot bot commented Sep 19, 2023

@s77rt Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@github-actions
Copy link
Contributor

github-actions bot commented Sep 19, 2023

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

@ewanmellor
Copy link
Author

I have read the CLA Document and I hereby sign the CLA

@ewanmellor
Copy link
Author

recheck

1 similar comment
@ewanmellor
Copy link
Author

recheck

@@ -42,6 +59,7 @@ const defaultProps = {
renderTooltipContent: undefined,
renderTooltipContentKey: [],
shouldHandleScroll: false,
shouldUseMultilinePositioning: false,
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's remove this prop. I think we want to have this feature enabled for all tooltips

@@ -94,7 +95,7 @@ class Hoverable extends Component {
if (this.isScrollingRef && this.props.shouldHandleScroll && !this.state.isHovered) return;

if (isHovered !== this.state.isHovered) {
this.setState({isHovered}, isHovered ? this.props.onHoverIn : this.props.onHoverOut);
this.setState({isHovered}, () => (isHovered ? this.props.onHoverIn : this.props.onHoverOut)(ev));
Copy link
Contributor

Choose a reason for hiding this comment

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

Given that onHoverIn may be called without events it's better to use onMouseEnter. Add onMouseEnter and onMouseLeave props to Hoverable and use onMouseEnter to set the target and mouse position.

In Tooltip:

    const target = useRef(null);
    const initialMousePosition = useRef({x: 0, y: 0});

    const updateTargetAndMousePosition = useCallback((e) => {
        target.current = e.target;
        initialMousePosition.current = {x: e.clientX, y: e.clientY};
    }, []);

    <Hoverable onMouseEnter={updateTargetAndMousePosition) ... />

Comment on lines 101 to 107
if (shouldUseMultilinePositioning) {
if (ev) {
const {clientX, clientY, target} = ev;
const bb = chooseBoundingBox(target, clientX, clientY);
updateBounds(bb);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Undo this. chooseBoundingBox should be called from updateBounds

    const updateBounds = (bounds) => {
        if (bounds.width === 0) {
            setIsRendered(false);
        }
        const betterBounds = chooseBoundingBox(target.current, initialMousePosition.current.x, initialMousePosition.current.y);
        setWrapperWidth(betterBounds.width);
        setWrapperHeight(betterBounds.height);
        setXOffset(betterBounds.x);
        setYOffset(betterBounds.y);
    };

Copy link
Author

Choose a reason for hiding this comment

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

@s77rt This doesn't make sense. If the user hovers over one part of the link and then moves to the other part, you need to move the tooltip. updateBounds is only called when the element moves, but in that case the element itself has not moved, so we will miss the necessary update. That's why it needs to be in the hover event handler.

Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not sure if this is a valid case. if the user moves to the other part then we'd have two possible outcomes:

  1. User is still hovering the target, in this case the tooltip does not need to be updated as this case is only possible if the mouse stays at the same row (x position)
  2. User lost hover, in this case onMouseEnter will be called once the user hover the next part and the tooltip will be placed correctly

Copy link
Author

Choose a reason for hiding this comment

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

@s77rt Right, but your proposed updateTargetAndMousePosition doesn't set the tooltip position, it just saves the mouse position at that time. So when the onMouseEnter is called, you remember the location but don't do anything with that. And you won't get a call to updateBounds because the element hasn't moved.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes, that's the intended use. updateBounds will be called once the tooltip is visible or on bounds change

Copy link
Author

Choose a reason for hiding this comment

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

@s77rt "updateBounds will be called by BoundsObserver". This only happens if the element moves. If the user is moving the mouse between two parts of the same link, the element does not move and updateBounds is not called.

Copy link
Contributor

Choose a reason for hiding this comment

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

That's correct. But the user can't move the mouse between two parts without firing the onMouseLeave and then onMouseEnter again on the second part

Copy link
Author

Choose a reason for hiding this comment

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

@s77rt Yes, but again, if the user does onMouseLeave and onMouseEnter, then you have nothing calling updateBounds. Your proposed updateTargetAndMousePosition does not call updateBounds. So the tooltip does not move. What am I missing from what you are saying?

Copy link
Contributor

Choose a reason for hiding this comment

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

  • onMouseLeave -> onHoverOut -> hideTooltip -> setIsVisible(false)
  • onMouseEnter (1st callback) -> updateTargetAndMousePosition
  • onMouseEnter (2nd callback) -> onHoverIn -> showTooltip -> setIsVisible(true)

Besides setting the target and mouse position, we have a change in the isVisible state which is passed to the enabled prop of BoundsObserver and per the docs https://socket.dev/npm/package/@react-ng/bounds-observer

Additionally, this callback will be invoked on enabling, i.e. when the enabled property changes to true

Copy link
Author

Choose a reason for hiding this comment

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

@s77rt OK, I finally see what you are saying. I have updated this PR with all the changes mentioned.

* enough then we go with that.
* @return {DOMRect} The chosen bounding box.
*/
function chooseBoundingBox(target, clientX, clientY, slop = 0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we'd need a safer algo without the recursive call.

Comment on lines 46 to 48
// Fall back to the full bounding box if we failed to find a matching one
// (shouldn't happen).
return target.getBoundingClientRect();
Copy link
Contributor

Choose a reason for hiding this comment

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

Don't write code that can't be reached.

* @return {DOMRect} The chosen bounding box.
*/
function chooseBoundingBox(target, clientX, clientY, slop = 0) {
const bbs = target.getClientRects();
Copy link
Contributor

Choose a reason for hiding this comment

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

minor optimisation, if bbs contains only one element then just use it (that element would be same as getBoundingClientRect)

… link

Changes from PR review:
  o  Remove the shouldUseMultilinePositioning prop, and instead make the
new algorithm the one to use in all situations.
  o  Refactor chooseBoundingBox to avoid a recursive call.
  o  Shortcut chooseBoundingBox in the case where the element only
has one bounding box.
  o  Revert the changes to Hoverable that pass the MouseEvent through
onHoverIn / onHoverOut, and instead add direct pass-throughs for the
onMouseEnter / onMouseLeave events.
  o  Change the algorithm so that the onHoverIn event handler only
records the mouse position, and rely on BoundsObserver being enabled
as a side-effect of the isVisible change to move the tooltip.
@ewanmellor
Copy link
Author

recheck

Comment on lines 162 to 164
if (_.isFunction(this.props.onMouseEnter)) {
this.props.onMouseEnter(el);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Move this to be the first callback (same for onMouseLeave)

Copy link
Author

Choose a reason for hiding this comment

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

Done.

Copy link
Contributor

Choose a reason for hiding this comment

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

This is still not the first, it needs to goes before setIsHovered

Copy link
Author

Choose a reason for hiding this comment

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

Done.

Comment on lines 160 to 162
if (!t) {
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there a case where target is not defined?

Copy link
Author

Choose a reason for hiding this comment

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

No, but the type system would not be able to see that, because it cannot tell that updateBounds will never be called before a hover event makes the tooltip visible.

Regardless, this file is not TypeScript, so I've removed it.

if (!t) {
return;
}
const betterBounds = chooseBoundingBox(t, initialMousePosition.current.x, initialMousePosition.current.y);
Copy link
Contributor

Choose a reason for hiding this comment

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

Please add a comment here on why we need better bounding box

Copy link
Author

Choose a reason for hiding this comment

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

Done.

… link

Changes from PR review:
  o  Reorder the callbacks from Hoverable.
  o  Remove a null check.
  o  Add a comment.
… link

Changes from PR review:
  o  Small tidyup.
@ewanmellor
Copy link
Author

recheck

… link

Change from PR review: move the onMouseEnter / onMouseLeave callbacks
before the setIsHovered calls.
Comment on lines +23 to +27
* @param {number} slop An allowed slop factor when searching for the bounding
* box. If the user is moving the mouse quickly we can end up getting a
* hover event with the position outside any of our bounding boxes. We retry
* with a small slop factor in that case, so if we have a bounding box close
* enough then we go with that.
Copy link
Contributor

Choose a reason for hiding this comment

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

I have been checking and I think the need for the tolerance is not related to moving the mouse quickly, I can reproduce the bug constantly and this seems due to the returned bbs values corresponding to the text fragments only and not the block. Let's have the tolerance always used and integrate this function inside chooseBoundingBox

// Fall back to the full bounding box if we failed to find a matching one.
// This could only happen if the user is moving the mouse very quickly
// and they got it outside our slop above.
return target.getBoundingClientRect();
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
return target.getBoundingClientRect();
return bbs[0];

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.

2 participants