Home.js 13.4 KB
'use strict';

import React from 'react';
import ReactNative from 'react-native';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Banner from './Banner';
import Notice from './Notice';
import YH_SectionView from './YH_SectionView';
import ListCell from './ListCell';
import UploadProgress from './UploadProgress';
import SuperMan from './SuperMan';
import LoadingIndicator from '../../../common/components/LoadingIndicator';
import LoadMoreIndicator from '../../../common/components/LoadMoreIndicator';
import PropTypes from 'prop-types';


const {
    View,
    Text,
    Image,
    ListView,
    TouchableOpacity,
    RefreshControl,
    Platform,
    StyleSheet,
    Dimensions,
    InteractionManager,
} = ReactNative;

let {width, height} = Dimensions.get('window');
let bannerHeight = Math.ceil((363 / 750) * width);
let sectionHeight = Math.ceil((419 / 750) * width);

export default class Home extends React.Component {

    static propTypes = {

        progressing: ImmutablePropTypes.listOf(
            ImmutablePropTypes.contains({
                uploadState: PropTypes.number.isRequired,
                progress: PropTypes.number,
                image: PropTypes.string,
                onPressRetry: PropTypes.func,
                onPressDelete: PropTypes.func,
            }),
        ),
        banner: ImmutablePropTypes.listOf(
            ImmutablePropTypes.listOf(
                ImmutablePropTypes.contains({
                    src: PropTypes.string.isRequired,
                    url: PropTypes.string,
                }),
            ),
        ),
        notice: ImmutablePropTypes.listOf(
            ImmutablePropTypes.listOf(
                ImmutablePropTypes.contains({
                    title: PropTypes.string.isRequired,
                    url: PropTypes.string,
                }),
            ),
        ),
        section: ImmutablePropTypes.listOf(
            ImmutablePropTypes.listOf(
                ImmutablePropTypes.contains({
                    header: ImmutablePropTypes.contains({
                        id: PropTypes.number.isRequired,
                        logo: PropTypes.string.isRequired,
                        title: PropTypes.string.isRequired,
                        post: PropTypes.string.isRequired,
                        comment: PropTypes.string.isRequired,
                        like: PropTypes.string.isRequired,
                    }),
                    hot: ImmutablePropTypes.contains({
                        postId: PropTypes.number,
                        avatar: PropTypes.string,
                        title: PropTypes.string,
                        content: PropTypes.string.isRequired,
                    }),
                    new: ImmutablePropTypes.contains({
                        postId: PropTypes.number,
                        avatar: PropTypes.string,
                        title: PropTypes.string,
                        content: PropTypes.string.isRequired,
                    }),
                    num: ImmutablePropTypes.contains({
                        onedayAddNum: PropTypes.number.isRequired,
                    }),
                })
            ),
        ),
        recommendation: ImmutablePropTypes.listOf(
            ImmutablePropTypes.contains({
                author: ImmutablePropTypes.contains({
                    avatar: PropTypes.string,
                    uid: PropTypes.number,
                    name: PropTypes.string,
    			}),
                timeago: PropTypes.string.isRequired,
                isOwner: PropTypes.bool,
                isTop: PropTypes.bool,
                isLike: PropTypes.bool,
                id: PropTypes.number,
                title: PropTypes.string,
                desc: PropTypes.string,
                thumbs: ImmutablePropTypes.listOf(
                    ImmutablePropTypes.contains({
                        src: PropTypes.string,
                    })
                ),
                section: ImmutablePropTypes.contains({
    				id: PropTypes.number,
    				name: PropTypes.string,
    			}),
                commentCount: PropTypes.number,
                likeCount: PropTypes.number,
            }),
        ),
        user: ImmutablePropTypes.contains({
            avatar: PropTypes.string,
            uid: PropTypes.number,
            msgCount: PropTypes.string,
        }),

        bannerDuration: PropTypes.number,
        noticeOpen: PropTypes.oneOf(['Y', 'N']),
        noticeDuration: PropTypes.number,
        onPressPost: PropTypes.func,
        onPressAvatar: PropTypes.func,
        onPressSectionTag: PropTypes.func,
        onPressComment: PropTypes.func,
        onPressLike: PropTypes.func,
        onRefresh: PropTypes.func,
        onEndReached: PropTypes.func,
        onUploadRetry: PropTypes.func,
        onUploadSuccess: PropTypes.func,
        onUploadDelete: PropTypes.func,
        onSaveingTheWorld: PropTypes.func,
    };

    constructor(props) {
        super (props);

        this._renderRow = this._renderRow.bind(this);
        this._renderSectionHeader = this._renderSectionHeader.bind(this);
        this._renderSeparator = this._renderSeparator.bind(this);
        this.triggerPullToRefresh = this.triggerPullToRefresh.bind(this);

        this.dataSource = new ListView.DataSource({
            rowHasChanged: (r1, r2) => !Immutable.is(r1, r2),
            sectionHeaderHasChanged: (s1, s2) => !Immutable.is(s1, s2),
        });
    }

