App icon indicating copy to clipboard operation
App copied to clipboard

Fix `Inverted`prop on the `FlatList`component with a RN Patch

Open mallenexpensify opened this issue 5 years ago • 142 comments

If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] to request to join our Slack channel!


Expected Result:

  • When copying text in e.cash that when you highlight lines of text, including across multiple messages, that the text is highlighted in order from top to bottom or bottom to top.
  • When pasting text that has been copied in e.cash, that it shows up in the correct order.

Actual Result:

  • Copying is sporadic and 'jumps around' when you highlight text over multiple messages. View video example at https://www.screencast.com/t/AzFBzTDs3ESm
    image

  • Pasting - When pasting copied text from multiple e.cash messages, it's out of order

image

Action Performed:

  • Open Web or Desktop
  • Create multiple messages in a test account (ie. 1 , click enter, 2, click enter, etc)
  • Attempt to copy the multiple messages, observe you can't easily copy them in the correct order.
  • Once you've been able to capture some of the multiple messages, paste in the compose box
  • Observe the messages paste out of order.

Workaround:

The work around is to copy single messages at a time.

Platform:

Where is this issue occurring?

Web ✅ iOS Android Desktop App ✅ Mobile Web

Version Number: Version 1.0.62 (the issue has been happening since we launched) Logs: N/A Notes/Photos/Videos:
The deliverable is to fix the core issue (Copying and Pasting on Web and Desktop are weird and out of order). The PR should be submitted against our RN fork (Expensify/react-native). A lot of discussion about this issue is here for additional context https://github.com/Expensify/Expensify.cash/issues/1341

Expensify/Expensify Issue URL: From months ago https://github.com/Expensify/Expensify/issues/142340#

View all open jobs on Upwork

Issue OwnerCurrent Issue Owner: @mallenexpensify

mallenexpensify avatar Jun 04 '21 18:06 mallenexpensify

Triggered auto assignment to @kadiealexander (AutoAssignerTriage), see https://stackoverflow.com/c/expensify/questions/4749 for more details.

MelvinBot avatar Jun 04 '21 18:06 MelvinBot

Triggered auto assignment to @thienlnam (Engineering), see https://stackoverflow.com/c/expensify/questions/4319 for more details.

MelvinBot avatar Jun 04 '21 18:06 MelvinBot

@thienlnam we plan to have a contributor work on this, can you review to ensure I didn't miss anything then add the External label? Thanks

mallenexpensify avatar Jun 04 '21 18:06 mallenexpensify

Triggered auto assignment to @trjExpensify (External), see https://stackoverflow.com/c/expensify/questions/8582 for more details.

MelvinBot avatar Jun 07 '21 15:06 MelvinBot

@mallenexpensify Sorry, was OOO but issue looks good and we can have a contributor start working on it. Nice detailed write-up!

thienlnam avatar Jun 07 '21 15:06 thienlnam

~Posted at $2000 https://www.upwork.com/jobs/~01953cb695d659063b~ ~Raised to $4000 and created a new job https://www.upwork.com/jobs/~014c8ddadb545a60f4~ Raised to $8000 and updated title to React Native - Fix Inverted prop on the FlatList component with a RN Patch #3381 Expensify. https://www.upwork.com/jobs/~01a4a59d0c8d74eae5

mallenexpensify avatar Jun 10 '21 15:06 mallenexpensify

Hello,

I was checking this issue in the web version of the expensify.cash and noticed that the chat messages are deeply nested in divs. My first action towards fixing this issue would be trying to streamline this chat to make sure there are less areas of conflit between the messages.

However, if I also remember it right, it is an expensify policy not to have different code for web/android/ios etc. Is that still the case? Since I can imagine the reason for this complexity might be special needs of the mobile platforms.

FredericoGauz avatar Jun 20 '21 13:06 FredericoGauz

Hi! it seems that the problem is in prop inverted of FlatList. This prop used transform: scaleX: -1

