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

Hide flagged attachment in attachment carousel #24564

Merged

Conversation

bernhardoj
Copy link
Contributor

@bernhardoj bernhardoj commented Aug 15, 2023

Details

When we flagged an attachment as intimidation/bullying, the attachment becomes hidden in the chat screen. However, we didn't do the same when the user is viewing the attachment in the carousel. This PR hides the attachment in the carousel too.

Fixed Issues

$ #22915
PROPOSAL: #22915 (comment)

Tests

Same as QA Steps

  • Verify that no errors appear in the JS console

Offline tests

Same as QA Steps

QA Steps

  1. Send an attachment to user B
  2. As user B, flag the attachment as Intimidation/Bullying
  3. Open the flagged attachment
  4. Verify you see the attachment is hidden with the same text (This message has been flagged...) and button (Reveal message) as hidden messages
  5. Press the "Reveal message" button
  6. Verify you can now see the attachment
  7. Press the "Hidden message" button
  8. Verify the attachment is hidden
  • 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
Screen.Recording.2023-08-28.at.17.39.13.mov
Mobile Web - Chrome
Screen.Recording.2023-08-28.at.17.44.24.mov
Mobile Web - Safari
Screen.Recording.2023-08-28.at.17.43.33.mov
Desktop
Screen.Recording.2023-08-28.at.17.46.17.mov
iOS
Screen.Recording.2023-08-28.at.17.41.19.mov
Android
Screen.Recording.2023-08-28.at.17.42.18.mov

@bernhardoj bernhardoj requested a review from a team as a code owner August 15, 2023 05:09
@melvin-bot melvin-bot bot removed the request for review from a team August 15, 2023 05:09
@melvin-bot
Copy link

melvin-bot bot commented Aug 15, 2023

@fedirjh 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]

@melvin-bot melvin-bot bot requested a review from fedirjh August 15, 2023 05:10
@fedirjh
Copy link
Contributor