    componentDidMount() {
        this.triggerPullToRefresh();
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.scrollToTop) {
            this.listView.scrollTo({x: 0, y: 0, animated: false, });
        }
    }

    triggerPullToRefresh() {
        InteractionManager.runAfterInteractions(() => {
            this.listView && this.listView.getScrollResponder().startPullToRefresh();
        });
    }

    _renderRow(rowData, sectionID, rowID, highlightRow) {
        switch (sectionID) {

            case 'progressing':
                return (
                    <UploadProgress
                        data={rowData}
                        onPressRetry={this.props.onUploadRetry}
                        onPressDelete={this.props.onUploadDelete}
                        uploadSuccess={this.props.onUploadSuccess}
                    />
                );

			case 'banner':
                if (rowData.size == 0) {
                    return null;
                } else {
                    return (
                        <Banner
                            data={rowData}
                            duration={this.props.bannerDuration}
                            width={width}
                            height={bannerHeight}
                            onPress={this.props.onPressBanner}
                        />
                    );
                }
			case 'notice':
				return (
                    <Notice
                        data={rowData}
                        duration={this.props.noticeDuration}
                        width={width}
                        height={40}
                        onPress={this.props.onPressNotice}
                    />
				);
			case 'section':
                return (
                    <YH_SectionView
                        style={styles.carouselSection}
                        items={rowData.toJS()}
                        onClick={(info) => {
                            let type = info.type;
                            let item = rowData.get(info.index);
                            if (type == 0) {
                                // section
                                let section = {
                                    id: item.get('header').get('id'),
                                    name: item.get('header').get('title'),
                                }
                                this.props.onPressSection && this.props.onPressSection(section);
                            } else if (type == 1) {
                                // hot
                                let postId = item.get('hot').get('postId')
                                if (postId) {
                                    this.props.onPressPost && this.props.onPressPost(postId);
                                }
                            } else if (type == 2) {
                                // new
                                let postId = item.get('new').get('postId')
                                if (postId) {
                                    this.props.onPressPost && this.props.onPressPost(postId);
                                }
                            }
                        }}
                    />
                );
			case 'recommendation':
				return (
                    <ListCell
                        key={sectionID + rowID}
                        data={rowData}
                        onPressPost={this.props.onPressPost}
                        onPressAvatar={this.props.onPressAvatar}
                        onPressSectionTag={this.props.onPressSectionTag}
                        onPressComment={this.props.onPressComment}
                        onPressLike={this.props.onPressLike}
                    />
				);
            default:
                return null;
		}
    }

    _renderSectionHeader(sectionData, sectionID) {
        switch (sectionID) {
			case 'recommendation':
                if (this.props.recommendation.size == 0) {
                    if (this.props.isLoadingMore && this.props.isFetching) {
                        return null;
                    } else {
                        return null;
                    }
                }

				return (
                    <View style={styles.sectionHeader}>
                        <Image style={styles.sectionHeaderImg} source={require('../../images/home/hot.png')}/>
                        <Text style={styles.sectionHeaderText}>热门推荐</Text>
                        <View style={styles.sectionHeaderTopLine}/>
                        <View style={styles.sectionHeaderBottomLine}/>
                    </View>
				);

            default:
                return null;
		}
    }

    _renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
        return (
            <View key={'separator' + sectionID + rowID} style={styles.separator}/>
        );
    }

	render() {
        let {progressing, banner, notice, section, recommendation, user, endReached, isRefreshing, isLoadingMore, isFetching, isUserStateFetching} = this.props;
        let dataSource = {
            progressing: progressing.toArray(),
            banner: banner.toArray(),
            notice: notice.toArray(),
            section: section.toArray(),
            recommendation: recommendation.toArray(),
        }

        return (
            <View style={styles.container}>
                <ListView
                    ref={(c) => {
                        this.listView = c;
                    }}
                    dataSource={this.dataSource.cloneWithRowsAndSections(dataSource)}
                    renderRow={this._renderRow}
                    renderSectionHeader={this._renderSectionHeader}
                    renderSeparator={this._renderSeparator}
                    enableEmptySections={true}
                    enablePullToRefresh={true}
                    isOnPullToRefresh={isRefreshing}
                    onRefreshData={() => {
                        this.props.onRefresh && this.props.onRefresh();
                    }}
                    onEndReached={() => {
                        this.props.onEndReached && this.props.onEndReached();
                    }}
                    renderFooter={()=>{
                        if (endReached) {
                            return <LoadMoreIndicator
                                    isVisible={true}
                                    text={'暂无更多'}
                                />
                        } else {
                            return <LoadMoreIndicator
                                    isVisible={isLoadingMore}
                                    animating={isFetching}
                                />
                        }
                    }}
                />
                <LoadingIndicator
                    isVisible={isUserStateFetching}
                />
                <SuperMan
                    uid={user.uid}
                    avatar={user.avatar}
                    msgCount={user.msgCount}
                    onSaveingTheWorld={this.props.onSaveingTheWorld}
                />
            </View>
        );

    }
}

let styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    carouselSection: {
        width,
        height: sectionHeight,
    },
    sectionHeader: {
        flexDirection: 'row',
        height: 33,
        alignItems: 'center',
        backgroundColor: 'white',
        // borderTopWidth: 0.5,         // borderTopWidth 在iPhone 6P上显示有bug
        // borderTopColor: '#e0e0e0',
    },
    sectionHeaderImg: {
        width: 9,
        height: 12,
        marginLeft: 17,
    },
    sectionHeaderText: {
        fontSize: 12,
        marginLeft: 5,
    },
    sectionHeaderTopLine: {
        position: 'absolute',
        left: 0,
        top: 0,
        width: width,
        height: 0.5,
        backgroundColor: '#e0e0e0',
    },
    sectionHeaderBottomLine: {
        position: 'absolute',
        left: 17,
        bottom: 0,
        width: width - 17,
        height: 0.5,
        backgroundColor: '#e0e0e0',
    },
    separator: {
        height: 0.5,
        backgroundColor: '#e0e0e0',
    },
});