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

16265 - Refactor ReportActionItemMessageEdit to functional component #20296

Conversation

kushu7
Copy link
Contributor

@kushu7 kushu7 commented Jun 6, 2023

Details

Fixed Issues

$ #16265
PROPOSAL: #16265 (comment)

Tests

  1. Go to report.
  2. Edit a message.
  3. Verify working of edit message.
  • Verify that no errors appear in the JS console

Offline tests

Same as Tests

QA Steps

  1. Go to report.
  2. Edit a message.
  3. Verify working of edit message.
  • 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
    • 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 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
web1.mov
Mobile Web - Chrome
mweb.chrome.mp4
Mobile Web - Safari
msafari.mov
Desktop
Screen.Recording.2023-06-06.at.11.28.40.PM.mov
iOS
ios.mov
Android
android.mp4

@kushu7 kushu7 requested a review from a team as a code owner June 6, 2023 18:00
@melvin-bot melvin-bot bot requested review from roryabraham and removed request for a team June 6, 2023 18:01
@melvin-bot
Copy link

melvin-bot bot commented Jun 6, 2023

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

@s77rt
Copy link
Contributor

s77rt commented Jun 6, 2023

I will review this @roryabraham

cc @yuwenmemon

src/pages/home/report/ReportActionItemMessageEdit.js Outdated Show resolved Hide resolved
src/pages/home/report/ReportActionItemMessageEdit.js Outdated Show resolved Hide resolved
src/pages/home/report/ReportActionItemMessageEdit.js Outdated Show resolved Hide resolved
src/pages/home/report/ReportActionItemMessageEdit.js Outdated Show resolved Hide resolved
@kushu7 kushu7 requested a review from roryabraham June 7, 2023 03:10
@kushu7
Copy link
Contributor Author

kushu7 commented Jun 7, 2023

@roryabraham Please re-review once, I have applied changes.

roryabraham
roryabraham previously approved these changes Jun 7, 2023
Copy link
Contributor

@roryabraham roryabraham left a comment

Choose a reason for hiding this comment

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

Looks better to me, but let's get the C+ review here for testing.

@roryabraham roryabraham requested a review from s77rt June 7, 2023 04:50
const emojiButtonID = 'emojiButton';
const messageEditInput = 'messageEditInput';

