mitre-form-component
Version:
Componente de formulário de captação de leads para ser usado em projetos da Mitre Realty.
1,234 lines (1,137 loc) • 32.8 kB
JavaScript
// src/components/Form/index.tsx
import React3, { useState as useState3 } from "react";
// src/components/hooks/useError.ts
import { useState } from "react";
function useError() {
const [error, setError] = useState(null);
const handleError = (err) => {
const errorObj = err instanceof Error ? err : new Error(String(err));
setError(errorObj);
console.error(errorObj);
};
const clearError = () => setError(null);
return { error, handleError, clearError };
}
// src/components/Form/index.tsx
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { PhoneNumberUtil } from "google-libphonenumber";
// src/components/styles/utils.ts
function flex(direction = "row", alignItems, justifyContent) {
return `
align-items:${alignItems || null};
display:flex;
flex-direction:${direction};
justify-content:${justifyContent || null};
`;
}
var opacityEffect = `
&:hover {
cursor:pointer;
opacity:.9;
}
&:active {
opacity:.7;
}
`;
// src/components/Form/styles.ts
import styled from "styled-components";
var FormContainer = styled.div`
${flex("column")}
align-items: stretch;
justify-content: flex-start;
overflow-x: hidden;
overflow-y: auto;
background: ${(props) => props.$backgroundColor || "var(--gray-180)"};
padding: ${(props) => props.$innerPadding || "1rem"};
/* Hide scrollbars for WebKit browsers */
::-webkit-scrollbar {
display: none;
}
/* Hide scrollbars for Firefox */
scrollbar-width: none;
box-sizing: border-box;
height: 100%;
`;
var HeaderContainer = styled.div`
margin-bottom: 1rem;
`;
var ButtonContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
margin-top: 0.75rem;
button {
${opacityEffect}
color: var(--black);
font-weight: 600;
border: none;
border-radius: 8px;
width: 60%;
margin-top: 10px;
margin-bottom: 10px;
}
`;
var Form = styled.form`
label {
font-weight: 700;
}
input {
margin-bottom: 0.75rem;
}
p {
font-family: "Montserrat", sans-serif;
font-style: italic;
font-weight: 200;
font-size: 0.8rem;
color: ${(props) => props.$textColor || "var(--black)"};
text-align: start;
}
a {
font-family: "Montserrat", sans-serif;
font-style: italic;
font-weight: 200;
font-size: 0.8rem;
color: ${(props) => props.$textColor || "var(--black)"};
}
h6 {
text-align: start;
margin-left: 10px;
color: ${(props) => props.$textColor || "var(--black)"};
}
& > div {
margin-bottom: 10px;,
}
`;
var Title = styled.h2`
font-size: 1.25rem;
font-weight: 700;
line-height: 24px;
letter-spacing: 0em;
color: ${(props) => props.$textColor || "var(--black)"};
`;
var Text = styled.p`
font-size: 1rem;
font-weight: 400;
line-height: 23px;
letter-spacing: 0em;
margin-top: 10px;
color: ${(props) => props.$textColor || "var(--black)"};
`;
// src/components/styles/global.ts
import { createGlobalStyle } from "styled-components";
import { useEffect } from "react";
var GlobalStyles = createGlobalStyle`
:root {
--red: #e52e4d;
--white: #FFF;
--black: #2F2F2F;
--black-2:#1E1E1E;
--alphaBlack: #000000;
--black-2:#1E1E1E;
--black-3:#353535;
--yellow-400:#FFD789;
--yellow-500: #F6C76B;
--gray-40:#F0F0F0;
--gray-45:#767676;
--gray-50: #686A69;
--gray-60: #8F8F8F;
--gray-100: #B6B6B6;
--gray-150: #B9B9B9;
--gray-180: #CECECE;
--gray-200: #D2D2D2;
--gray-300: #EBEBEB;
--gray-400: #ECECEC;
--gray-500: #F4F4F4;
--gray-550:#6F6F6F;
--gray-600:#686868;
--gray-700: #535353;
--gray-800:#9D9D9D;
--shadow-500: 0px 4px 8px rgba(91, 91, 91, 0.2);
--green:#57C06E;
--green-2:#2DCE68;
--blue:#007BFF;
--transparent: transparent;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
@media (max-width: 1080px) {
font-size: 93.75%;
}
@media (max-width: 720px) {
font-size: 87.5%;
}
}
body {
background: var(--white);
-webkit-font-smoothing: antialiased;
}
body, input, textarea, select, button {
font-family: "Montserrat", sans-serif;
font-weight: 400;
}
h1, h2, h3, h4, h5, h6, strong {
font-weight: 600;
}
button {
cursor: pointer;
}
[disabled] {
opacity: 0.6;
cursor: not-allowed;
}
.hidden {
overflow: hidden;
}
::-webkit-scrollbar {
-webkit-appearance: none;
background: var(--gray-500);
width: 6px;
height: 10px;
}
::-webkit-scrollbar-thumb {
background-color: var(--gray-50);
}
.aligncenter {
text-align: center;
}
.width-190px {
width:190px;
}
.hidden-content {
display:none !important;
}
.global-margin-bottom {
margin-bottom:20px;
}
.background-light-gray {
background:#F4F4F4;
}
.full-width-and-height {
height:100%;
width:100%;
}
.flex-direction-column {
flex-direction:column;
}
.bold {
font-weight:700;
}
.margin-center-x {
margin:0 auto;
}
.border-none {
border:none;
}
.text-center {
text-align:center;
}
.relative {
position:relative;
}
/* accessibility */
body ._access-menu p._text-center{
font-family: "Montserrat", sans-serif;
font-style: italic;
font-size: 1.2rem!important;
margin-top: 6px;
margin-bottom: 3px;
}
`;
var FontLoader = () => {
useEffect(() => {
const link = document.createElement("link");
link.href = "https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700&display=swap";
link.rel = "stylesheet";
document.head.appendChild(link);
}, []);
return null;
};
var global_default = FontLoader;
// src/components/Input/index.tsx
import {
forwardRef,
useCallback
} from "react";
// src/components/Input/masks.ts
function cep(e) {
e.currentTarget.maxLength = 9;
let value = e.currentTarget.value;
value = value.replace(/\D/g, "");
value = value.replace(/^(\d{5})(\d)/, "$1-$2");
e.currentTarget.value = value;
return e;
}
function currency(e) {
let value = e.currentTarget.value;
value = value.replace(/\D/g, "");
value = value.replace(/(\d)(\d{2})$/, "$1,$2");
value = value.replace(/(?=(\d{3})+(\D))\B/g, ".");
e.currentTarget.value = value;
return e;
}
function cpf(e) {
e.currentTarget.maxLength = 14;
let value = e.currentTarget.value;
if (!value.match(/^(\d{3}).(\d{3}).(\d{3})-(\d{2})$/)) {
value = value.replace(/\D/g, "");
value = value.replace(/(\d{3})(\d)/, "$1.$2");
value = value.replace(/(\d{3})(\d)/, "$1.$2");
value = value.replace(/(\d{3})(\d{2})$/, "$1-$2");
e.currentTarget.value = value;
}
return e;
}
function date(e) {
let value = e.currentTarget.value;
value = value.replace(/\D/g, "");
value = value.replace(/(\d{2})(\d)/, "$1/$2");
value = value.replace(/(\d{2})(\d)/, "$1/$2");
e.currentTarget.value = value;
return e;
}
// src/components/Input/styles.ts
import styled2, { css } from "styled-components";
var FormLabel = styled2.label`
font-family: "Montserrat", sans-serif;
font-style: normal;
font-weight: 500;
font-size: 1rem;
color: ${(props) => props.$textColor || "var(--black)"};
display: block;
margin-bottom: 0.5rem;
text-align: left;
`;
var Input = styled2.input`
font-family: "Montserrat", sans-serif;
font-style: normal;
font-weight: 500;
font-size: 1rem;
line-height: 1.5rem;
background: ${(props) => props.$backgroundColor || "var(--white)"};
color: ${(props) => props.$textColor || "var(--black)"};
padding: 0.5rem;
border-radius: 0.125rem;
border: 1px solid ${(props) => props.$borderColor || "transparent"};
display: block;
height: 3.125rem;
width: 100%;
&:focus {
border-radius: 0.125rem;
border: 2px solid ${(props) => props.$focusBorderColor || "var(--yellow-500)"};
outline: none;
}
&::placeholder {
font-size: 1rem;
line-height: 1.5rem;
color: ${(props) => props.$placeholderColor || "var(--gray-100)"};
font-weight: 800;
}
/* Autofill styles */
&:-webkit-autofill {
background: ${(props) => props.$backgroundColor || "var(--white)"} !important;
color: ${(props) => props.$textColor || "var(--black)"} !important;
-webkit-text-fill-color: ${(props) => props.$textColor || "var(--black)"} !important;
transition: background-color 5000s ease-in-out 0s; /* Prevent flashing */
}
&:-webkit-autofill::first-line {
font-family: "Montserrat", sans-serif;
font-size: 1rem;
font-weight: 500;
}
`;
var FormErrorMessage = styled2.small`
font-size: 0.75rem;
line-height: 1.125rem;
color: var(--red);
margin-top: 0.25rem;
display: block;
`;
var FormControl = styled2.div.withConfig({
shouldForwardProp: (prop) => !["isInvalid"].includes(prop)
})`
${FormLabel} {
${(props) => props.isInvalid && css`
color: var(--red);
`};
}
${Input} {
${(props) => props.isInvalid && css`
border: 1px solid var(--red);
&:not(:focus)::placeholder {
color: var(--red);
font-weight: 600;
}
`};
&:focus {
${(props) => props.isInvalid && css`
border: 1px solid var(--red);
`};
}
}
`;
// src/components/Input/index.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var InputBase = ({
id,
label,
error,
showErrorMessage = true,
labelTextColor,
backgroundColor,
borderColor,
focusBorderColor,
inputPlaceholderColor,
inputTextColor,
mask = "",
type = "text",
...rest
}, ref) => {
const handleKeyUp = useCallback(
(e) => {
if (mask === "cep") cep(e);
if (mask === "currency") currency(e);
if (mask === "cpf") cpf(e);
if (mask === "date") date(e);
},
[mask]
);
return /* @__PURE__ */ jsxs(FormControl, { isInvalid: !!error, children: [
!!label && /* @__PURE__ */ jsx(FormLabel, { htmlFor: id, $textColor: labelTextColor, children: label }),
!mask ? /* @__PURE__ */ jsx(
Input,
{
id,
ref,
type,
"aria-invalid": !!error && showErrorMessage ? "true" : "false",
autoComplete: rest.autoComplete || "on",
$backgroundColor: backgroundColor,
$borderColor: borderColor,
$focusBorderColor: focusBorderColor,
$placeholderColor: inputPlaceholderColor,
$textColor: inputTextColor,
...rest
}
) : /* @__PURE__ */ jsx(
Input,
{
id,
ref,
type,
"aria-invalid": !!error && showErrorMessage ? "true" : "false",
autoComplete: rest.autoComplete || "on",
onKeyUp: handleKeyUp,
$backgroundColor: backgroundColor,
$borderColor: borderColor,
$focusBorderColor: focusBorderColor,
$placeholderColor: inputPlaceholderColor,
$textColor: inputTextColor,
...rest
}
),
!!error && showErrorMessage && /* @__PURE__ */ jsx(FormErrorMessage, { "data-testid": "error-message", children: typeof error === "string" ? error : error.message })
] });
};
var Input2 = forwardRef(InputBase);
// src/components/Button/styles.ts
import { darken } from "polished";
import styled3, { css as css2 } from "styled-components";
var Icon = styled3.span`
font-size: 0;
line-height: 0;
transition: all 0.25s ease;
transform: translate3d(-30px, 0px, 0px);
visibility: hidden;
opacity: 0;
margin-right: 0.625rem;
`;
var Text2 = styled3.span`
font-family: "Montserrat", sans-serif;
font-size: 1rem;
line-height: 1.5rem;
margin-bottom: -2px;
transition: all 0.25s ease;
`;
var TextSubmitting = styled3.span`
font-family: "Montserrat", sans-serif;
font-weight: 400;
font-size: 1rem;
transition: all 0.25s ease;
`;
var LoadingIcon = styled3.span.withConfig({
shouldForwardProp: (prop) => prop !== "hasText"
})`
display: block;
width: 1rem;
height: 1rem;
border: 0.125rem solid var(--white);
border-radius: 50%;
animation: loadingAnimation 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
border-color: var(--white) transparent transparent transparent;
margin-right: ${(props) => props.hasText ? "0.625rem" : "0"};
@keyframes loadingAnimation {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
`;
var Button = styled3.button.withConfig({
shouldForwardProp: (prop) => ![
"hasIcon",
"isSubmitting",
"hasSubmittingMessage",
"bgColor",
"bordercolor",
"color",
"height"
].includes(prop)
})`
background: ${(props) => darken(0.1, props?.bgColor || "#F6C76B")};
color: ${(props) => props?.color || "#2F2F2F"};
border: 1px solid ${(props) => darken(0.1, props?.bordercolor || "#F6C76B")};
border-radius: 2px;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0 0.75rem;
height: ${(props) => props?.height || "3.125rem"};
position: relative;
font-size: 0;
line-height: 0;
transition: all 0.25s;
${Icon} {
display: ${(props) => props?.hasIcon ? "block" : ""};
}
${Text2} {
transform: ${(props) => props?.hasIcon ? "translate3d(-4.5px, 0px, 0px)" : "unset"};
@media print, screen and (min-width: 40em) {
transform: ${(props) => props?.hasIcon ? "translate3d(-14.5px, 0px, 0px)" : "unset"};
}
color: ${(props) => props?.color || "#2F2F2F"};
}
&:hover {
background: ${(props) => darken(0.2, props?.bgColor || "#F6C76B")};
border-color: ${(props) => darken(0.2, props?.bordercolor || "#F6C76B")};
${Icon} {
opacity: 1;
visibility: visible;
transform: translate3d(0px, 0px, 0px);
}
${Text2} {
transform: ${(props) => props?.hasIcon ? "translate3d(-5px, 0px, 0px)" : "unset"};
}
}
${Text2} {
${(props) => props.isSubmitting && !props.hasSubmittingMessage && css2`
transform: unset;
opacity: 0;
`}
}
${LoadingIcon} {
${(props) => props.isSubmitting && !props.hasSubmittingMessage && css2`
display: flex;
-webkit-box-align: center;
align-items: center;
position: absolute;
`}
}
`;
// src/components/Button/index.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
function Button2({
children,
icon,
isSubmitting = false,
submittingMessage = "",
disabled = false,
color = "var(--black)",
...rest
}) {
return /* @__PURE__ */ jsxs2(
Button,
{
isSubmitting,
hasSubmittingMessage: submittingMessage.length > 0,
disabled: isSubmitting || disabled,
"aria-disabled": isSubmitting || disabled,
hasIcon: !!icon,
color,
...rest,
children: [
icon && !isSubmitting && /* @__PURE__ */ jsx2(Icon, { "data-testid": "button-icon", children: icon }),
isSubmitting && /* @__PURE__ */ jsx2(LoadingIcon, { hasText: submittingMessage.length > 0 }),
(!isSubmitting || submittingMessage.length === 0) && /* @__PURE__ */ jsx2(Text2, { className: "text", children }),
isSubmitting && submittingMessage.length > 0 && /* @__PURE__ */ jsx2(TextSubmitting, { children: submittingMessage })
]
}
);
}
// src/components/Alert/index.tsx
import { useEffect as useEffect2, useState as useState2, useCallback as useCallback2 } from "react";
// src/components/Alert/styles.ts
import styled4, { css as css3, keyframes } from "styled-components";
var fadeIn = keyframes`
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
`;
var fadeOut = keyframes`
from { opacity: 1; transform: translateY(0); }
to { opacity: 0; transform: translateY(-10px); }
`;
var typeStyles = {
error: css3`
background-color: var(--red);
border: 1px solid var(--red);
color: var(--white);
svg {
color: var(--white);
}
`,
warning: css3`
background-color: var(--yellow-500);
border: 1px solid var(--yellow-400);
color: var(--black);
svg {
color: var(--black);
}
`,
info: css3`
background-color: var(--blue);
border: 1px solid var(--blue);
color: var(--white);
svg {
color: var(--white);
}
`,
success: css3`
background-color: var(--green);
border: 1px solid var(--green-2);
color: var(--white);
svg {
color: var(--white);
}
`
};
var AlertContainer = styled4.div`
position: fixed;
width: 500px;
top: 15px;
right: 15px;
padding: 1rem ${({ $dismissible }) => $dismissible ? "2.5rem" : "1rem"} 1rem
1rem;
margin-bottom: 1rem;
animation: ${({ $isClosing }) => $isClosing ? fadeOut : fadeIn} 0.3s
ease-out;
animation-fill-mode: forwards;
align-items: center;
gap: 0.5rem;
box-shadow: var(--shadow-500);
border-radius: 0.5rem;
font-size: 1rem;
font-weight: 500;
${({ $type }) => typeStyles[$type]}
`;
var DismissButton = styled4.button`
position: absolute;
background: transparent;
right: 10px;
border: none;
cursor: pointer;
color: inherit;
opacity: 1;
transition: opacity 0.2s;
&:hover {
opacity: 0.7;
}
svg {
width: 1rem;
height: 1rem;
}
`;
// src/components/Alert/index.tsx
import { HiX } from "react-icons/hi";
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var Alert = ({
type = "info",
children,
className,
dismissible = false,
onDismiss,
autoDismiss
}) => {
const [isClosing, setIsClosing] = useState2(false);
const handleDismiss = useCallback2(() => {
setIsClosing(true);
setTimeout(() => onDismiss?.(), 300);
}, [onDismiss]);
useEffect2(() => {
if (autoDismiss) {
const timer = setTimeout(handleDismiss, autoDismiss);
return () => clearTimeout(timer);
}
}, [autoDismiss, handleDismiss]);
return /* @__PURE__ */ jsxs3(
AlertContainer,
{
$type: type,
$dismissible: dismissible,
$isClosing: isClosing,
className,
role: "alert",
children: [
children,
dismissible && /* @__PURE__ */ jsx3(
DismissButton,
{
onClick: handleDismiss,
"aria-label": "Dismiss alert",
children: /* @__PURE__ */ jsx3(HiX, {})
}
)
]
}
);
};
// src/components/PhoneInput/index.tsx
import {
forwardRef as forwardRef2
} from "react";
// src/components/PhoneInput/styles.ts
import styled5, { css as css4 } from "styled-components";
import { PhoneInput } from "react-international-phone";
import "react-international-phone/style.css";
var FormLabel2 = styled5.label`
font-family: "Montserrat", sans-serif;
font-style: normal;
font-weight: 500;
font-size: 1rem;
color: ${(props) => props.$textColor || "var(--black)"};
display: block;
margin-bottom: 0.5rem;
text-align: left;
`;
var StyledPhoneInput = styled5(PhoneInput)`
width: 100%;
height: 3.125rem;
background: ${(props) => props.$backgroundColor || "var(--white)"};
font-family: "Montserrat", sans-serif;
border: 1px solid ${(props) => props.$borderColor || "transparent"};
border-radius: 0.125rem;
&:focus-within {
border-radius: 0.125rem;
border: 2px solid ${(props) => props.$focusBorderColor || "var(--yellow-500)"};
outline: none;
.react-international-phone-country-selector-button {
border-right: 1px solid ${(props) => props.$focusBorderColor || "var(--yellow-500)"};
}
}
/* Style for the inner phone input container */
.react-international-phone-input-container {
width: 100%;
height: 100%;
display: flex;
align-items: center;
overflow: hidden;
font-family: "Montserrat", sans-serif;
font-size: 1rem;
font-weight: 500;
color: ${(props) => props.$textColor || "var(--black)"};
background: ${(props) => props.$backgroundColor || "var(--white)"};
}
/* Style for the country selector button */
.react-international-phone-country-selector-button {
height: 100%;
background: ${(props) => props.$backgroundColor || "var(--white)"};
display: flex;
align-items: center;
justify-content: center;
font-family: "Montserrat", sans-serif;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
outline: none;
border: none;
border-right: 1px solid ${(props) => props.$borderColor || "var(--transparent)"};
}
/* Style for the input itself */
input.react-international-phone-input {
flex: 1;
height: 100%;
padding: 0 0.5rem;
margin: 0;
background: ${(props) => props.$backgroundColor || "var(--white)"};
font-family: "Montserrat", sans-serif;
font-style: normal;
font-weight: 500;
font-size: 1rem;
line-height: 1.5rem;
color: ${(props) => props.$textColor || "var(--black)"};
outline: none;
border: none;
border-radius: 0.125rem;
&::placeholder {
font-size: 1rem;
line-height: 1.5rem;
color: ${(props) => props.$placeholderColor || "var(--gray-100)"};
font-weight: 800;
}
&:-webkit-autofill {
background: ${(props) => props.$backgroundColor || "var(--white)"} !important;
-webkit-text-fill-color: ${(props) => props.$textColor || "var(--black)"} !important;
transition: background-color 5000s ease-in-out 0s;
}
&:-webkit-autofill::first-line {
font-family: "Montserrat", sans-serif;
font-size: 1rem;
font-weight: 500;
}
}
`;
var FormErrorMessage2 = styled5.small`
font-size: 0.75rem;
line-height: 1.125rem;
color: var(--red);
margin-top: 0.25rem;
display: block;
`;
var FormControl2 = styled5.div.withConfig({
shouldForwardProp: (prop) => !["isInvalid"].includes(prop)
})`
${FormLabel2} {
${(props) => props.isInvalid && css4`
color: var(--red);
`};
}
${StyledPhoneInput} {
${(props) => props.isInvalid && css4`
border: 1px solid var(--red);
&:not(:focus)::placeholder {
color: var(--red);
font-weight: 600;
}
`};
.react-international-phone-input-container {
${(props) => props.isInvalid && css4`
border: 1px solid var(--red);
&:not(:focus)::placeholder {
color: var(--red);
font-weight: 600;
}
`};
}
.react-international-phone-country-selector-button {
${(props) => props.isInvalid && css4`
border-right: 1px solid var(--red);
`};
}
}
`;
// src/components/PhoneInput/index.tsx
import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
var PhoneInputBase = ({
id,
label,
error,
showErrorMessage = true,
labelTextColor,
backgroundColor,
borderColor,
focusBorderColor,
inputPlaceholderColor,
inputTextColor,
value,
...rest
}, ref) => {
return /* @__PURE__ */ jsxs4(FormControl2, { isInvalid: !!error, children: [
!!label && /* @__PURE__ */ jsx4(FormLabel2, { htmlFor: id, $textColor: labelTextColor, children: label }),
/* @__PURE__ */ jsx4(
StyledPhoneInput,
{
ref,
defaultCountry: "br",
disableCountryGuess: true,
disableDialCodeAndPrefix: true,
showDisabledDialCodeAndPrefix: false,
placeholder: rest.placeholder,
"aria-invalid": !!error && showErrorMessage ? "true" : "false",
value: String(value),
onChange: (phone, meta) => {
if (typeof rest.onChange === "function") {
rest.onChange({
phone,
dialCode: meta.country.dialCode,
inputValue: meta.inputValue
});
}
},
inputProps: {
id,
name: rest.name || "phone",
required: rest.required,
autoFocus: rest.autoFocus,
autoComplete: rest.autoComplete || "tel"
},
$backgroundColor: backgroundColor,
$borderColor: borderColor,
$focusBorderColor: focusBorderColor,
$placeholderColor: inputPlaceholderColor,
$textColor: inputTextColor
}
),
!!error && showErrorMessage && /* @__PURE__ */ jsx4(FormErrorMessage2, { "data-testid": "error-message", children: typeof error === "string" ? error : error?.message })
] });
};
var PhoneInput2 = forwardRef2(PhoneInputBase);
// src/components/Form/index.tsx
import { Fragment, jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
var phoneUtil = PhoneNumberUtil.getInstance();
var isPhoneValid = (phone) => {
try {
return phoneUtil.isValidNumber(phoneUtil.parseAndKeepRawInput(phone));
} catch (error) {
console.log("erro ao validar telefone = " + error);
return false;
}
};
var schema = yup.object().shape({
name: yup.string().required("Nome \xE9 obrigat\xF3rio"),
email: yup.string().required("Email \xE9 obrigat\xF3rio").email("Email inv\xE1lido"),
phone: yup.object().shape({
phone: yup.string().required("Telefone \xE9 obrigat\xF3rio!").test(
"is-valid-phone",
"N\xFAmero de telefone inv\xE1lido!",
function(value) {
const digitsOnly = value?.replace(/\D/g, "") || "";
return digitsOnly.length >= 8 && isPhoneValid(value);
}
),
inputValue: yup.string().required("Telefone \xE9 obrigat\xF3rio!"),
dialCode: yup.string().required("C\xF3digo de pa\xEDs \xE9 obrigat\xF3rio")
})
});
var MitreFormComponent = React3.forwardRef(({
productId,
apiUrl,
apiToken,
utm_source,
utm_medium,
utm_campaign,
utm_term,
showHeader = true,
backgroundColor = "var(--gray-180)",
textColor = "var(--black)",
buttonBackgroundColor = "#F6C76B",
buttonTextColor = "var(--black)",
innerPadding = "1rem",
inputBackgroundColor = "var(--white)",
inputBorderColor = "var(--transparent)",
inputFocusBorderColor = "var(--yellow-500)",
inputPlaceholderColor = "var(--gray-100)",
inputTextColor = "var(--black)"
}, ref) => {
const [loading, setIsLoading] = useState3(false);
const { error, handleError, clearError } = useError();
const [successMessage, setSuccessMessage] = useState3("");
const [formKey, setFormKey] = useState3(0);
const { control, register, handleSubmit, formState: { errors }, reset, clearErrors } = useForm({
resolver: yupResolver(schema),
mode: "onSubmit"
});
const resetForm = () => {
reset({
name: "",
email: "",
phone: { phone: "", inputValue: "", dialCode: "" }
}, {
keepErrors: false,
keepDirty: false,
keepTouched: false,
keepIsSubmitted: false,
keepSubmitCount: false,
keepValues: false,
keepDefaultValues: false
});
clearErrors();
setFormKey((k) => k + 1);
};
const sendMessage = async (data) => {
const { name, email, phone } = data;
const phoneValue = phone.inputValue;
const phoneDigitsOnly = phoneValue?.replace(/\D/g, "") || "";
const message = "Gostaria de mais informa\xE7\xF5es sobre o produto";
try {
setIsLoading(true);
if (!productId || !utm_source || !apiToken) {
throw new Error("Par\xE2metros obrigat\xF3rios n\xE3o informados");
}
const requestBody = {
name,
email,
phone: phoneDigitsOnly,
message,
productId,
utm_source
};
if (utm_medium) requestBody.utm_medium = utm_medium;
if (utm_campaign) requestBody.utm_campaign = utm_campaign;
if (utm_term) requestBody.utm_term = utm_term;
const response = await fetch(`${apiUrl}/leads`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Basic ${apiToken}`
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
console.log("response = " + JSON.stringify(response));
throw new Error("Falha ao enviar a mensagem!");
}
setSuccessMessage("Mensagem enviada com sucesso!");
resetForm();
} catch (err) {
handleError(err);
} finally {
setIsLoading(false);
}
};
return /* @__PURE__ */ jsxs5(Fragment, { children: [
/* @__PURE__ */ jsx5(global_default, {}),
/* @__PURE__ */ jsx5(GlobalStyles, {}),
error && /* @__PURE__ */ jsx5(
Alert,
{
type: "error",
dismissible: true,
onDismiss: clearError,
autoDismiss: 5e3,
children: error.message
}
),
successMessage && /* @__PURE__ */ jsx5(
Alert,
{
type: "success",
dismissible: true,
onDismiss: () => setSuccessMessage(""),
autoDismiss: 5e3,
children: successMessage
}
),
/* @__PURE__ */ jsxs5(FormContainer, { $backgroundColor: backgroundColor, $innerPadding: innerPadding, ref, children: [
showHeader && /* @__PURE__ */ jsxs5(HeaderContainer, { children: [
/* @__PURE__ */ jsx5(Title, { $textColor: textColor, children: "Atendimento por mensagem" }),
/* @__PURE__ */ jsx5(Text, { $textColor: textColor, children: "Informe seus dados e retornaremos a mensagem." })
] }),
/* @__PURE__ */ jsxs5(Form, { $textColor: textColor, onSubmit: handleSubmit(sendMessage), noValidate: true, children: [
/* @__PURE__ */ jsx5(
Input2,
{
id: "name",
label: "Nome *",
placeholder: "Digite seu nome",
...register("name"),
error: errors.name?.message,
autoComplete: "name",
required: true,
labelTextColor: textColor,
backgroundColor: inputBackgroundColor,
borderColor: inputBorderColor,
focusBorderColor: inputFocusBorderColor,
inputPlaceholderColor,
inputTextColor
}
),
/* @__PURE__ */ jsx5(
Input2,
{
id: "email",
label: "Email *",
type: "email",
placeholder: "exemplo@email.com",
...register("email"),
error: errors.email?.message,
autoComplete: "email",
required: true,
labelTextColor: textColor,
backgroundColor: inputBackgroundColor,
borderColor: inputBorderColor,
focusBorderColor: inputFocusBorderColor,
inputPlaceholderColor,
inputTextColor
}
),
/* @__PURE__ */ jsx5(
Controller,
{
name: "phone",
control,
defaultValue: { phone: "", inputValue: "", dialCode: "" },
shouldUnregister: true,
render: ({ field }) => {
const errorMsg = errors.phone?.inputValue?.message || errors.phone?.phone?.message || errors.phone?.message;
return /* @__PURE__ */ jsx5(
PhoneInput2,
{
id: "phone",
label: "Telefone *",
placeholder: "(11) 00000-0000",
error: errorMsg,
required: true,
value: field.value.phone,
onChange: field.onChange,
name: field.name,
labelTextColor: textColor,
backgroundColor: inputBackgroundColor,
borderColor: inputBorderColor,
focusBorderColor: inputFocusBorderColor,
inputPlaceholderColor,
inputTextColor
}
);
}
},
formKey
),
/* @__PURE__ */ jsx5("h6", { children: "* Campos de preenchimento obrigat\xF3rio." }),
/* @__PURE__ */ jsx5(ButtonContainer, { children: /* @__PURE__ */ jsx5(Button2, { bgColor: buttonBackgroundColor, color: buttonTextColor, type: "submit", isSubmitting: loading, children: "Enviar mensagem" }) }),
/* @__PURE__ */ jsxs5("p", { children: [
"A Mitre Realty respeita a sua privacidade e utiliza os seus dados pessoais para contat\xE1-lo por e-mail ou telefone aqui registrados. Para saber mais, acesse a nossa",
" ",
/* @__PURE__ */ jsx5(
"a",
{
href: "https://www.mitrerealty.com.br/politica-de-privacidade",
target: "_blank",
rel: "noopener noreferrer",
children: "Pol\xEDtica de Privacidade"
}
),
". Ao clicar em ",
'"',
"enviar",
'"',
", voc\xEA concorda em permitir que a Mitre Realty, armazene e processe os dados pessoais fornecidos por voc\xEA para finalidade informada"
] })
] })
] })
] });
});
MitreFormComponent.displayName = "MitreFormComponent";
var Form_default = MitreFormComponent;
export {
Form_default as MitreFormComponent
};
//# sourceMappingURL=index.js.map