Viacheslav80 avatar Jun 21 '21 09:06 Viacheslav80

@FredericoGauz

My first action towards fixing this issue would be trying to streamline this chat to make sure there are less areas of conflit between the messages.

Can you clarify what you mean by this? What are "areas of conflict" between the messages?

However, if I also remember it right, it is an expensify policy not to have different code for web/android/ios etc. Is that still the case?

We allow different code for platform specific changes, but try to dry it up so only the part that needs to be platform specific is separated out and the changes are in different platform specific file extensions. Feel free to read more information on it here

thienlnam avatar Jun 21 '21 15:06 thienlnam

@Viacheslav80

Hi! it seems that the problem is in prop inverted of FlatList. This prop used transform: scaleX: -1

I'm pretty sure that this is to display the chat messages in inverse order - can you verify that this doesn't change the functionality of the chat messages and doesn't break anything else?

thienlnam avatar Jun 21 '21 15:06 thienlnam

@thienlnam I agree with you. this prop is the easiest way to do infinite scrolling with the addition of an element at the bottom

Viacheslav80 avatar Jun 21 '21 16:06 Viacheslav80

Raised to $4000 and created a new job https://www.upwork.com/jobs/~014c8ddadb545a60f4

mallenexpensify avatar Jun 23 '21 22:06 mallenexpensify

@Viacheslav80 Is right, the prop inverted of Flatlist applies scaleY: -1 (specifically Y and not X), this causes a problem similar to that of flexbox's -reverse or order attribute known as html order vs css order. This is mainly a concern for website's accessibly - screen readers and keyboard navigation will follow the html order and not visual css one. However, it also breaks the mouse selection and copy-paste order (the actual issue in question). See my little fiddle for a simple demo. Try to select and copy-paste and you will the exact thing reported in the OP.

Proposal

To solve the issue I propose to avoid usage of Flatlist's inverted prop and pass the array of messages to Flatlist in their actual order (older first, newest last). I checked how other chat apps are doing it and they are not inverting the order of messages either. See for yourself, inspect the last message in slack or mattermost web app, and you'll see that it's the last block in it's parent div.

As a quick demo I removed the inverted prop in BaseInvertedFlatList.js as well as reversed the data array: data={this.props.data.reverse()}, also I had to remove the scaleY(-1) here and I got this result:

https://user-images.githubusercontent.com/64093836/123218109-fe072080-d4d3-11eb-92e2-325393480133.mp4

Now there is obviously more to it:

  1. Make sure that chat is scrolled all the way to the bottom by default.
  2. Remove reverse mouse wheel scrolling
  3. Try to benchmark the impact of this.props.data.reverse(). If it's too much I'll need to find another way to do it.
  4. Make sure the messages are bundled together in a correct way (when one person sends multiple messages, only the first message should show the avatar and date).
  5. Think about android and iOS, maybe it's worth it to ditch the usage of inverted list there too. Should help with accessibility if that's a concern.

There might be more todos. These are just the ones that are on my mind right now.

Anyway, I believe that since it is a common practice to not invert the message list visually in chat apps, I shouldn't run into any pitfalls. If anything, I will always be able to take a peek at mattermost source code (an open-source self-hosted slack alternative).

dklymenk avatar Jun 24 '21 07:06 dklymenk

Proposal

As we know the issue is the inverted prop in the FlatList component, so my solution is to implementing the inverted FlatList virtually in the BaseInvertedFlatList.js file.

I have changed the BaseInvertedFlatList component so that the inverted feature is implemented and we don't need to change the other part of the source code used the BaseInvertedFlatList component.

New BaseInvertedFlatList component

the renderItem method is reimplemented.

/* eslint-disable react/jsx-props-no-multi-spaces */
import _ from 'underscore';
import React, {forwardRef, Component} from 'react';
import PropTypes from 'prop-types';
import {FlatList, View} from 'react-native';
import {lastItem} from '../../libs/CollectionUtils';

