SignUp.tsx 9.6 KB
Newer Older
Sam Gluck's avatar
Sam Gluck committed
1
2
3
4
5
6
7
8
import * as React from 'react';
import { Redirect, RouteComponentProps } from 'react-router';
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 PreviousStep from './PreviousStep';
9
import Tag, { TagContainer } from '../../components/elements/Tag/Tag';
Sam Gluck's avatar
Sam Gluck committed
10
11
import Step1 from './Step1';
import Step2 from './Step2';
12
import UserProfile from '../user/UserProfile';
Sam Gluck's avatar
Sam Gluck committed
13
import User from '../../types/User';
14
15
import H4 from '../../components/typography/H4/H4';
import Button from '../../components/elements/Button/Button';
Sam Gluck's avatar
Sam Gluck committed
16
17
18
19
20
21
22
23
24

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
25
  min-width: 500px;
Sam Gluck's avatar
Sam Gluck committed
26
27
28
29
30
31
  height: 100%;
  padding: 25px;
  background-color: ${(props: StyledThemeInterface) =>
    props.theme.styles.colour.base5};
`;

Sam Gluck's avatar
Sam Gluck committed
32
33
34
35
36
const stepScrollTo = {
  1: 0,
  2: 650
};

Sam Gluck's avatar
Sam Gluck committed
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
//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
78
  user: User;
Sam Gluck's avatar
Sam Gluck committed
79
80
81
82
}

interface SignUpProps extends RouteComponentProps<SignUpMatchParams> {}

83
84
85
const SignUpProfileSection = styled.div<any>`
  padding: 50px;
`;
Sam Gluck's avatar
Sam Gluck committed
86

Sam Gluck's avatar
Sam Gluck committed
87
88
89
90
91
92
const Step2Section = styled.div<any>`
  opacity: ${props => (props.active ? 1 : 0.1)};
  pointer-events: ${props => (props.active ? 'unset' : 'none')};
  transition: opacity 1.75s linear;
`;

93
const Interests = ({ active, interests, onTagClick }) => (
Sam Gluck's avatar
Sam Gluck committed
94
95
  <Step2Section active={active}>
    <H4>Interests</H4>
96
97
98
99
100
101
102
103
104
105
106
107
    <TagContainer>
      {interests.map(interest => (
        <Tag
          focused
          closeable
          key={interest}
          onClick={() => onTagClick(interest)}
        >
          {interest}
        </Tag>
      ))}
    </TagContainer>
Sam Gluck's avatar
Sam Gluck committed
108
109
  </Step2Section>
);
Sam Gluck's avatar
Sam Gluck committed
110

Sam Gluck's avatar
Sam Gluck committed
111
112
113
114
115
const Languages = ({ active, languages }) => (
  <Step2Section active={active}>
    <H4>Languages</H4>
  </Step2Section>
);
Sam Gluck's avatar
Sam Gluck committed
116
117
118
119

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

Sam Gluck's avatar
Sam Gluck committed
120
121
  _profileElem: HTMLElement;

Sam Gluck's avatar
Sam Gluck committed
122
123
124
125
126
127
128
129
130
131
132
133
134
  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
135
    } as User
Sam Gluck's avatar
Sam Gluck committed
136
137
138
139
140
141
142
  };

  constructor(props) {
    super(props);

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

Sam Gluck's avatar
Sam Gluck committed
143
144
145
146
    if (!this.state.user.username && this.state.currentStep > 1) {
      this.props.history.replace('/sign-up');
      return;
    }
Sam Gluck's avatar
Sam Gluck committed
147
148
149
150
151
152
153
154
155
156
157

    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);
158
    this.scrollForStep(this.state.currentStep);
Sam Gluck's avatar
Sam Gluck committed
159
160
161
162
163
164
165
166
  }

  getStepComponent() {
    const stepIdx = this.state.currentStep - 1;
    let Step = SignUp.stepComponents[stepIdx];
    if (!Step) {
      return null;
    }
167
168
169
170
171
172
173
174
175
176
177
178
    return (
      <Step
        {...{
          user: this.state.user,
          goToNextStep: this.goToNextStep,
          goToPreviousStep: this.goToPreviousStep,
          randomizeEmojiId: this.randomizeEmojiId,
          linkUserState: this.linkUserState,
          toggleInterest: this.toggleUserInterest
        }}
      />
    );
Sam Gluck's avatar
Sam Gluck committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
  }

  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
194
      this.scrollForStep(prevStep);
Sam Gluck's avatar
Sam Gluck committed
195
196
197
198
199
200
201
202
203
204
205
206
207
    }
  }

  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
208
209
210
211
212
213
    this.scrollForStep(nextStep);
  }

  scrollForStep(step) {
    // https://gist.github.com/andjosh/6764939#gistcomment-2047675
    function scrollTo(element, to = 0, duration = 1000) {
214
215
216
      if (!element) {
        return;
      }
Sam Gluck's avatar
Sam Gluck committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
      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
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
  }

  /**
   * 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
      }
    });
  }

269
270
271
272
273
274
275
276
  /**
   * Load an image from the user file system and set as `imageTypeName` on the
   * state so it can be displayed without uploading.
   * @param imageTypeName the type of image being set
   */
  setUserImage(
    imageTypeName: 'profileImage' | 'avatarImage'
  ): (evt: React.SyntheticEvent) => void {
Sam Gluck's avatar
Sam Gluck committed
277
278
279
280
281
282
283
284
285
    return (evt: any) => {
      const reader = new FileReader();

      reader.addEventListener(
        'load',
        () => {
          this.setState({
            user: {
              ...this.state.user,
286
              [imageTypeName]: reader.result as string
Sam Gluck's avatar
Sam Gluck committed
287
288
289
290
291
292
293
294
295
296
297
298
            }
          });
        },
        false
      );

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

299
300
301
302
  private getNextStepName() {
    return ['your interests', 'discover'][this.state.currentStep - 1];
  }

Sam Gluck's avatar
Sam Gluck committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
  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()}
327
328
329
330
            <Row style={{ flexGrow: 1 }} />
            <Row>
              {this.getNextStepName() ? (
                <Col
Sam Gluck's avatar
Sam Gluck committed
331
                  style={{
332
333
334
                    display: 'flex',
                    alignItems: 'center',
                    color: 'grey'
Sam Gluck's avatar
Sam Gluck committed
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
373
                  Next: {this.getNextStepName()}
                </Col>
              ) : null}
              <Col style={{ display: 'flex', justifyContent: 'flex-end' }}>
                {this.state.currentStep > 1 ? (
                  <>
                    <Button secondary onClick={this.goToNextStep}>
                      Skip
                    </Button>
                    <div style={{ height: '10px', width: '10px' }} />
                  </>
                ) : null}
                <Button onClick={this.goToNextStep}>Continue</Button>
              </Col>
            </Row>
          </Grid>
        </Sidebar>
        <UserProfile
          innerRef={e => (this._profileElem = e)}
          user={this.state.user}
          setUserImage={this.setUserImage}
          body={({ containerProps }) => {
            return (
              <SignUpProfileSection {...containerProps}>
                <Interests
                  onTagClick={this.toggleUserInterest}
                  active={this.state.currentStep > 1}
                  interests={this.state.user.interests}
                />
                <Languages
                  active={this.state.currentStep > 1}
                  languages={this.state.user.languages}
                />
              </SignUpProfileSection>
            );
          }}
        />
Sam Gluck's avatar
Sam Gluck committed
374
375
376
377
      </SignUpBody>
    );
  }
}