fedirjh commented Aug 16, 2023

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible 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 checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified tests pass on all platforms & I tested again on:
    • Android / native
    • Android / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
    • MacOS / Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (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
    • 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 verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • 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
  • 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
    • 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 reviewer checklist, including those that don't apply to this PR.

Copy link
Contributor

@fedirjh fedirjh left a comment

Choose a reason for hiding this comment

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

cc @bernhardoj, left some comments about little bug on native/mWeb

const {translate} = useLocalize();
const [isHidden, setIsHidden] = useState(item.isHidden);

useEffect(() => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we just remove this hook? it's causing this little bug on native/ mWeb Chrome. The attachment is getting hidden before the navigation

CleanShot.2023-08-16.at.13.22.46-converted.mp4

Copy link
Contributor

Choose a reason for hiding this comment

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

Open the flagged attachment and try to swipe to the next attachment,then cancel the gesture and you can notice that the attachment is hidden.

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 either keep the attachment visible until the next re-render or keep the attachment visible and implement the hide button similar to comments

Copy link
Contributor

Choose a reason for hiding this comment

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

I tested moving the logic to componentWillUnmount, it fixes this bug, but it introduces another bug, sometimes the attachment gets hidden after the next preview. I think that's because updatating state doesn’t works in componentWillUnmount !?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We actually have the viewability config here to update the focus state only when the attachment is 95% visible

const viewabilityConfig = {
// To facilitate paging through the attachments, we want to consider an item "viewable" when it is
// more than 95% visible. When that happens we update the page index in the state.
itemVisiblePercentThreshold: 95,
};

but somehow this didn't work correctly.

If this works correctly, I think the hook is fine even though it will still revert to hidden when we swipe 95%.

I tested moving the logic to componentWillUnmount

I don't think the CarouselItem is unmounted when we swipe it, except the attachment is out of the flat list window size.

I think that's because updatating state doesn’t works in componentWillUnmount

if the component is unmounted, there is no use to update the state because the state is also gone

I think we either keep the attachment visible until the next re-render or keep the attachment visible

I think this is the best choice for now. If someone later reported a bug to hide the attachment back when navigating to another attachment, then we can reintroduce the hook but also fix the viewability issue of the flatlist. What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@shawnborton Ah, okay. Which one do you prefer?
1 (button full width)
image

2 (button in center)
image

(button horizontal and vertical margin is 16)

@fedirjh sure, I will test the zooming later

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@shawnborton any preference on the button view above? 👆

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 the Centered button makes sense, It aligns with the hide button :

Screenshot 2023-08-22 at 7 23 55 PM

Copy link
Contributor

Choose a reason for hiding this comment

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

Works for me too!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Great, thanks for the confirmation.

@fedirjh there is an issue with the image zooming, pdf is fine, will try to fix it.

<Text
style={styles.buttonSmallText}
selectable={false}
dataSet={{[CONST.SELECTION_SCRAPER_HIDDEN_ELEMENT]: true}}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added some comments and this dataSet that is also set in the report action item.

dataSet={{[CONST.SELECTION_SCRAPER_HIDDEN_ELEMENT]: true}}

@bernhardoj
Copy link
Contributor Author

@fedirjh I'm currently stuck on the zooming issue (on native). Below is the explanation of the issue.

When we zoom an image attachment (that is flagged), the zoomed image won't fit 100% on the container. Please see the video below:

Screen.Recording.2023-08-23.at.19.10.46.mov

Compare it with the image attachment without the Hide message button:

Screen.Recording.2023-08-23.at.19.12.01.mov

This happens because the canvasHeight of the image includes the Hide message button.
image

The canvas height is taken from the carousel View onLayout

<View
style={[styles.flex1, styles.attachmentCarouselContainer]}
onLayout={({nativeEvent}) =>
setContainerDimensions({width: PixelRatio.roundToNearestPixel(nativeEvent.layout.width), height: PixelRatio.roundToNearestPixel(nativeEvent.layout.height)})
}

and it's required before rendering the pager (carousel)

{containerDimensions.width > 0 && containerDimensions.height > 0 && (
<AttachmentCarouselPager

This issue actually also happens on an attachment modal when we try to upload a new attachment.

So,

should we ignore it?

or

we make the button absolute and without bg?

image image

@bernhardoj
Copy link
Contributor Author

@fedirjh any thoughts on above?

@bernhardoj
Copy link
Contributor Author

@fedirjh bump ^

@fedirjh
Copy link
Contributor

fedirjh commented Aug 28, 2023

When we zoom an image attachment (that is flagged), the zoomed image won't fit 100% on the container.

Hey @bernhardoj, does it only affect flagged attachments? If that's the case, I believe this might not be a bug. The height differs when the hide button is present, hence it's reasonable for the flagged attachment to have a distinct zoom ratio. Therefore, my recommendation is that we take no action.


However, I believe there is another bug that needs to be addressed. When we preview a flagged attachment in the report view and then open it in the carousel view, the hidden message is displayed. My expectation is to see the flagged attachment instead.

CleanShot.2023-08-28.at.08.52.58.mp4

@bernhardoj
Copy link
Contributor Author

bernhardoj commented Aug 28, 2023

does it only affect flagged attachments

yes

However, I believe there is another bug that needs to be addressed. When we preview a flagged attachment in the report view and then open it in the carousel view, the hidden message is displayed. My expectation is to see the flagged attachment instead.

I wouldn't say it's a bug. When we press the attachment, we navigate to the attachment carousel. Handling the case where the user already revealed the attachment on chat would require some changes that I think are not very clean. Here is what we would need to do:

  1. Pass a param to the route to indicate that this attachment is already revealed.
-r/${reportID}/attachment?source=${encodeURI(source)}
+r/${reportID}/attachment?source=${encodeURI(source)}&isRevealed={true/false}
  1. In the carousel (ReportAttachments), we get the param and pass revealedAttachment={source} to AttachmentModal and then pass to AttachmentCarousel.
  2. In attachment carousel, we pass isRevealed to CarouselItem if the current active source is the same as revealedAttachment.
  3. We use isRevealed to set the initial value of isHidden state.
    isRevealed || item.hasBeenFlagged

EDIT: we would also need to pass a context to the ImageRenderer to tell whether the current attachment is revealed or not

@fedirjh

@fedirjh
Copy link
Contributor

fedirjh commented Sep 6, 2023

can't reproduce it in iOS 16.2. Can you test it on the main?

I couldn’t reproduce on main, and I am not consistently reproducing it on this branch as well , seems there is something with my emulator, it's iOS 16.4 , I will test on another emulator.

@fedirjh
Copy link
Contributor

fedirjh commented Sep 6, 2023

Screenshots/Videos

Web
CleanShot.2023-09-05.at.18.14.41.mp4
Mobile Web - Chrome
CleanShot.2023-09-06.at.11.07.58.mp4
Mobile Web - Safari
CleanShot.2023-09-06.at.15.40.04.mp4
Desktop
CleanShot.2023-09-05.at.18.18.09.mp4
iOS
CleanShot.2023-09-05.at.18.25.49.mp4
Android
CleanShot.2023-09-06.at.10.46.45-converted.mp4

const contextValue = useMemo(
() => ({
isAttachmentHidden,
updateIsAttachmentHidden: (reportActionID, value) => setIsAttachmentHidden({...isAttachmentHidden, [reportActionID]: value}),
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
updateIsAttachmentHidden: (reportActionID, value) => setIsAttachmentHidden({...isAttachmentHidden, [reportActionID]: value}),
updateIsAttachmentHidden: (reportActionID, value) => setIsAttachmentHidden((state) => ({...state, [reportActionID]: value})),

@bernhardoj Why do we use useMemo ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

To prevent unnecessary rerender. If we pass an object without memo to the context value, the object will always be recreated which triggers the useEffect we use inside ReportActionItem.

Copy link
Contributor

@fedirjh fedirjh left a comment

Choose a reason for hiding this comment

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

cc @bernhardoj I have some concerns about the performance impact and I left some comments about possible improvements.

Comment on lines 49 to 53
const {isAttachmentHidden} = useContext(ReportAttachmentsContext);
const [isHidden, setIsHidden] = useState(() => {
const isAttachmentHiddenValue = isAttachmentHidden[item.reportActionID];
return isAttachmentHiddenValue === undefined ? item.hasBeenFlagged : isAttachmentHiddenValue;
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Can't we create a simple hook, useHiddenAttachements(reportActionID) that returns a boolean, that will simplify the logic and make it more readable?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Definitely can, but I decided to not create it because it doesn't solve any actual problem. It reduces the number of characters we type but both isAttachmentHidden and updateIsAttachmentHidden are already available through ReportAttachmentsContext and it's still readable. (Actually my honest reason is I don't like creating a new file 😂)

Before:

const {isAttachmentHidden} = useContext(ReportAttachmentsContext);
const [isHidden, setIsHidden] = useState(() => {
    const isAttachmentHiddenValue = isAttachmentHidden[item.reportActionID];
    return isAttachmentHiddenValue === undefined ? item.hasBeenFlagged : isAttachmentHiddenValue;
});

After:

const isAttachmentHidden = useHiddenAttachments(item.reportActionID);
const [isHidden, setIsHidden] = useState(() => isAttachmentHidden === undefined ? item.hasBeenFlagged : isAttachmentHidden);

Let me know if it makes sense to not create the hook.

Copy link
Contributor

Choose a reason for hiding this comment

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

The problem is that any update to isAttachmentHidden will cause a re-render on all mounted CarouselItem components, even those which are not flagged.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That will be the same case with using hook. Using hook will still require us to access the context. Btw, it's not possible for the isAttachmentHidden state to get updated when we are inside the carousel.

Also, updates to isAttachmentHidden will re-render the whole app.

Comment on lines 141 to 149
useEffect(() => {
const isAttachment = ReportUtils.isReportMessageAttachment(_.last(props.action.message));
// To prevent unnecessary re-render, skip updating the state if the value is the same
if (!isAttachment || Boolean(isAttachmentHidden[props.action.reportActionID]) === isHidden) {
return;
}
updateIsAttachmentHidden(props.action.reportActionID, isHidden);
}, [props.action.reportActionID, props.action.message, isHidden, isAttachmentHidden, updateIsAttachmentHidden]);

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 this is not really necessary and it just adds overload and complexity to the code.

The reportActionItem will re-render when isAttachmentHidden is updated, isAttachmentHidden should be used only for the attachments carousel.

Actually, all report action items will re-render and this is not really a performance-wise approach.

I would suggest creating a new function updateHidden instead of using a useEffect hook :

updateHidden(hiddenState){
    setIsHidden(hiddenState)
    updateIsAttachmentHidden(hiddenState)
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If we remove the optimization, the app will freeze because of an infinite amount of set state calls.

In the useEffect, we depend on updateIsAttachmentHidden, and calling updateIsAttachmentHidden will update the isAttachmentHidden state which means updateIsAttachmentHidden instance is recreated which then triggers the useEffect again, and so on.

I already tried using your suggestion before but it suffers from the same case.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Actually, I think we can move the optimization up to the context. I will try it and push if it works fine.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Actually, I think we can move the optimization up to the context. I will try it and push if it works fine.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@fedirjh can I resolve this one?

Copy link
Contributor Author

@bernhardoj bernhardoj Sep 11, 2023

Choose a reason for hiding this comment

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

setIsHidden is also being used in this useEffect

useEffect(() => {
if (props.action.actionName !== CONST.REPORT.ACTIONS.TYPE.ADDCOMMENT) {
return;
}
// Hide reveal message button and show the message if latestDecision is changed to empty
if (_.isEmpty(latestDecision)) {
setModerationDecision(CONST.MODERATION.MODERATOR_DECISION_APPROVED);
setIsHidden(false);
return;
}
setModerationDecision(latestDecision);
if (!_.contains([CONST.MODERATION.MODERATOR_DECISION_APPROVED, CONST.MODERATION.MODERATOR_DECISION_PENDING], latestDecision)) {
setIsHidden(true);
return;
}
setIsHidden(false);
}, [latestDecision, props.action.actionName]);

If we create a new function (let's call it updateHiddenState), we must wrap it in a callback.

useCallback((isHiddenValue) => {
    setIsHiddenState(isHiddenValue);
    updateHiddenAttachments(actionID, isHiddenValie);
}, [updateHiddenAttachments])

Then the above useEffect will now depend on the new function

[..., updateHiddenState]

Each time hiddenAttachments context is updated, the useEffect will be triggered which will update the state infinitely.

I'm thinking that if hiddenAttachments is updated, the updateHiddenAttachemnts shouldn't be recreated. I will try that and if it works, I will create the new function.

Copy link
Contributor

Choose a reason for hiding this comment

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

setIsHidden is also being used in this useEffect

Hmmm, I wonder why we need to include updateHiddenState in that hook. If a user intends to view the attachment in fullscreen, they should first reveal it.

It would be better to pass updateHiddenState exclusively to the onPress handler of the hide/reveal button. This approach eliminates unnecessary initialization, which, in turn, avoids triggering superfluous updates.

This results in the following evaluation:

  • If it's hidden and not revealed, take no action.
  • If it's hidden and revealed, initialize and update the context. This ensures that we minimize unnecessary updates, with updates contingent on user interactions.

Currently, the code operates as follows:

All attachments are added to the context, and their values are set to either true or false based on their hidden status.

I'm thinking that if hiddenAttachments is updated, the updateHiddenAttachemnts shouldn't be recreated.

This would ultimately resolve any unnecessary re-renders. Maybe using ref to store the state would help achieve that.

Copy link
Contributor Author

@bernhardoj bernhardoj Sep 11, 2023

Choose a reason for hiding this comment

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

Ah, you're right. I already handle the case where the state is undefined here.
image

Maybe using ref to store the state would help achieve that.

Yep, this is what I recently thought and tested. The hiddenAttachments will be a ref instead of a state. Then, we will expose a new function called isAttachmentHidden(reportActionID) through the context, so CarouselItem can get the ref value. This way, updating hiddenAttachments won't re-render the whole app. We don't need the reactivity from the state, so I think it's fine to use ref. What do you think?

diff --git a/src/components/Attachments/AttachmentCarousel/CarouselItem.js b/src/components/Attachments/AttachmentCarousel/CarouselItem.js
index b5b1e0352c..538ebac8d7 100644
--- a/src/components/Attachments/AttachmentCarousel/CarouselItem.js
+++ b/src/components/Attachments/AttachmentCarousel/CarouselItem.js
@@ -46,10 +46,10 @@ const defaultProps = {
 
 function CarouselItem({item, isFocused, onPress}) {
     const {translate} = useLocalize();
-    const {hiddenAttachments} = useContext(ReportAttachmentsContext);
+    const {isAttachmentHidden} = useContext(ReportAttachmentsContext);
     const [isHidden, setIsHidden] = useState(() => {
-        const isAttachmentHidden = hiddenAttachments[item.reportActionID];
-        return isAttachmentHidden === undefined ? item.hasBeenFlagged : isAttachmentHidden;
+        const isAttachmentHiddenValue = isAttachmentHidden(item.reportActionID);
+        return isAttachmentHiddenValue === undefined ? item.hasBeenFlagged : isAttachmentHiddenValue;
     });
 
     const renderButton = (style) => (
diff --git a/src/pages/home/report/ReportAttachmentsContext.js b/src/pages/home/report/ReportAttachmentsContext.js
index d763f9389c..cca47b54aa 100644
--- a/src/pages/home/report/ReportAttachmentsContext.js
+++ b/src/pages/home/report/ReportAttachmentsContext.js
@@ -1,4 +1,4 @@
-import React, {useEffect, useMemo, useState} from 'react';
+import React, {useEffect, useMemo, useRef} from 'react';
 import PropTypes from 'prop-types';
 import useCurrentReportID from '../../../hooks/useCurrentReportID';
 
@@ -11,26 +11,25 @@ const propTypes = {
 
 function ReportAttachmentsProvider(props) {
     const currentReportID = useCurrentReportID();
-    const [hiddenAttachments, setHiddenAttachments] = useState({});
+    const hiddenAttachments = useRef({});
 
     useEffect(() => {
         // We only want to store the attachment visibility for the current report.
         // If the current report ID changes, clear the state.
-        setHiddenAttachments({});
+        hiddenAttachments.current = {};
     }, [currentReportID]);
 
     const contextValue = useMemo(
         () => ({
-            hiddenAttachments,
+            isAttachmentHidden: (reportActionID) => hiddenAttachments.current[reportActionID],
             updateHiddenAttachments: (reportActionID, value) => {
-                // To prevent unnecessary re-render, skip updating the state if the value is the same
-                if (Boolean(hiddenAttachments[reportActionID]) === value) {
-                    return;
-                }
-                setHiddenAttachments((state) => ({...state, [reportActionID]: value}));
+                hiddenAttachments.current = {
+                    ...hiddenAttachments.current,
+                    [reportActionID]: value,
+                };
             },
         }),
-        [hiddenAttachments],
+        [],
     );
 
     return <ReportAttachmentsContext.Provider value={contextValue}>{props.children}</ReportAttachmentsContext.Provider>;

Copy link
Contributor

Choose a reason for hiding this comment

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

@bernhardoj That makes more sense. Let's proceed with this approach.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@fedirjh Great, pushed the new updated.

src/pages/home/report/ReportAttachmentsContext.js Outdated Show resolved Hide resolved
Copy link
Contributor

@fedirjh fedirjh left a comment

Choose a reason for hiding this comment

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

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible 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 checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified tests pass on all platforms & I tested again on:
    • Android / native
    • Android / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
    • MacOS / Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (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
    • 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 verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • 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
  • 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
    • 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 reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Web
CleanShot.2023-09-05.at.18.14.41.mp4
Mobile Web - Chrome
CleanShot.2023-09-06.at.11.07.58.mp4
Mobile Web - Safari
CleanShot.2023-09-06.at.15.40.04.mp4
Desktop
CleanShot.2023-09-05.at.18.18.09.mp4
iOS
CleanShot.2023-09-05.at.18.25.49.mp4
Android
CleanShot.2023-09-06.at.10.46.45-converted.mp4

@melvin-bot melvin-bot bot requested a review from amyevans September 11, 2023 14:03
Copy link
Contributor

@fedirjh fedirjh left a comment

Choose a reason for hiding this comment

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

LGTM

🎀 👀 🎀 C+ reviewed

amyevans
amyevans previously approved these changes Sep 11, 2023
Copy link
Contributor

@amyevans amyevans left a comment

Choose a reason for hiding this comment

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

Nice work! Just a very minor request to increase comment clarity

Comment on lines 51 to 52
const isAttachmentHiddenValue = isAttachmentHidden(item.reportActionID);
return isAttachmentHiddenValue === undefined ? item.hasBeenFlagged : isAttachmentHiddenValue;
Copy link
Contributor

Choose a reason for hiding this comment

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

NAB but I'd prefer isAttachmentHidden

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It will conflict with the isAttachmentHidden function, so I need to append Value to it

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 it could be simplified using the null-coalescing operator ??

const [isHidden, setIsHidden] = useState(isAttachmentHidden(item.reportActionID) ?? item.hasBeenFlagged);

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's a good idea, but the lint forbids null coalescing operators
image

Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe we can pass that rule ?

FYI, nullish coalescing will be supported as part of the TypeScript migration. You can find more details in the following link: TS_STYLE.md

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Wow, lot of new rules. Let's get confirmation from @amyevans.

@amyevans can we ignore the rule for this case?

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 go for it, I think that improves readability considerably and is valid given we're supporting it soon.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Great, updated

@amyevans amyevans merged commit 6188d7b into Expensify:main Sep 12, 2023
12 checks passed
@OSBotify
Copy link
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify
Copy link
Contributor

🚀 Deployed to staging by https://github.com/amyevans in version: 1.3.69-0 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 success ✅
🕸 web 🕸 success ✅

@OSBotify
Copy link
Contributor

🚀 Deployed to production by https://github.com/mountiny in version: 1.3.69-2 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 failure ❌
🕸 web 🕸 success ✅

@OSBotify
Copy link
Contributor

🚀 Deployed to staging by https://github.com/amyevans in version: 1.3.70-0 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 success ✅
🕸 web 🕸 success ✅

@OSBotify
Copy link
Contributor

🚀 Deployed to production by https://github.com/thienlnam in version: 1.3.70-8 🚀

platform result
🤖 android 🤖 failure ❌
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 failure ❌
🕸 web 🕸 success ✅

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.

5 participants