Advertisement
Nov4tO266

Untitled

Jun 4th, 2019
811
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { PureComponent } from 'react';
  2. import { Alert, Share, FlatList, ListRenderItemInfo, InteractionManager, BackHandler } from 'react-native';
  3. import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
  4. import { heightPercentageToDP as hp } from 'react-native-responsive-screen';
  5. import { withNavigation, NavigationInjectedProps } from 'react-navigation';
  6. import { ChildProps } from 'react-apollo';
  7.  
  8. import Question, { QuestionProps } from '~/components/Question';
  9. import QuestionPagination from '~/components/Question/Pagination';
  10. import PageHeader from '~/components/PageHeader';
  11.  
  12. import { ChildDataProps, graphql } from "react-apollo";
  13. import { ALL_QUESTIONS } from '~/graphQL/queries';
  14. // import mock from '~/assets/questoes.mock';
  15.  
  16. interface QuestionsPageState {
  17.   favorited: boolean;
  18.   answered: boolean;
  19.   currentItem: number;
  20.   questions: QuestionProps[];
  21. }
  22.  
  23. @withNavigation
  24. // @graphql<NavigationInjectedProps, QueryResult>(QUESTIONS_QUERY)
  25. class QuestionsPage extends PureComponent<ChildProps<NavigationInjectedProps, QuestionsPageState>> {
  26.   private listRef: FlatList<QuestionProps> | null = null;
  27.  
  28.   public state = {
  29.     favorited: false,
  30.     answered: false,
  31.     currentItem: 0,
  32.     questions: null,
  33.   };
  34.  
  35.   public componentDidMount() {
  36.     BackHandler.addEventListener('hardwareBackPress', this.exit);
  37.   }
  38.  
  39.   public componentWillUnmount() {
  40.     this.listRef = null;
  41.     BackHandler.removeEventListener('hardwareBackPress', this.exit);
  42.   }
  43.  
  44.   private share = (message: string) => {
  45.     InteractionManager.runAfterInteractions(async () => {
  46.       try {
  47.         await Share.share({ message });
  48.       } catch (error) {
  49.         Alert.alert('Erro ao compartilhar a questão', error.message);
  50.       }
  51.     });
  52.   };
  53.  
  54.   private renderItem = (question: ListRenderItemInfo<QuestionProps>) => (
  55.     <Question
  56.      {...question.item}
  57.      onChooseAlternative={() => this.handleAlternative()}
  58.       comments={question.item.comments}
  59.       onChooseMoreComments={() => this.props.navigation.navigate('Comments', { comments: question.item.comments.data })}
  60.     />
  61.   );
  62.  
  63.   private fetchQuestions = () => {
  64.     const allQuestions = graphql<{}, Response, ChildProps>(ALL_QUESTIONS);
  65.  
  66.     InteractionManager.runAfterInteractions(() => {
  67.       this.setState((state: QuestionsPageState) => {
  68.         const needMoreQuestions = state.currentItem + 2 >= state.questions.length;
  69.  
  70.         if (!needMoreQuestions) {
  71.           return null;
  72.         }
  73.  
  74.         return {
  75.           // questions: [...state.questions, data],
  76.         };
  77.       });
  78.     });
  79.   };
  80.  
  81.   private handleAlternative = () => {
  82.     this.setState((state: QuestionsPageState) => {
  83.       this.fetchQuestions();
  84.       return {
  85.         answered: true,
  86.       };
  87.     });
  88.   };
  89.  
  90.   private handleNextItem = () => {
  91.     this.setState((state: QuestionsPageState) => {
  92.       const nextItem = state.currentItem + 1;
  93.  
  94.       this.fetchQuestions();
  95.  
  96.       if (this.listRef) {
  97.         this.listRef.scrollToIndex({ index: nextItem });
  98.       }
  99.  
  100.       return {
  101.         currentItem: nextItem,
  102.         favorited: false,
  103.         answered: false,
  104.       };
  105.     });
  106.   };
  107.  
  108.   private exit = () => {
  109.     Alert.alert('Tem certeza que deseja parar seus estudos?', '', [
  110.       { text: 'Não' },
  111.       { text: 'Sim', onPress: () => this.props.navigation.goBack() },
  112.     ]);
  113.   };
  114.  
  115.   public render() {
  116.     const { navigation } = this.props;
  117.     const { currentItem, questions, favorited, answered } = this.state;
  118.     const hasNextQuestion = currentItem + 1 < questions.length;
  119.     const label = navigation.getParam('label', '');
  120.  
  121.     return (
  122.       <>
  123.         <PageHeader
  124.           label={label}
  125.           leftAction={{
  126.             title: 'Back',
  127.             icon: <Icon name="arrow-left" size={hp(4)} color="#BABABA" />,
  128.             onPress: () => this.exit(),
  129.           }}
  130.           rightActions={[
  131.             {
  132.               title: 'Favoritar',
  133.               icon: (
  134.                 <Icon
  135.                   name={favorited ? 'heart' : 'heart-outline'}
  136.                   size={hp(4)}
  137.                   color={favorited ? '#00D8A7' : '#BABABA'}
  138.                 />
  139.               ),
  140.               onPress: () => this.setState({ favorited: true }),
  141.             },
  142.             {
  143.               title: 'Compartilhar com um amigo',
  144.               icon: <Icon name="share-variant" size={hp(4)} color="#00D8A7" />,
  145.               onPress: () => this.share(mock[currentItem].statement),
  146.             },
  147.             {
  148.               title: 'Reportar erro na questão',
  149.               icon: <Icon name="alert-circle-outline" size={hp(4)} color="#FF4350" />,
  150.               onPress: () => navigation.navigate('QuestionReport', mock[currentItem]),
  151.             },
  152.           ]}
  153.         />
  154.         <FlatList
  155.          horizontal
  156.          pagingEnabled
  157.          scrollEnabled={false}
  158.          data={questions}
  159.          extraData={questions}
  160.          initialScrollIndex={currentItem}
  161.          renderItem={this.renderItem}
  162.          keyExtractor={(question: QuestionProps) => `question-${question.id}`}
  163.           ref={(ref: FlatList<QuestionProps>) => (this.listRef = ref)}
  164.         />
  165.         <QuestionPagination
  166.          onSkipPress={() => this.handleNextItem()}
  167.           onNextPress={() => this.handleNextItem()}
  168.           allowNext={hasNextQuestion && answered}
  169.           allowSkip={hasNextQuestion}
  170.         />
  171.       </>
  172.     );
  173.   }
  174. }
  175.  
  176. export default QuestionsPage;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement