SignUp.tsx 12.7 KB
Newer Older
Sam Gluck's avatar
Sam Gluck committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import * as React from 'react';
import { Redirect, RouteComponentProps } from 'react-router';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faImage, faUser } from '@fortawesome/free-solid-svg-icons';
import { Grid, Row, Col } from '@zendeskgarden/react-grid';

import styled, { StyledThemeInterface } from '../../themes/styled';
import Logo from '../../components/brand/Logo/Logo';
import Body from '../../components/chrome/Body/Body';
import H6 from '../../components/typography/H6/H6';
import PreviousStep from './PreviousStep';
import Step1 from './Step1';
import Step2 from './Step2';
import P from '../../components/typography/P/P';
Sam Gluck's avatar
Sam Gluck committed
15
16
import H4 from '../../components/typography/H4/H4';
import User from '../../types/User';
Sam Gluck's avatar
Sam Gluck committed
17
18
19
20
21
22
23
24
25

const SignUpBody = styled(Body)`
  display: flex;
  flex-direction: row;
`;

//TODO media queries/responsivity
const Sidebar = styled.div`
  width: 25%;
Sam Gluck's avatar
Sam Gluck committed
26
  min-width: 500px;
Sam Gluck's avatar
Sam Gluck committed
27
28
29
30
31
32
33
34
  height: 100%;
  padding: 25px;
  background-color: ${(props: StyledThemeInterface) =>
    props.theme.styles.colour.base5};
`;

//TODO media queries/responsivity
const UserProfile = styled.div`
Sam Gluck's avatar
Sam Gluck committed
35
  overflow: auto;
Sam Gluck's avatar
Sam Gluck committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
  width: 75%;
  height: 100%;
  margin-left: 1%;
  background-color: ${(props: StyledThemeInterface) =>
    props.theme.styles.colour.base5};
`;

//TODO don't use any props type
const UserProfileImage = styled.div<any>`
  position: relative;
  width: 100%;
  height: 400px;
  background-color: ${props => props.theme.styles.colour.base4};
  background-image: ${props =>
    props.backgroundImage
Sam Gluck's avatar
Sam Gluck committed
51
52
53
      ? `linear-gradient(transparent, rgba(0, 0, 0, .75)), url(${
          props.backgroundImage
        })`
Sam Gluck's avatar
Sam Gluck committed
54
55
56
57
58
59
60
61
62
63
64
65
      : ''};
  background-position: center;
  background-size: 100% auto;
  color: ${props => props.theme.styles.colour.base3};
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 6rem;
`;

const liftUserAvatar = -75;

Sam Gluck's avatar
Sam Gluck committed
66
67
68
69
70
71
72
73
74
const AvatarPlaceholder = styled.div`
  font-size: 12px;
  position: absolute;
  top: 150px;
  text-align: center;
  text-shadow: 1px 1px 0 #00000069;
  transition: all 0.2s linear;
`;

Sam Gluck's avatar
Sam Gluck committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//TODO don't use any props type
const UserAvatar = styled.div<any>`
  overflow: hidden;
  height: 150px;
  width: 150px;
  border-radius: 75px;
  background-color: ${props => props.theme.styles.colour.base3};
  background-image: ${props => `url(${props.backgroundImage})`};
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  color: ${props => props.theme.styles.colour.base5};
  position: relative;
  top: ${liftUserAvatar}px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 4rem;
Sam Gluck's avatar
Sam Gluck committed
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

  // avatar placeholder
  > div {
    font-size: 6px;
    pointer-events: none;
  }

  &:hover > div {
    top: 50%;
    font-size: 12px;
  }
  // end avatar placeholder

  // avatar font awesome icon
  svg {
    top: 0;
    position: relative;
    transition: all 0.2s linear;
    pointer-events: none;
  }

  &:hover svg {
    font-size: 30px;
    top: -25px;
  }
  // end avatar font awesome icon
Sam Gluck's avatar
Sam Gluck committed
120
121
122
123
124
125
126
127
`;

const UserDetails = styled.div`
  position: relative;
  top: ${liftUserAvatar}px;
  text-align: center;
`;

Sam Gluck's avatar
Sam Gluck committed
128
129
130
131
132
133
const SignUpProfileSection = styled.div`
  position: relative;
  top: ${liftUserAvatar}px;
  padding: 50px;
`;

Sam Gluck's avatar
Sam Gluck committed
134
135
136
137
138
139
140
const FileInput = styled.input`
  cursor: pointer;
  height: calc(100% + 100px);
  width: 100%;
  position: absolute;
  top: -100px;
  left: 0;
Sam Gluck's avatar
Sam Gluck committed
141
142
143
144

  &:focus {
    outline: 0;
  }
Sam Gluck's avatar
Sam Gluck committed
145
146
`;

Sam Gluck's avatar
Sam Gluck committed
147
148
149
150
151
const stepScrollTo = {
  1: 0,
  2: 650
};

Sam Gluck's avatar
Sam Gluck committed
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
//TODO this should be offloaded to an API
function generateEmojiId(): string {
  const emojis = [
    '😀',
    '😃',
    '😣',
    '😐',
    '🤥',
    '🍏',
    '🍎',
    '🍐',
    '🍊',
    '🍋',
    '🐶',
    '🐱',
    '🐭',
    '🐹',
    '🐰',
    '😀',
    '😃',
    '😄',
    '😁',
    '😆',
    '🌹',
    '💐',
    '🍁',
    '🐴'
  ];
  let id = '';
  for (let i = 0; i < 3; i++) {
    id += emojis[Math.floor(Math.random() * emojis.length)];
  }
  return id;
}

interface SignUpMatchParams {
  step: string;
}

interface SignUpState {
  currentStep: number;
Sam Gluck's avatar
Sam Gluck committed
193
  user: User;
Sam Gluck's avatar
Sam Gluck committed
194
195
196
197
198
199
200
201
202
203
204
}

interface SignUpProps extends RouteComponentProps<SignUpMatchParams> {}

const FadedFallbackText = ({ value, fallback }) =>
  value ? (
    <span>{value}</span>
  ) : (
    <span style={{ color: 'lightgrey' }}>{fallback}</span>
  );

Sam Gluck's avatar
Sam Gluck committed
205
206
207
208
209
210
211
212
213
214
215
const Step2Section = styled.div<any>`
  opacity: ${props => (props.active ? 1 : 0.1)};
  pointer-events: ${props => (props.active ? 'unset' : 'none')};
  transition: opacity 1.75s linear;
`;

const Interests = ({ active, interests }) => (
  <Step2Section active={active}>
    <H4>Interests</H4>
  </Step2Section>
);
Sam Gluck's avatar
Sam Gluck committed
216

Sam Gluck's avatar
Sam Gluck committed
217
218
219
220
221
const Languages = ({ active, languages }) => (
  <Step2Section active={active}>
    <H4>Languages</H4>
  </Step2Section>
);
Sam Gluck's avatar
Sam Gluck committed
222
223
224
225

export default class SignUp extends React.Component<SignUpProps, SignUpState> {
  static stepComponents = [Step1, Step2];

Sam Gluck's avatar
Sam Gluck committed
226
227
  _profileElem: HTMLElement;

Sam Gluck's avatar
Sam Gluck committed
228
229
230
231
232
233
234
235
236
237
238
239
240
  state = {
    currentStep: -1,
    user: {
      username: '',
      email: '',
      emojiId: generateEmojiId(),
      avatarImage: undefined,
      profileImage: undefined,
      role: '',
      location: '',
      language: 'en-gb',
      interests: [] as string[],
      languages: [] as string[]
Sam Gluck's avatar
Sam Gluck committed
241
    } as User
Sam Gluck's avatar
Sam Gluck committed
242
243
244
245
246
247
248
  };