function ReportActionItemMessageEdit({action, forwardedRef, draftMessage, index, isKeyboardShown, isSmallScreenWidth, preferredSkinTone, reportID, shouldDisableEmojiPicker, translate}) {
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 against our style guidance. Use props as the function parameter and do not destruct the props, just use props.action, props.forwardedRef, etc.

Comment on lines +103 to +109
setDraft((prevDraft) => {
setSelection({
start: prevDraft.length,
end: prevDraft.length,
});
return prevDraft;
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Do we have to call setDraft to access the previous draft? Is there any other options here?

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 are setting old value to setDraft method. it will not cause re-render.

though we can directly access draft value and use it. as we just have to do it at mount only:

setSelection({
            start: draft.length,
            end: draft.length,
        });

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@s77rt need your input on this.

Copy link
Contributor

Choose a reason for hiding this comment

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

I don't think using draft will work, we will have to add it as a dependency.
Maybe we should just keep it as it's now?

@yuwenmemon Any thoughts on this?

Comment on lines 112 to 125
useEffect(
() => () => {
// Skip if this is not the focused message so the other edit composer stays focused.
if (!isFocused) {
return;
}

/**
* Update Selection on change cursor position.
*
* @param {Event} e
*/
onSelectionChange(e) {
this.setState({selection: e.nativeEvent.selection});
}
// Show the main composer when the focused message is deleted from another client
// to prevent the main composer stays hidden until we swtich to another chat.
ComposerActions.setShouldShowComposeInput(true);
},
// eslint-disable-next-line react-hooks/exhaustive-deps -- for willUnmount lifecycle
[],
);
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 remove this useEffect and just use the previous one?
One useEffect can handle both componentDidMount and componentWillUnmount phases.

updateDraft(draft) {
const {text: newDraft = '', emojis = []} = EmojiUtils.replaceEmojis(draft, this.props.isSmallScreenWidth, this.props.preferredSkinTone);
const updateDraft = useCallback(
(newDraftValue) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

NAB can you please change the variable name to newDraftInput.

Comment on lines 152 to 161
if (newDraftValue !== newDraft) {
setSelection((prevSelection) => {
const remainder = draft.slice(prevSelection.end).length;
return {
start: newDraft.length - remainder,
end: newDraft.length - remainder,
};
});
}
setDraft(newDraft);
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 rewrite this as:

            setDraft((prevDraft) => {
                if (newDraftValue !== newDraft) {
                    setSelection((prevSelection) => {
                        const remainder = prevDraft.slice(prevSelection.end).length;
                        return {
                            start: newDraft.length - remainder,
                            end: newDraft.length - remainder,
                        };
                    });
                }
                return newDraft;
            });

Comment on lines 221 to 230
const addEmojiToTextBox = useCallback(
(emoji) => {
setSelection((prevSelection) => ({
start: prevSelection.start + emoji.length,
end: prevSelection.start + emoji.length,
}));
updateDraft(ComposerUtils.insertText(draft, selection, emoji));
},
[draft, selection, updateDraft],
);
Copy link
Contributor

Choose a reason for hiding this comment

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

In which cases the component would re-render and have same draft and selection? I don't think this is common so the useCallback may be a bad choice here since we will mostly end up redefining the function.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

So should i remove useCallback here?

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes

@yuwenmemon yuwenmemon self-requested a review June 7, 2023 15:01
@s77rt
Copy link
Contributor

s77rt commented Jun 7, 2023

@kushu7 Can you please push commits for requested changes that we agreed on

@kushu7
Copy link
Contributor Author

kushu7 commented Jun 7, 2023

@kushu7 Can you please push commits for requested changes that we agreed on

Just pushed, Please review it.

@kushu7 kushu7 requested a review from s77rt June 7, 2023 15:58
Comment on lines 111 to 122
return () => {
// Skip if this is not the focused message so the other edit composer stays focused.
if (!isFocused) {
return;
}

/**
* Update Selection on change cursor position.
*
* @param {Event} e
*/
onSelectionChange(e) {
this.setState({selection: e.nativeEvent.selection});
}
// Show the main composer when the focused message is deleted from another client
// to prevent the main composer stays hidden until we swtich to another chat.
ComposerActions.setShouldShowComposeInput(true);
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- we need it to call it once on mount
}, []);
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 about the cleanup function here. Won't isFocused always be false (as that's it's initial state).

The cleanup function is evaluated now but executed later or am I missing something?

Copy link
Contributor Author

@kushu7 kushu7 Jun 7, 2023

Choose a reason for hiding this comment

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

It will get latest value.
Deps array particularly we use when we have to do something when deps are changing.

In cleanup. Function will get latest value of isFocused not initial value

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@s77rt you are right, we should replace it by useRef. as ref will always return latest value.

const textInputRef = useRef(null);
const isFocusedRef = useRef(false);

    useEffect(() => {
        // For mobile Safari, updating the selection prop on an unfocused input will cause it to automatically gain focus
        // and subsequent programmatic focus shifts (e.g., modal focus trap) to show the blue frame (:focus-visible style),
        // so we need to ensure that it is only updated after focus.
        setDraft((prevDraft) => {
            setSelection({
                start: prevDraft.length,
                end: prevDraft.length,
            });
            return prevDraft;
        });

        return () => {
            // Skip if this is not the focused message so the other edit composer stays focused.
            if (!isFocusedRef.current) {
                return;
            }

            // Show the main composer when the focused message is deleted from another client
            // to prevent the main composer stays hidden until we swtich to another chat.
            ComposerActions.setShouldShowComposeInput(true);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps -- we need it to call it once on mount
    }, []);

and in composer props

onFocus={() => {
                                setIsFocused(true);
                                isFocusedRef.current = true;
                                ReportScrollManager.scrollToIndex({animated: true, index: props.index}, true);
                                ComposerActions.setShouldShowComposeInput(false);
                            }}
                            onBlur={(event) => {
                                setIsFocused(false);
                                isFocusedRef.current = false;

What do you say?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Copy link
Contributor

Choose a reason for hiding this comment

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

This works but it's not ideal to have two variables that hold the same value. Let's fix it in another way

Copy link
Contributor

Choose a reason for hiding this comment

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

Unfortunately this is not working as expected. The isFocused method seems to return false where the isFocused state is still set to true. This will reintroduce this bug #16623.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@s77rt are you sure? I tested by console.log
In another useEffect method with isFocused as deps.

Both were showing same value. And textInput.isFocused() is already used in some components.

Copy link
Contributor

Choose a reason for hiding this comment

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

Kooha-2023-06-08-12-23-47.mp4

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Screenshot 2023-06-08 at 5 39 53 PM

I got it now as unmount state ( cleanup fn) we process using previous state. but isFocused() return us current state of component.

I think we proceed with ref variable for keeping focus state. as its synced with isFocused state.

const isFocusedRef = useRef(false);

useEffect(() => {
        isFocusedRef.current = isFocused
    }, [isFocused])

@s77rt what do you think?

Copy link
Contributor

Choose a reason for hiding this comment

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

I don't think this is the ideal approach, there could be an easy solution that we are missing. Can you please ask on Slack, given that there is many ongoing functional refactor maybe someone encountered a similar case.

@kushu7 kushu7 requested a review from s77rt June 8, 2023 05:01
@kushu7
Copy link
Contributor Author

kushu7 commented Jun 12, 2023

@s77rt Please have a look, I have pushed the changes.

// to prevent the main composer stays hidden until we swtich to another chat.
ComposerActions.setShouldShowComposeInput(true);
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- we need it to call it once on mount
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
// eslint-disable-next-line react-hooks/exhaustive-deps -- we need it to call it once on mount

Not needed, we are using a ref now and it always have the same value so no need for it to be a dependency (and no error will be thrown).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Forgot about it. I have removed it now.

@kushu7 kushu7 requested a review from s77rt June 12, 2023 15:46
@s77rt
Copy link
Contributor

s77rt commented Jun 12, 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 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
web.mp4
Mobile Web - Chrome
mweb-chrome.mp4
Mobile Web - Safari
mweb-safari.mp4
Desktop
desktop.mp4
iOS
ios.mp4
Android
android.mp4

@kushu7 kushu7 requested a review from roryabraham June 13, 2023 19:41
@@ -1,6 +1,7 @@
/* eslint-disable rulesdir/onyx-props-must-have-default */
import lodashGet from 'lodash/get';
import React from 'react';
import React, {useState, useRef, useMemo, useEffect, useCallback} from 'react';
// eslint-disable-next-line no-restricted-imports
Copy link
Contributor

Choose a reason for hiding this comment

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

There are no restricted imports on the next line AFAICT, so let's remove this:

Suggested change
// eslint-disable-next-line no-restricted-imports

}

ReportActionItemMessageEdit.propTypes = propTypes;
ReportActionItemMessageEdit.defaultProps = defaultProps;
ReportActionItemMessageEdit.displayName = 'ReportActionItemMessageEdit';
export default compose(
withLocalize,
Copy link
Contributor

Choose a reason for hiding this comment

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

It was reverted for an unrelated reason, but let's re-introduce the useLocalize hook from #20708 and use it here instead of withLocalize.

}

ReportActionItemMessageEdit.propTypes = propTypes;
ReportActionItemMessageEdit.defaultProps = defaultProps;
ReportActionItemMessageEdit.displayName = 'ReportActionItemMessageEdit';
export default compose(
withLocalize,
withWindowDimensions,
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 also use useWindowDimensions hook from src/hooks instead of withWindowDimensions. Also don't forget to remove the unused props from these HOCs when you remove them

Copy link
Contributor

Choose a reason for hiding this comment

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

Lastly, let's also add a very simple useKeyboardState hook in src/hooks:

export default function useKeyboardState() {
    const [isKeyboardShown, setIsKeyboardShown] = useState(false);
    useEffect(() => {
        const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => setIsKeyboardShown(true));
        return keyboardDidShowListener.remove;
    }, []);
    useEffect(() => {
        const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => setIsKeyboardShown(false));
        return keyboardDidHideListener.remove;
    }, []);
    return {
        isKeyboardShown,
    };
}

Then use it like this:

const {isKeyboardShown} = useKeyboardState();

And then remove the withKeyboardState HOC and props.

Copy link
Contributor

Choose a reason for hiding this comment

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

We should get used to using hooks more as we migrate to a functional react style because they're often simpler to read, simpler to use, simpler to type once we start migrating everything to TypeScript, and don't bloat the component tree as much as HOCs.

Copy link
Contributor

Choose a reason for hiding this comment

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

Actually, I see we have a context for withKeyboardState that's preventing us from setting up duplicate listeners. So the useKeyboardState hook becomes even simpler. Just:

  1. Export KeyboardStateContext from withKeyboardState

  2. Implement useKeyboardState like so:

    import {useContext} from 'react';
    import {KeyboardStateContext} from '../components/withKeyboardState';
    
    export default function useKeyboardState() {
        return useContext(KeyboardStateContext);
    }

@kushu7 kushu7 requested a review from roryabraham June 13, 2023 20:35
@kushu7
Copy link
Contributor Author

kushu7 commented Jun 13, 2023

Why Lint getting failed. weird 👀
No error on local
Error: 35:25 error Missing file extension for "../../../hooks/useLocalize" import/extensions

@roryabraham
Copy link
Contributor

@kushu7 it looks like you need to:

  1. Merge main
  2. Commit + push the useLocalize hook

@kushu7
Copy link
Contributor Author

kushu7 commented Jun 13, 2023

  1. Merge main
  2. Commit + push the useLocalize hook

Thanks, I was behind.

src/hooks/useKeyboardState.js Show resolved Hide resolved
src/pages/home/report/ReportActionItemMessageEdit.js Outdated Show resolved Hide resolved
// to prevent the main composer stays hidden until we swtich to another chat.
ComposerActions.setShouldShowComposeInput(true);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
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 unsure whether the cleanup function will behave as you expect without wasPreviouslyFocused being a dependency 🤔

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're okay here, but honestly not 100% sure.

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 I'm just thrown off because eslint knows that if you do this:

const myRef = useRef(1);
useEffect(() => {
   console.log(`Do something with ${myRef.current}`);
}, []);

Then you don't have to pass myRef or myRef.current as a dependency to the useEffect. That's exactly what we're doing here, but eslint is thrown off because it doesn't know what usePrevious is doing and doesn't know it's just returning aRef.current under the hood.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@roryabraham I tested through. I can conclude. It will not work. it holds previous value, but require wasPreviouslyFocused to add in deps array.
I tested using that focus bug, its failing.
My thought was also same as yours. as we were moving only logic to usePreviousHook.

usePreviousHook is hook good when we require to check old value. but its require to add it in deps array. but in our case we can't use it as we are performing componentWillUnmount action.
Code i used to test current state at cleanup function.

const wasPreviouslyFocused = usePrevious(isFocused);
    const isFocusedRef = useRef(false);

    useEffect(() => {
        // required for keeping last state of isFocused variable
        isFocusedRef.current = isFocused;
        console.log(wasPreviouslyFocused,'<-SYNC-CHECK->',isFocused,'----',isFocusedRef.current)
    }, [isFocused]);

    useEffect(()=>{
        return ()=>{
            console.log('cleanup with dep',wasPreviouslyFocused, '-it should be isFocusedRef.current',isFocusedRef.current)
        }
    },[wasPreviouslyFocused])

    useEffect(()=>{
        return ()=>{
            console.log('cleanup without dep value',wasPreviouslyFocused,'-it should be isFocusedRef.current',isFocusedRef.current)
        }
    },[])


useEffect(() => {
        // For mobile Safari, updating the selection prop on an unfocused input will cause it to automatically gain focus
        // and subsequent programmatic focus shifts (e.g., modal focus trap) to show the blue frame (:focus-visible style),
        // so we need to ensure that it is only updated after focus.
        setDraft((prevDraft) => {
            setSelection({
                start: prevDraft.length,
                end: prevDraft.length,
            });
            return prevDraft;
        });

        return () => {
            // Skip if this is not the focused message so the other edit composer stays focused
            console.log(wasPreviouslyFocused,'<-SYNC-CHECK CLEANUP VALUE->',isFocused,'---',isFocusedRef.current)
            if (!wasPreviouslyFocused) {
                return;
            }

            // Show the main composer when the focused message is deleted from another client
            // to prevent the main composer stays hidden until we swtich to another chat.
            ComposerActions.setShouldShowComposeInput(true);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
Testing with usePrevious
Screen.Recording.2023-06-14.at.11.01.50.AM.mov

Copy link
Contributor

Choose a reason for hiding this comment

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

Thanks for your thorough re-testing, it's a bummer that usePrevious has this limitation. I imagine it would be a useful hook to build into the core React 🤔

@kushu7 kushu7 requested review from s77rt and roryabraham June 14, 2023 05:44
@kushu7
Copy link
Contributor Author

kushu7 commented Jun 14, 2023

@s77rt As this migration got many changes after last testing, I request to Re-test also at your end also. I have tested through it.

cc @roryabraham @yuwenmemon

Copy link
Contributor

@s77rt s77rt left a comment

Choose a reason for hiding this comment

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

Retested. Working well from my end.

cc @yuwenmemon

Copy link
Contributor

@yuwenmemon yuwenmemon left a comment

Choose a reason for hiding this comment

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

All yours @roryabraham

Copy link
Contributor

@roryabraham roryabraham left a comment

Choose a reason for hiding this comment

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

Thanks for all those changes @kushu7 and your thorough testing. LGTM 👍🏼

@roryabraham roryabraham merged commit 19b408c into Expensify:main Jun 14, 2023
15 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.

@kushu7 kushu7 deleted the migarate-report-action-item-message-edit-to-functional branch June 14, 2023 17:49
@OSBotify
Copy link
Contributor

🚀 Deployed to staging by https://github.com/roryabraham in version: 1.3.28-0 🚀

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

@OSBotify
Copy link
Contributor

🚀 Deployed to production by https://github.com/AndrewGable in version: 1.3.28-5 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 success ✅
🕸 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.

None yet

5 participants