summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.jsx
blob: 0929b8f7113acc59a56fda6b849a1491443d9c05 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

import { isEmailOrPhoneNumber } from "./isEmailOrPhoneNumber";
import React from "react";
import { SubmitFormSnippet } from "../SubmitFormSnippet/SubmitFormSnippet.jsx";

function validateInput(value, content) {
  const type = isEmailOrPhoneNumber(value, content);
  return type ? "" : "Must be an email or a phone number.";
}

function processFormData(input, message) {
  const { content } = message;
  const type = content.include_sms
    ? isEmailOrPhoneNumber(input.value, content)
    : "email";
  const formData = new FormData();
  let url;
  if (type === "phone") {
    url = "https://basket.mozilla.org/news/subscribe_sms/";
    formData.append("mobile_number", input.value);
    formData.append("msg_name", content.message_id_sms);
    formData.append("country", content.country);
  } else if (type === "email") {
    url = "https://basket.mozilla.org/news/subscribe/";
    formData.append("email", input.value);
    formData.append("newsletters", content.message_id_email);
    formData.append(
      "source_url",
      encodeURIComponent(`https://snippets.mozilla.com/show/${message.id}`)
    );
  }
  formData.append("lang", content.locale);
  return { formData, url };
}

function addDefaultValues(props) {
  return {
    ...props,
    content: {
      scene1_button_label: "Learn more",
      retry_button_label: "Try again",
      scene2_dismiss_button_text: "Dismiss",
      scene2_button_label: "Send",
      scene2_input_placeholder: "Your email here",
      locale: "en-US",
      country: "us",
      message_id_email: "",
      include_sms: false,
      ...props.content,
    },
  };
}

export const SendToDeviceSnippet = props => {
  const propsWithDefaults = addDefaultValues(props);

  return (
    <SubmitFormSnippet
      {...propsWithDefaults}
      form_method="POST"
      className="send_to_device_snippet"
      inputType={propsWithDefaults.content.include_sms ? "text" : "email"}
      validateInput={
        propsWithDefaults.content.include_sms ? validateInput : null
      }
      processFormData={processFormData}
    />
  );
};

export const SendToDeviceScene2Snippet = props => {
  return <SendToDeviceSnippet expandedAlt={true} {...props} />;
};