  constructor(props) {
    super(props);

    this.state.currentStep = Number(props.match.params.step);

Sam Gluck's avatar
Sam Gluck committed
249
250
251
252
    if (!this.state.user.username && this.state.currentStep > 1) {
      this.props.history.replace('/sign-up');
      return;
    }
Sam Gluck's avatar
Sam Gluck committed
253
254
255
256
257
258
259
260
261
262
263

    this.randomizeEmojiId = this.randomizeEmojiId.bind(this);
    this.linkUserState = this.linkUserState.bind(this);
    this.goToNextStep = this.goToNextStep.bind(this);
    this.goToPreviousStep = this.goToPreviousStep.bind(this);
    this.toggleUserInterest = this.toggleUserInterest.bind(this);
    this.setUserImage = this.setUserImage.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    this.state.currentStep = Number(nextProps.match.params.step);
264
    this.scrollForStep(this.state.currentStep);
Sam Gluck's avatar
Sam Gluck committed
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
  }

  getStepComponent() {
    const stepProps = {
      user: this.state.user,
      goToNextStep: this.goToNextStep,
      goToPreviousStep: this.goToPreviousStep,
      randomizeEmojiId: this.randomizeEmojiId,
      linkUserState: this.linkUserState,
      toggleInterest: this.toggleUserInterest
    };
    const stepIdx = this.state.currentStep - 1;
    let Step = SignUp.stepComponents[stepIdx];
    if (!Step) {
      return null;
    }
    return <Step {...stepProps} />;
  }

  randomizeEmojiId() {
    this.setState({
      user: {
        ...this.state.user,
        emojiId: generateEmojiId()
      }
    });
  }

  goToPreviousStep() {
    const prevStep = Number(this.state.currentStep) - 1;
    if (prevStep > 0) {
      this.props.history.push(`/sign-up/${prevStep}`);
Sam Gluck's avatar
Sam Gluck committed
297
      this.scrollForStep(prevStep);
Sam Gluck's avatar
Sam Gluck committed
298
299
300
301
302
303
304
305
306
307
308
309
310
    }
  }

  goToNextStep() {
    const nextStep = Number(this.state.currentStep) + 1;
    if (nextStep > SignUp.stepComponents.length) {
      // the user has completed sign up, set them in the local cache and
      // redirect them to the homepage
      //TODO set in local cache
      this.props.history.push('/');
      return;
    }
    this.props.history.push(`/sign-up/${nextStep}`);
Sam Gluck's avatar
Sam Gluck committed
311
312
313
314
315
316
    this.scrollForStep(nextStep);
  }

  scrollForStep(step) {
    // https://gist.github.com/andjosh/6764939#gistcomment-2047675
    function scrollTo(element, to = 0, duration = 1000) {
317
318
319
      if (!element) {
        return;
      }
Sam Gluck's avatar
Sam Gluck committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
      const start = element.scrollTop;
      const change = to - start;
      const increment = 20;
      let currentTime = 0;
      const animateScroll = () => {
        currentTime += increment;
        element.scrollTop = easeInOutQuad(currentTime, start, change, duration);
        if (currentTime < duration) {
          setTimeout(animateScroll, increment);
        }
      };
      animateScroll();
    }
    function easeInOutQuad(t, b, c, d) {
      t /= d / 2;
      if (t < 1) return (c / 2) * t * t + b;
      t--;
      return (-c / 2) * (t * (t - 2) - 1) + b;
    }
    scrollTo(this._profileElem, stepScrollTo[step]);
Sam Gluck's avatar
Sam Gluck committed
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
  }

  /**
   * Produce a callback for an input's onChange prop that sets
   * the value of `field` at `this.state.user.{field}`.
   * @param field {String} field to create setter callback for
   **/
  linkUserState(field) {
    return evt =>
      this.setState({
        user: {
          ...this.state.user,
          [field]: evt.target.value
        }
      });
  }

  toggleUserInterest(interest: string) {
    let interests;
    if (this.state.user.interests.indexOf(interest) > -1) {
      interests = this.state.user.interests.filter(i => i !== interest);
    } else {
      interests = [...this.state.user.interests, interest];
    }
    this.setState({
      user: {
        ...this.state.user,
        interests
      }
    });
  }

  setUserImage(name: string): (evt: React.SyntheticEvent) => void {
    return (evt: any) => {
      const reader = new FileReader();

      reader.addEventListener(
        'load',
        () => {
          this.setState({
            user: {
              ...this.state.user,
              [name]: reader.result as string
            }
          });
        },
        false
      );

      if (evt.target.files[0]) {
        reader.readAsDataURL(evt.target.files[0]);
      }
    };
  }

