-
Notifications
You must be signed in to change notification settings - Fork 32
/
ProtestForm.js
346 lines (307 loc) · 11.7 KB
/
ProtestForm.js
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
import React, { useState, useEffect, useCallback } from 'react';
import styled from 'styled-components/macro';
import { Link } from 'react-router-dom';
import PlacesAutocomplete from '../PlacesAutocomplete';
import { useForm } from 'react-hook-form';
import { Map, TileLayer, Marker } from 'react-leaflet';
import Button from '../elements/Button';
import { validateLatLng, isValidUrl } from '../../utils';
import { fetchNearbyProtests } from '../../api';
import L from 'leaflet';
import DateTimeList from '../DateTimeList';
const protestMarker = new L.Icon({
iconUrl: '/icons/fist.svg',
iconRetinaUrl: '/icons/fist.svg',
iconSize: [50, 48],
iconAnchor: [25, 48],
});
function ProtestForm({
initialCoords,
submitCallback,
defaultValues = {},
afterSubmitCallback = () => {},
editMode = null,
isAdmin,
}) {
const coordinatesUpdater = useCallback(() => {
let initialState = [31.7749837, 35.219797];
if (validateLatLng(initialCoords)) initialState = initialCoords;
return initialState;
}, [initialCoords]);
const { register, handleSubmit, setValue, reset } = useForm({
defaultValues,
});
const [streetAddressDefaultValue, setStreetAddressDefaultValue] = useState(defaultValues.streetAddress);
// These two are separate so that onMoveEnd isn't called on every map move
const [mapCenter, setMapCenter] = useState(coordinatesUpdater);
// Marker position
const [markerPostion, setMarkerPosition] = useState(coordinatesUpdater);
const [dateTimeList, setDateTimeList] = useState(defaultValues.dateTimeList || [{ id: 0, date: '2020-10-24', time: '17:30' }]);
const [submitSuccess, setSubmitSuccess] = useState(false);
const [submitMessage, setSubmitMessage] = useState('');
const [nearbyProtests, setNearbyProtests] = useState([]);
const [zoomLevel, setZoomLevel] = useState(14);
// const { recaptcha } = useRef(null);
const setStreetAddress = React.useCallback((value) => setValue('streetAddress', value), [setValue]);
useEffect(() => {
reset({});
setStreetAddressDefaultValue('');
setStreetAddress('');
}, [editMode, reset, setStreetAddress]);
// The two useEffects below this are in order to deal with the defaultValues & Places Autocomplete
useEffect(() => {
if (Object.keys(defaultValues).length > 0) {
reset(defaultValues);
setSubmitMessage('');
setSubmitSuccess(false);
setStreetAddressDefaultValue(defaultValues.streetAddress);
setStreetAddress(defaultValues.streetAddress);
setDateTimeList(defaultValues.dateTimeList || [{ id: 0, date: '2020-10-24', time: '17:30' }]);
if (validateLatLng(defaultValues.latlng)) {
setMapCenter(defaultValues.latlng);
setMarkerPosition(defaultValues.latlng);
}
}
}, [defaultValues, reset, setStreetAddress, setDateTimeList]);
// Load nearby protests on mount
useEffect(() => {
const coords = coordinatesUpdater();
async function nearbyProtests() {
const protests = await fetchNearbyProtests(coords);
setNearbyProtests(protests);
}
nearbyProtests();
}, [coordinatesUpdater]);
const onSubmit = async (params) => {
if (!editMode && !params.streetAddress) {
alert('אנא הזינו את כתובת ההפגנה');
return;
} else {
if (!mapCenter) {
alert('אנא הזינו כתובת תקינה');
return;
}
if (params.telegramLink && !isValidUrl(params.telegramLink)) {
alert('לינק לקבוצת הטלגרם אינו תקין');
return;
}
if (params.whatsAppLink && !isValidUrl(params.whatsAppLink)) {
alert('לינק לקבוצת הוואטסאפ אינו תקין');
return;
}
try {
params.coords = mapCenter;
params.dateTimeList = dateTimeList;
if (defaultValues.protestRef) {
params.protestRef = defaultValues.protestRef;
}
let protest = await submitCallback(params);
if (editMode) {
setSubmitSuccess(true);
setSubmitMessage('ההפגנה נשלחה בהצלחה ותתווסף למפה בזמן הקרוב :)');
afterSubmitCallback();
return;
}
if (protest._document) {
setSubmitSuccess(true);
setSubmitMessage('ההפגנה נשלחה בהצלחה ותתווסף למפה בזמן הקרוב :)');
afterSubmitCallback();
} else {
throw new Error('protest._document was null.');
}
} catch (err) {
console.error(err);
setSubmitSuccess(true);
setSubmitMessage('תקלה התרחשה בתהליך השליחה. אנא פנו אלינו וננסה להבין את הבעיה: support@1km.zendesk.com');
}
}
};
// useEffect(() => {
// loadReCaptcha(process.env.REACT_APP_RECAPTCHA_KEY);
// }, []);
// const verifyCallback = (recaptchaToken) => {
// setRecaptchaToken(recaptchaToken);
// };
return (
<ProtestFormWrapper onSubmit={handleSubmit(onSubmit)}>
{submitSuccess && !editMode ? (
<>
<SuccessMessage>{submitMessage}</SuccessMessage>
<Link to="/">
<Button>לעמוד הראשי</Button>
</Link>
</>
) : (
<>
{(!editMode || isAdmin) && (
<>
<ProtestFormLabel>
שם המקום
<ProtestFormInput
type="text"
name="displayName"
ref={register}
placeholder="איפה ההפגנה?"
autoFocus
></ProtestFormInput>
<ProtestFormInputDetails>שם המקום כפי שתושבי האיזור מכירים אותו</ProtestFormInputDetails>
</ProtestFormLabel>
<ProtestFormLabel>
כתובת
<PlacesAutocomplete
setManualAddress={setMapCenter}
setStreetAddress={setStreetAddress}
inputRef={register}
defaultValue={streetAddressDefaultValue}
/>
<ProtestFormInputDetails>לאחר בחירת הכתובת, הזיזו את הסמן למיקום המדויק:</ProtestFormInputDetails>
</ProtestFormLabel>
<MapWrapper
center={mapCenter}
zoom={zoomLevel}
scrollWheelZoom={'center'}
onMove={(t) => {
setMarkerPosition([t.target.getCenter().lat, t.target.getCenter().lng]);
setZoomLevel(t.target._zoom);
}}
onMoveEnd={async (t) => {
const newPosition = [t.target.getCenter().lat, t.target.getCenter().lng];
setMapCenter(newPosition);
setMarkerPosition(newPosition);
setZoomLevel(t.target._zoom);
// Fetch protests on move end
if (mapCenter) {
const protests = await fetchNearbyProtests(mapCenter);
setNearbyProtests(protests);
}
}}
onZoom={(event) => {
setZoomLevel(event.target._zoom);
}}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={markerPostion}></Marker>
{nearbyProtests.map((protest) => (
<Marker
position={[protest.coordinates.latitude, protest.coordinates.longitude]}
icon={protestMarker}
key={protest.id}
></Marker>
))}
</MapWrapper>
<hr />
</>
)}
<ProtestFormSectionTitle>תאריך ושעה</ProtestFormSectionTitle>
<DateTimeList dateTimeList={dateTimeList} setDateTimeList={setDateTimeList} />
<hr />
<ProtestFormSectionTitle>פרטי יצירת קשר</ProtestFormSectionTitle>
<ProtestFormLabel>
קבוצת וואטסאפ
<ProtestFormInput placeholder="לינק לקבוצה" name="whatsAppLink" ref={register}></ProtestFormInput>
</ProtestFormLabel>
<ProtestFormLabel>
קבוצת טלגרם
<ProtestFormInput placeholder="לינק לקבוצה" name="telegramLink" ref={register}></ProtestFormInput>
</ProtestFormLabel>
<ProtestFormLabel>
הערות
<ProtestFormInput placeholder="הערות להפגנה" name="notes" ref={register}></ProtestFormInput>
<ProtestFormInputDetails>כל דבר שחשוב שיופיע בפרטי ההפגנה.</ProtestFormInputDetails>
</ProtestFormLabel>
{!editMode ? (
<>
<ProtestFormInputDetails margin="10px 0">
האימייל לא יפורסם באתר ולא יועבר לשום גורם חיצוני. ניצור קשר במידה ונצטרך לוודא את פרטי ההפגנה.
</ProtestFormInputDetails>
<ProtestFormLabel>
כתובת מייל
<ProtestFormInput type="email" placeholder="האימייל שלך" name="email" ref={register}></ProtestFormInput>
</ProtestFormLabel>
<ProtestFormCheckboxWrapper>
<ProtestFormCheckbox type="checkbox" id="contact-approve" name="approveContact" ref={register} />
<label htmlFor="contact-approve">אני מעוניין/מעוניינת לקבל עדכונים מיוצר האתר</label>
</ProtestFormCheckboxWrapper>
<Button type="submit" color="#1ED96E">
הוספת הפגנה
</Button>
</>
) : (
<>
{defaultValues.protestRef ? (
<>
<p style={{ textAlign: 'center' }}>.ההפגנה כבר נוצרה, רק צריך לאשר שהיא תקינה</p>
<Button type="submit" color="#1ED96E">
אישור הפגנה
</Button>
</>
) : (
<Button type="submit" color="#1ED96E">
{editMode === 'pending' ? 'יצירת הפגנה' : 'עריכת הפגנה'}
</Button>
)}
</>
)}
</>
)}
</ProtestFormWrapper>
);
}
const ProtestFormWrapper = styled.form`
width: 300px;
margin: 25px auto;
justify-items: center;
@media (min-width: 768px) {
grid-column: 1 / -1;
}
`;
export const ProtestFormLabel = styled.label`
display: flex;
flex-direction: column;
width: 100%;
margin-bottom: 10px;
font-weight: 600;
`;
export const ProtestFormInput = styled.input`
width: 100%;
padding: 6px 12px;
margin-bottom: 0;
font-size: 16px;
border: 1px solid #d2d2d2;
-webkit-appearance: none;
`;
const ProtestFormInputDetails = styled.span.attrs((props) => ({
textAlign: props.textAlign || 'initial',
margin: props.margin || '0',
}))`
display: block;
font-size: 14px;
font-weight: 300;
margin: ${(props) => props.margin};
text-align: ${(props) => props.textAlign};
`;
const ProtestFormCheckbox = styled.input``;
const MapWrapper = styled(Map)`
width: 100%;
height: 250px;
margin-bottom: 10px;
z-index: 0;
`;
const ProtestFormSectionTitle = styled.h3`
margin: 3px 0;
`;
const ProtestFormCheckboxWrapper = styled.div`
display: grid;
grid-template-columns: 20px 1fr;
align-items: start;
margin: 7.5px 0;
font-size: 14px;
font-weight: 100;
`;
const SuccessMessage = styled.h2`
text-align: center;
`;
export default ProtestForm;