-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathWorldChat.js
More file actions
executable file
·372 lines (339 loc) · 9.91 KB
/
WorldChat.js
File metadata and controls
executable file
·372 lines (339 loc) · 9.91 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import React, { Component } from 'react'
import '../styles/WorldChat.css'
import _ from 'lodash'
import { GoogleMap, withGoogleMap, Marker, InfoWindow, withScriptjs } from 'react-google-maps'
import Chat from './Chat'
import Banner from './Banner'
import { withApollo, graphql, compose } from 'react-apollo'
import gql from 'graphql-tag'
const allLocations = gql`
query allLocations {
allLocations {
id
latitude
longitude
traveller {
id
name
}
}
}
`
const travellerForId = gql`
query travellerForId($id: ID!) {
Traveller(id: $id) {
id
name
location {
id
latitude
longitude
}
}
}
`
const createLocationAndTraveller = gql`
mutation createLocationAndTraveller($name: String!, $latitude: Float!, $longitude: Float!) {
createLocation(latitude: $latitude, longitude: $longitude, traveller: {
name: $name
}) {
id
latitude
longitude
traveller {
id
name
}
}
}
`
const updateLocation = gql`
mutation updateLocation($locationId: ID!, $latitude: Float!, $longitude: Float!) {
updateLocation(id: $locationId, latitude: $latitude, longitude: $longitude) {
traveller {
id
name
}
id
latitude
longitude
}
}
`
const WorldChatGoogleMap = _.flowRight(
withScriptjs,
withGoogleMap,
)(props => (
<GoogleMap
ref={props.onMapLoad}
defaultZoom={3}
defaultCenter={{ lat: 52.53734, lng: 13.395 }}
onClick={props.onMapClick}
defaultOptions={{
disableDefaultUI: true
}}
>
{Boolean(props.markers) && props.markers.map((marker , index) => (
<Marker
{...marker}
showInfo={false}
icon={marker.isOwnMarker ? require('../assets/marker_blue.svg') : require('../assets/marker.svg')}
onClick={() => props.onMarkerClick(marker)}
defaultAnimation={2}
key={index}
>
{marker.showInfo && (
<InfoWindow
onCloseClick={() => props.onMarkerClose(marker)}>
<div className=''>{marker.travellerName}</div>
</InfoWindow>
)}
</Marker>
))}
</GoogleMap>
)
)
const WORLDCHAT_USER_ID_KEY = 'WORLDCHAT_USER_ID'
class WorldChat extends Component {
state = {
markers: [],
travellerId: undefined,
location: undefined,
}
async componentDidMount() {
this.locationSubscription = this.props.allLocationsQuery.subscribeToMore({
document: gql`
subscription {
Location(filter: {
mutation_in: [CREATED, UPDATED]
}) {
mutation
node {
id
latitude
longitude
traveller {
id
name
}
}
}
}
`,
variables: null,
updateQuery: (previousState, {subscriptionData}) => {
if (subscriptionData.data.Location.mutation === 'CREATED') {
const newLocation = subscriptionData.data.Location.node
const locations = previousState.allLocations.concat([newLocation])
return {
allLocations: locations,
}
}
else if (subscriptionData.data.Location.mutation === 'UPDATED') {
const locations = previousState.allLocations.slice()
const updatedLocation = subscriptionData.data.Location.node
const oldLocationIndex = locations.findIndex(location => {
return updatedLocation.id === location.id
})
locations[oldLocationIndex] = updatedLocation
return {
allLocations: locations,
}
}
return previousState
}
})
const travellerId = localStorage.getItem(WORLDCHAT_USER_ID_KEY)
// Check if traveller already exists
if (!Boolean(travellerId)) {
this._createNewTraveller()
}
else {
this._updateExistingTraveller(travellerId)
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.allLocationsQuery.allLocations) {
const newMarkers = nextProps.allLocationsQuery.allLocations.map(location => {
const isOwnMarker = location.traveller.id === this.state.travellerId
return {
travellerName: isOwnMarker ? location.traveller.name + ' (You)' : location.traveller.name,
position: {
lat: location.latitude,
lng: location.longitude,
},
isOwnMarker: isOwnMarker
}
})
this.setState({
markers: newMarkers,
})
}
}
_removeAllMarkers() {
const newMarkers = this.state.markers.slice()
newMarkers.forEach(marker => {
marker.showInfo = false
})
this.setState({
markers: newMarkers,
})
}
_createNewTraveller = () => {
console.log('Create new traveller: ', this.props.name)
if (navigator.geolocation) {
// Retrieve location
navigator.geolocation.getCurrentPosition(position => {
this.props.createLocationAndTravellerMutation({
variables: {
name: this.props.name,
latitude: position.coords.latitude,
longitude: position.coords.longitude,
}
}).then(result => {
localStorage.setItem(WORLDCHAT_USER_ID_KEY, result.data.createLocation.traveller.id)
this.setState({
travellerId: result.data.createLocation.traveller.id,
})
})
})
}
else {
// Create fake location
window.alert("We could not retrieve your location, so we're putting you close to Santa 🎅❄️")
const nortpholeCoordinates = this._generateRandomNorthPolePosition()
this.props.createLocationAndTravellerMutation({
variables: {
name: this.props.name,
latitude: nortpholeCoordinates.latitude,
longitude: nortpholeCoordinates.longitude,
}
}).then(result => {
localStorage.setItem(WORLDCHAT_USER_ID_KEY, result.data.createLocation.traveller.id)
this.setState({
travellerId: result.data.createLocation.traveller.id,
})
})
}
}
_updateExistingTraveller = async (travellerId) => {
this.setState({
travellerId: travellerId
})
// Check for traveller with this Id
const travellerForIdResponse = await this.props.client.query(
{
query: travellerForId,
variables: {
id: travellerId,
},
}
)
console.log('Update existing traveller: ', travellerForIdResponse)
const existingTraveller = travellerForIdResponse.data.Traveller
console.log('existingTraveller: ', existingTraveller)
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
// Retrieve location
this.props.updateLocationMutation({
variables: {
locationId: existingTraveller.location.id,
latitude: position.coords.latitude,
longitude: position.coords.longitude,
}
})
})
} else {
// Create fake location
const nortpholeCoordinates = this._generateRandomNorthPolePosition()
this.props.updateLocationMutation({
variables: {
locationId: existingTraveller.location.id,
latitude: nortpholeCoordinates.latitude,
longitude: nortpholeCoordinates.longitude,
}
})
}
}
handleMapLoad = this.handleMapLoad.bind(this)
handleMapClick = this.handleMapClick.bind(this)
handleMarkerClick = this.handleMarkerClick.bind(this)
handleMarkerClose = this.handleMarkerClose.bind(this)
handleMarkerClick(targetMarker) {
this.setState({
markers: this.state.markers.map(marker => {
if (marker === targetMarker) {
return {
...marker,
showInfo: true,
}
}
return marker
}),
})
}
handleMarkerClose(targetMarker) {
this.setState({
markers: this.state.markers.map(marker => {
if (marker === targetMarker) {
return {
...marker,
showInfo: false,
}
}
return marker
}),
})
}
handleMapLoad(map) {
this._mapComponent = map
}
handleMapClick() {
this._removeAllMarkers()
}
_generateRandomNorthPolePosition = () => {
const latitude = 64.7555869
const longitude = -147.34432909999998
const latitudeAdd = Math.random() > 0.5
const longitudeAdd = Math.random() > 0.5
const latitudeDelta = Math.random() * 3
const longitudeDelta = Math.random() * 3
const newLatitude = latitudeAdd ? latitude + latitudeDelta : latitude - latitudeDelta
const newLongitude = longitudeAdd ? longitude + longitudeDelta : longitude - longitudeDelta
return {latitude: newLatitude, longitude: newLongitude}
}
render() {
return (
<div style={{height: `100%`}}>
<WorldChatGoogleMap
googleMapURL='https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyCedl-z2FCu87QocGvWB_GW0mLBPiy7-Kg'
loadingElement={
<div style={{height: `100%`}}>
Loading
</div>
}
containerElement={
<div style={{ height: `100%` }} />
}
mapElement={
<div style={{ height: `100%` }} />
}
onMapLoad={this.handleMapLoad}
onMapClick={this.handleMapClick}
markers={this.state.markers}
onMarkerClick={this.handleMarkerClick}
onMarkerClose={this.handleMarkerClose}
/>
<Banner />
<Chat
travellerId={this.state.travellerId}
/>
</div>
)
}
}
export default compose(
graphql(allLocations, {name: 'allLocationsQuery'}),
graphql(createLocationAndTraveller, {name: 'createLocationAndTravellerMutation'}),
graphql(updateLocation, {name: 'updateLocationMutation'})
)(withApollo(WorldChat))