const propTypes = {
    /** Same as FlatList can be any array of anything */
    data: PropTypes.arrayOf(PropTypes.any),

    /** Same as FlatList although we wrap it in a measuring helper before passing to the actual FlatList component */
    renderItem: PropTypes.func.isRequired,

    /** This must be set to the minimum size of one of the renderItem rows. Web experiences issues when inaccurate. */
    initialRowHeight: PropTypes.number.isRequired,

    /** Passed via forwardRef so we can access the FlatList ref */
    innerRef: PropTypes.oneOfType([
        PropTypes.func,
        PropTypes.shape({current: PropTypes.instanceOf(FlatList)}),
    ]).isRequired,

    /** Should we measure these items and call getItemLayout? */
    shouldMeasureItems: PropTypes.bool,

    /** Should we remove the clipped sub views? */
    shouldRemoveClippedSubviews: PropTypes.bool,
};

const defaultProps = {
    data: [],
    shouldMeasureItems: false,
    shouldRemoveClippedSubviews: false,
};

class BaseInvertedFlatList extends Component {
    constructor(props) {
        super(props);

        this.renderItem = this.renderItem.bind(this);
        this.getItemLayout = this.getItemLayout.bind(this);

        // Stores each item's computed height after it renders
        // once and is then referenced for the life of this component.
        // This is essential to getting FlatList inverted to work on web
        // and also enables more predictable scrolling on native platforms.
        this.sizeMap = {};
    }

    /**
     * Return default or previously cached height for
     * a renderItem row
     *
     * @param {*} data
     * @param {Number} index
     *
     * @return {Object}
     */
    getItemLayout(data, index) {
        const size = this.sizeMap[index];

        if (size) {
            return {
                length: size.length,
                offset: size.offset,
                index,
            };
        }

        // If we don't have a size yet means we haven't measured this
        // item yet. However, we can still calculate the offset by looking
        // at the last size we have recorded (if any)
        const lastMeasuredItem = lastItem(this.sizeMap);

        return {
            // We haven't measured this so we must return the minimum row height
            length: this.props.initialRowHeight,

            // Offset will either be based on the lastMeasuredItem or the index +
            // initialRowHeight since we can only assume that all previous items
            // have not yet been measured
            offset: _.isUndefined(lastMeasuredItem)
                ? this.props.initialRowHeight * index
                : lastMeasuredItem.offset + this.props.initialRowHeight,
            index,
        };
    }

    /**
     * Measure item and cache the returned length (a.k.a. height)
     *
     * @param {React.NativeSyntheticEvent} nativeEvent
     * @param {Number} index
     */
    measureItemLayout(nativeEvent, index) {
        const computedHeight = nativeEvent.layout.height;

        // We've already measured this item so we don't need to
        // measure it again.
        if (this.sizeMap[index]) {
            return;
        }

        const previousItem = this.sizeMap[index - 1] || {};

        // If there is no previousItem this can mean we haven't yet measured
        // the previous item or that we are at index 0 and there is no previousItem
        const previousLength = previousItem.length || 0;
        const previousOffset = previousItem.offset || 0;
        this.sizeMap[index] = {
            length: computedHeight,
            offset: previousLength + previousOffset,
        };
    }

    /**
     * Render item method wraps the prop renderItem to render in a
     * View component so we can attach an onLayout handler and
     * measure it when it renders.
     *
     * @param {Object} params
     * @param {Object} params.item
     * @param {Number} params.index
     *
     * @return {React.Component}
     */
    renderItem({item, index}) {
        const {data=[]}=this.props;
        const invertedIndex=data.length-index-1;
        const invertedItem=data[invertedIndex];
        if (this.props.shouldMeasureItems) {
            return (
                <View onLayout={({nativeEvent}) => this.measureItemLayout(nativeEvent, invertedIndex)}>
                    {this.props.renderItem({invertedItem, invertedIndex})}
                </View>
            );
        }
        return this.props.renderItem({invertedItem, invertedIndex});
    }

