如何为Facebook Messenger这样的聊天应用实现React无限滚动组件?

时间:2019-07-10 10:12:10

标签: javascript reactjs chat

我知道关于此主题有很多问题(“无限滚动”), 我的问题旨在更加深入,以便确定实现此类组件的当前最佳可用解决方案。

我正在使用聊天应用程序,并且创建了类似于Facebook的Messenger聊天窗口的组件,您可以在桌面浏览器上看到它。

Facebook:

enter image description here

我的(到目前为止):

enter image description here enter image description here

用无限负载实现无限滚动确实很棘手。 从用户体验的角度来看,我需要始终至少满足以下属性:

  1. 每行消息的高度应实时动态计算,因为我不知道消息的高度,因为它们没有固定的高度;
  2. 无论何时用户键入新消息,滚动都必须自动到达可滚动组件的底部,直到最后发送的消息。可滚动组件本身具有顶部和底部填充(或者我也可以使用边距),以便在聊天的顶部和底部,底部和最后一条消息之间留出一些空间(请参见上面的图像); < / li>
  3. 聊天位于popover元素内,该元素以淡入淡出的动画形式打开,用户可以在使用页面时关闭和打开它;

现在,为了做到这一点,我已经尝试了几个库:

  • react-infinite:我的第一次尝试被放弃,因为它需要提前知道所有元素的高度;
  • react-list:我发现它确实很强大,问题是,如果我关闭弹出窗口并在有时丢失一些已经呈现的消息后重新打开它,在我看来,这可能是{{ 1}}组件。另外,该组件不允许我向上显示滚动底部(请参见https://github.com/coderiety/react-list/issues/50);
  • react-virtualized:功能非常强大,但是我发现将react-listList以及InfiniteLoaderAutoSizerCellMeasurer一起使用时比较棘手。另外,如果我调用CellMeasurerCache来自动将容器滚动到底部时发送消息,则滚动无法完全到达底部,因为可滚动容器具有顶部和底部填充。使用此组件我无法获得令人满意的结果。
  • react-infinite-any-height:我想尝试一下,但是目前看来,如果我安装它,它还没有移植到React 16上NPM警告我关于React 15的对等依赖关系不满意,但是我使用React 16。

所以我的问题更多是一种相互面对的方式:你们中的某个人是否曾经实现过我上面编写的3个需求的React聊天组件?您使用什么图书馆? 当Facebook Messenger处理得很好并且他们使用React时,你们中有人知道他们是如何实现这种组件的吗?如果我检查Facebook聊天窗口的聊天消息,似乎它会将所有已呈现的消息保留在DOM中。但是,如果是这样,这不会影响性能吗?

因此,我目前的问题多于答案。我真的很想找到适合我需求的组件。另一种选择是实施我自己的。

1 个答案:

答案 0 :(得分:3)

我最终实现了自己的非常简单的无限滚动组件(不过还没有重构它以使用钩子):


import React from "react";
import {
    isUndefined,
    hasVerticalScrollbar,
    hasHorizontalScrollbar,
    isInt,
    debounce
} from "js-utl";
import { classNames } from "react-js-utl/utils";

export default class SimpleInfiniteScroll extends React.Component {
    constructor(props) {
        super(props);

        this.handleScroll = this.handleScroll.bind(this);
        this.onScrollStop = debounce(this.onScrollStop.bind(this), 100);

        this.itemsIdsRefsMap = {};
        this.isLoading = false;
        this.isScrolling = false;
        this.lastScrollStopPromise = null;
        this.lastScrollStopPromiseResolve = null;

        this.node = React.createRef();
    }

    componentDidMount() {
        this.scrollToStart();
    }

    getNode() {
        return this.node && this.node.current;
    }

    getSnapshotBeforeUpdate(prevProps) {
        if (prevProps.children.length < this.props.children.length) {
            const list = this.node.current;
            const axis = this.axis();
            const scrollDimProperty = this.scrollDimProperty(axis);
            const scrollProperty = this.scrollProperty(axis);
            const scrollDelta = list[scrollDimProperty] - list[scrollProperty];

            return {
                scrollDelta
            };
        }
        return null;
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (
            this.isLoading &&
            ((prevProps.isInfiniteLoading && !this.props.isInfiniteLoading) ||
                ((this.props.hasMore || prevProps.hasMore) &&
                    prevProps.children.length !==
                        this.props.children.length)) &&
            snapshot
        ) {
            if (this.props.displayInverse) {
                const list = this.node.current;
                const axis = this.axis();
                const scrollDimProperty = this.scrollDimProperty(axis);
                const scrollProperty = this.scrollProperty(axis);
                const scrollDelta = snapshot.scrollDelta;
                const scrollTo = list[scrollDimProperty] - scrollDelta;

                this.scrollTo(scrollProperty, scrollTo);
            }
            this.isLoading = false;
        }
    }

    loadingComponentRenderer() {
        const { loadingComponent } = this.props;

        return (
            <div
                className="simple-infinite-scroll-loading-component"
                key={-2}
            >
                {loadingComponent}
            </div>
        );
    }

    axis() {
        return this.props.axis === "x" ? "x" : "y";
    }

    scrollProperty(axis) {
        return axis === "y" ? "scrollTop" : "scrollLeft";
    }

    offsetProperty(axis) {
        return axis === "y" ? "offsetHeight" : "offsetWidth";
    }

    clientDimProperty(axis) {
        return axis === "y" ? "clientHeight" : "clientWidth";
    }

    scrollDimProperty(axis) {
        return axis === "y" ? "scrollHeight" : "scrollWidth";
    }

    hasScrollbarFunction(axis) {
        return axis === "y" ? hasVerticalScrollbar : hasHorizontalScrollbar;
    }

    scrollToStart() {
        const axis = this.axis();
        this.scrollTo(
            this.scrollProperty(axis),
            !this.props.displayInverse ? 0 : this.scrollDimProperty(axis)
        );
    }

    scrollToEnd() {
        const axis = this.axis();
        this.scrollTo(
            this.scrollProperty(axis),
            !this.props.displayInverse ? this.scrollDimProperty(axis) : 0
        );
    }

    scrollTo(scrollProperty, scrollPositionOrPropertyOfScrollable) {
        const scrollableContentNode = this.node.current;
        if (scrollableContentNode) {
            scrollableContentNode[scrollProperty] = isInt(
                scrollPositionOrPropertyOfScrollable
            )
                ? scrollPositionOrPropertyOfScrollable
                : scrollableContentNode[scrollPositionOrPropertyOfScrollable];
        }
    }

    scrollToId(id) {
        if (this.itemsIdsRefsMap[id] && this.itemsIdsRefsMap[id].current) {
            this.itemsIdsRefsMap[id].current.scrollIntoView();
        }
    }

    scrollStopPromise() {
        return (
            (this.isScrolling && this.lastScrollStopPromise) ||
            Promise.resolve()
        );
    }

    onScrollStop(callback) {
        callback();
        this.isScrolling = false;
        this.lastScrollStopPromise = null;
        this.lastScrollStopPromiseResolve = null;
    }

    handleScroll(e) {
        const {
            isInfiniteLoading,
            hasMore,
            infiniteLoadBeginEdgeOffset,
            displayInverse
        } = this.props;

        this.isScrolling = true;
        this.lastScrollStopPromise =
            this.lastScrollStopPromise ||
            new Promise(resolve => {
                this.lastScrollStopPromiseResolve = resolve;
            });
        this.onScrollStop(() => {
            this.lastScrollStopPromiseResolve &&
                this.lastScrollStopPromiseResolve();
        });

        this.props.onScroll && this.props.onScroll(e);

        if (
            this.props.onInfiniteLoad &&
            (!isUndefined(hasMore) ? hasMore : !isInfiniteLoading) &&
            this.node.current &&
            !this.isLoading
        ) {
            const axis = this.axis();
            const scrollableContentNode = this.node.current;
            const scrollProperty = this.scrollProperty(axis);
            const offsetProperty = this.offsetProperty(axis);
            const scrollDimProperty = this.scrollDimProperty(axis);
            const currentScroll = scrollableContentNode[scrollProperty];
            const currentDim = scrollableContentNode[offsetProperty];
            const scrollDim = scrollableContentNode[scrollDimProperty];

            const finalInfiniteLoadBeginEdgeOffset = !isUndefined(
                infiniteLoadBeginEdgeOffset
            )
                ? infiniteLoadBeginEdgeOffset
                : currentDim / 2;

            let thresoldWasReached = false;
            if (!displayInverse) {
                const clientDimProperty = this.clientDimProperty(axis);
                const clientDim = scrollableContentNode[clientDimProperty];
                thresoldWasReached =
                    currentScroll +
                        clientDim +
                        finalInfiniteLoadBeginEdgeOffset >=
                    scrollDim;
            } else {
                thresoldWasReached =
                    currentScroll <= finalInfiniteLoadBeginEdgeOffset;
            }
            if (thresoldWasReached) {
                this.isLoading = true;
                this.props.onInfiniteLoad();
            }
        }
    }

    render() {
        const {
            children,
            displayInverse,
            isInfiniteLoading,
            className,
            hasMore
        } = this.props;

        return (
            <div
                className={classNames("simple-infinite-scroll", className)}
                ref={this.node}
                onScroll={this.handleScroll}
                onMouseOver={this.props.onInfiniteScrollMouseOver}
                onMouseOut={this.props.onInfiniteScrollMouseOut}
                onMouseEnter={this.props.onInfiniteScrollMouseEnter}
                onMouseLeave={this.props.onInfiniteScrollMouseLeave}
            >
                {(hasMore || isInfiniteLoading) &&
                    displayInverse &&
                    this.loadingComponentRenderer()}
                {children}
                {(hasMore || isInfiniteLoading) &&
                    !displayInverse &&
                    this.loadingComponentRenderer()}
            </div>
        );
    }
}

然后在this.props.children中,将扩展了React.PureComponent的以下组件类的React元素数组传递给它:

...

export default class ChatMessage extends React.PureComponent {
    ...
}

这样,在重新渲染时,仅重新渲染自上次渲染以来已更改的组件。

我还使用了不可变的数据结构来存储聊天消息的集合,尤其是immutable-linked-ordered-maphttps://github.com/tonix-tuft/immutable-linked-ordered-map),这使我可以实现O(1)的插入,删除时间复杂度消息的更新,以及几乎O(1)的查找时间。 本质上,ImmutableLinkedOrderedMap是一个有序的不可变映射,就像PHP中的关联数组一样,但是不可变:


const map = new ImmutableLinkedOrderedMap({
    mode: ImmutableLinkedOrderedMap.MODE.MULTIWAY,
    initialItems: [
        {
            id: 1, // <--- "[keyPropName] === 'id'"
            text: "Message text",
            // ...
        },
        {
            id: 2,
            text: "Another message text",
            // ...
        },
        // ...
    ]
})
map.get(2) // Will return: { id: 2, text: "Another message text", /* ... */ }
const newMessage = { id: 3, text: "Yet another message text", /* ... */ };
const newMap = map.set(newMessage);

console.log(map !== newMap); // true
console.log(map.length); // 2
console.log(newMap.length); // 3

let messages = newMap.replace(3, newMessage)
console.log(messages === newMap); // true, because newMessage with ID 3 didn't change
messages = newMap.replace(3, { ...newMessage, read: true })
console.log(messages === newMap); // false


然后,当我渲染存储在地图中的消息时,我只需调用其.values()方法即可,该方法返回一个数组,然后我将该数组映射为渲染消息,例如:


<SimpleInfiniteScroll>
    {messages.values().map((message) => <ChatMessage ... />)}
</SimpleInfiniteScroll>