File size: 5,222 Bytes
f5071ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import gql from 'graphql-tag';
import React from 'react';
import { useCallback, useState, useContext, useEffect } from 'react';
import { Redirect } from 'react-router-dom';
import { useApolloClient } from '@apollo/react-hooks';
import styled from 'styled-components';
import ChatNavbar from './ChatNavbar';
import MessageInput from './MessageInput';
import MessagesList from './MessagesList';
import { History } from 'history';
import {
  useGetChatQuery,
  useAddMessageMutation,
  GetChatQuery,
  GetChatQueryVariables,
  GetChatDocument,
} from '../../graphql/types';
import * as fragments from '../../graphql/fragments';
import { writeMessage } from '../../services/cache.service';

const Container = styled.div`
  background: url(/assets/chat-background.jpg);
  display: flex;
  flex-flow: column;
  height: 100vh;
`;

// eslint-disable-next-line
const getChatQuery = gql`
  query GetChat($chatId: ID!, $limit: Int!, $after: Float) {
    chat(chatId: $chatId) {
      ...FullChat
    }
  }
  ${fragments.fullChat}
`;

// eslint-disable-next-line
const addMessageMutation = gql`
  mutation AddMessage($chatId: ID!, $content: String!) {
    addMessage(chatId: $chatId, content: $content) {
      ...Message
    }
  }
  ${fragments.message}
`;

const PaginationContext = React.createContext({
  after: 0,
  limit: 20,
  /**
   * Sets new cursor
   */
  setAfter: (after: number) => {},
  /**
   * Resets `after` value to its inital state (null) so
   */
  reset: () => {},
});

const usePagination = () => {
  const pagination = useContext(PaginationContext);

  // Resets the pagination every time a component did unmount
  useEffect(() => {
    return () => {
      pagination.reset();
    };
  }, [pagination]);

  return pagination;
};

export const ChatPaginationProvider = ({ children }: { children: any }) => {
  const [after, setAfter] = useState<number | null>(null);

  return (
    <PaginationContext.Provider
      value={{
        limit: 20,
        after: after!,
        setAfter,
        reset: () => setAfter(null),
      }}>
      {children}
    </PaginationContext.Provider>
  );
};

export const useGetChatPrefetch = () => {
  const client = useApolloClient();
  const { limit, after } = usePagination();

  return (chatId: string) => {
    client.query<GetChatQuery, GetChatQueryVariables>({
      query: GetChatDocument,
      variables: {
        chatId,
        after,
        limit,
      },
    });
  };
};

interface ChatRoomScreenParams {
  chatId: string;
  history: History;
}

const ChatRoom: React.FC<ChatRoomScreenParams> = ({ history, chatId }) => {
  const { after, limit, setAfter } = usePagination();
  const { data, loading, fetchMore } = useGetChatQuery({
    variables: { chatId, after, limit },
  });

  const [addMessage] = useAddMessageMutation();

  const onSendMessage = useCallback(
    (content: string) => {
      if (data === undefined) {
        return null;
      }
      const chat = data.chat;
      if (chat === null) return null;

      addMessage({
        variables: { chatId, content },
        optimisticResponse: {
          __typename: 'Mutation',
          addMessage: {
            __typename: 'Message',
            id: Math.random().toString(36).substr(2, 9),
            createdAt: new Date(),
            isMine: true,
            chat: {
              __typename: 'Chat',
              id: chatId,
            },
            content,
          },
        },
        update: (client, { data }) => {
          if (data && data.addMessage) {
            writeMessage(client, data.addMessage);
          }
        },
      });
    },
    [data, chatId, addMessage]
  );

  useEffect(() => {
    if (!after) {
      return;
    }

    // every time after changes its value, fetch more messages
    fetchMore({
      variables: {
        after,
        limit,
      },
      updateQuery(prev, { fetchMoreResult }) {
        const messages = [
          ...fetchMoreResult!.chat!.messages.messages,
          ...prev.chat!.messages.messages,
        ];

        return {
          ...prev,
          chat: {
            ...prev.chat!,
            messages: {
              ...fetchMoreResult!.chat!.messages,
              messages,
            },
          },
        };
      },
    });
  }, [after, limit, fetchMore]);

  if (data === undefined) {
    return null;
  }
  const chat = data.chat;
  const loadingChat = loading;

  if (loadingChat) return null;
  if (chat === null) return null;

  // Chat was probably removed from cache by the subscription handler
  if (!chat) {
    return <Redirect to="/chats" />;
  }

  return (
    <Container>
      {chat?.id && <ChatNavbar chat={chat} history={history} />}
      {chat?.messages && (
        <MessagesList
          messages={chat.messages.messages}
          hasMore={chat.messages.hasMore}
          loadMore={() => setAfter(chat.messages.cursor!)}
        />
      )}
      <MessageInput onSendMessage={onSendMessage} />
    </Container>
  );
};

const ChatRoomScreen: React.FC<ChatRoomScreenParams> = ({
  history,
  chatId,
}) => {
  return (
    <ChatPaginationProvider>
      <ChatRoom history={history} chatId={chatId} />
    </ChatPaginationProvider>
  );
};

export default ChatRoomScreen;