    render() {
        const {style}=this.props;
        return (
            <FlatList
                // eslint-disable-next-line react/jsx-props-no-spreading
                {...this.props}
                style={[style,{justifyContent:'flex-end'}]}
                ref={this.props.innerRef}
                //inverted
                renderItem={this.renderItem}
                // Native platforms do not need to measure items and work fine without this.
                // Web requires that items be measured or else crazy things happen when scrolling.
                getItemLayout={this.props.shouldMeasureItems ? this.getItemLayout : undefined}
                bounces={false}

                // We keep this property very low so that chat switching remains fast
                maxToRenderPerBatch={1}
                windowSize={15}
                removeClippedSubviews={this.props.shouldRemoveClippedSubviews}
            />
        );
    }
}

BaseInvertedFlatList.propTypes = propTypes;
BaseInvertedFlatList.defaultProps = defaultProps;

export default forwardRef((props, ref) => (
    // eslint-disable-next-line react/jsx-props-no-spreading
    <BaseInvertedFlatList {...props} innerRef={ref} />
));

ghorbani-m avatar Jun 24 '21 08:06 ghorbani-m

Thank you both for the very detailed proposals!

@dklymenk I believe we ran into performance issues when reversing the props like that before but now that pagination exists with chats that might be okay but you may need to deal with some changes related to that

It looks like @ghorbani-m's proposal does something similar with changing it back to a regular FlatList and inverting the chats virtually before they are rendered.

Before we accept any proposal here, I'm finding that these proposals would change a fundamental way the chats work right now and want to loop in @kidroca / @roryabraham / @marcaaron who have been looking into bi-directional scrolling and get their thoughts on this

thienlnam avatar Jun 24 '21 17:06 thienlnam

Based on the issue description we are not trying to do any workarounds (past solutions all look like workaround and none have mentioned a RN fork) please see:

The deliverable is to fix the core issue (Copying and Pasting on Web and Desktop are weird and out of order). The PR should be submitted against our RN fork (Expensify/react-native).

marcaaron avatar Jun 24 '21 17:06 marcaaron

The deliverable is to fix the core issue (Copying and Pasting on Web and Desktop are weird and out of order). The PR should be submitted against our RN fork (Expensify/react-native).

Actually, I have completely missed that part. Sorry for that. However, even though I wouldn't call it a bug in react-native, what we can do is change how the inverted prop of Flatlist is implemented in your fork, if that's what you would prefer.

To accomplish that we remove all the scaleY stuff, and just reverse the array order in react-native Flatlist implementation. Ultimately I don't think it matters where we reverse it (in your fork or in Expensify.cash), there will, however, be some cleanup required in Expensify.cash anyway, as I have mentioned in my proposal.

I actually tried the code suggested by @ghorbani-m and it doesn't seem to work at all. I get a bunch of errors in the console and a blank white screen. Not sure what's up with that.

Also, I have to mention that messages stored in LocalStorage are already sorted by sequence number in ascending order, and then a reverse is applied to them in ReportActionsView.js. Additionally, I tried to apply my fix (removing inverted prop and scaleY) without doing an additional reverse and instead I have removed the one in ReportActionsView.js and the fix still worked.

So regardless of your priorities I can do the job, but personally I wouldn't touch the react-native code and just fix the code you have in FE repo.

dklymenk avatar Jun 24 '21 19:06 dklymenk

Thanks, our priority and the deliverable for this issue is to fix the react native code in our fork. If anyone is interested in doing that job (and not a workaround) then please provide a clear proposal for what changes you would make.

marcaaron avatar Jun 24 '21 19:06 marcaaron

Pinged a few contributors in Upwork who submitted proposals there, asked them to post here.

mallenexpensify avatar Jun 28 '21 17:06 mallenexpensify

Triggered auto assignment to @jliexpensify (External), see https://stackoverflow.com/c/expensify/questions/8582 for more details.

MelvinBot avatar Jul 02 '21 21:07 MelvinBot