  render() {
    if (!('step' in this.props.match.params)) {
      return <Redirect to="/sign-up/1" />;
    }

    return (
      <SignUpBody>
        <Sidebar>
          <Grid
            style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
          >
            <Row>
              <Col>
                <Logo link={false} />
                <PreviousStep
                  active={this.state.currentStep > 1}
                  onClick={this.goToPreviousStep}
                  title={`Go back to Step ${this.state.currentStep - 1}`}
                >
                  &lt;
                </PreviousStep>
              </Col>
            </Row>
            {this.getStepComponent()}
          </Grid>
        </Sidebar>
Sam Gluck's avatar
Sam Gluck committed
421
        <UserProfile innerRef={e => (this._profileElem = e)}>
Sam Gluck's avatar
Sam Gluck committed
422
          <UserProfileImage
Sam Gluck's avatar
Sam Gluck committed
423
            title="Click to select a profile background"
Sam Gluck's avatar
Sam Gluck committed
424
425
426
427
428
429
430
431
432
            backgroundImage={this.state.user.profileImage}
          >
            <FileInput
              onChange={this.setUserImage('profileImage')}
              type="file"
            />
            {!this.state.user.profileImage ? (
              <div
                style={{
Sam Gluck's avatar
Sam Gluck committed
433
                  pointerEvents: 'none',
Sam Gluck's avatar
Sam Gluck committed
434
435
436
437
438
439
440
441
                  position: 'relative',
                  top: '-20px',
                  textAlign: 'center'
                }}
              >
                <FontAwesomeIcon icon={faImage} />
                <P
                  style={{
Sam Gluck's avatar
Sam Gluck committed
442
                    pointerEvents: 'none',
Sam Gluck's avatar
Sam Gluck committed
443
444
445
446
447
                    marginTop: '-12px',
                    fontSize: '.8rem',
                    textShadow: '1px 1px 0 lightgrey'
                  }}
                >
Sam Gluck's avatar
Sam Gluck committed
448
                  Click to select
Sam Gluck's avatar
Sam Gluck committed
449
450
451
452
453
454
                  <br />a profile background
                </P>
              </div>
            ) : null}
          </UserProfileImage>
          <UserAvatar
Sam Gluck's avatar
Sam Gluck committed
455
            title="Click to select your profile image"
Sam Gluck's avatar
Sam Gluck committed
456
457
458
459
460
461
462
            backgroundImage={this.state.user.avatarImage}
          >
            <FileInput
              onChange={this.setUserImage('avatarImage')}
              type="file"
            />
            {!this.state.user.avatarImage ? (
Sam Gluck's avatar
Sam Gluck committed
463
464
465
466
467
468
469
              <>
                <FontAwesomeIcon icon={faUser} />
                <AvatarPlaceholder>
                  Click to select
                  <br />a profile picture
                </AvatarPlaceholder>
              </>
Sam Gluck's avatar
Sam Gluck committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
            ) : null}
          </UserAvatar>
          <UserDetails>
            <H6>{this.state.user.emojiId}</H6>
            <H6>
              <FadedFallbackText
                value={this.state.user.username}
                fallback="joebloggs84"
              />
            </H6>
            <H6>
              <FadedFallbackText
                value={this.state.user.role}
                fallback="Head Teacher"
              />
              <span style={{ color: 'lightgrey' }}>&nbsp;&nbsp;</span>
              <FadedFallbackText
                value={this.state.user.location}
                fallback="London, UK"
              />
            </H6>
          </UserDetails>
Sam Gluck's avatar
Sam Gluck committed
492
493
494
495
496
497
498
499
500
501
502
503
          <SignUpProfileSection>
            <Interests
              active={this.state.currentStep > 1}
              interests={this.state.user.interests}
            />
            <Languages
              active={this.state.currentStep > 1}
              languages={this.state.user.languages}
            />
          </SignUpProfileSection>
          {/*padding forces profile to be scrollable*/}
          <div style={{ height: '75%', width: '100%' }} />
Sam Gluck's avatar
Sam Gluck committed
504
505
506
507
508
        </UserProfile>
      </SignUpBody>
    );
  }
}