Добавил капчу, проверку файлов, отправку формы на сервер, возможность открепить файл, отредачил стили

This commit is contained in:
ifraimka committed 2024-11-19 14:43:37 +03:00
1 parent 963ad3b544
commit c58507ac4e
9 files changed
+329 -50

No files matched your search

+47
View File
@@ -12,10 +12,12 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@yandex/smart-captcha": "2.6.1",
"html-react-parser": "^5.1.10",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-google-recaptcha": "^3.1.0",
"react-router-dom": "^6.22.0",
"react-router-hash-link": "^2.4.3",
"react-scripts": "5.0.1",
@@ -4969,6 +4971,14 @@
"resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz",
"integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ=="
},
"node_modules/@yandex/smart-captcha": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/@yandex/smart-captcha/-/smart-captcha-2.6.1.tgz",
"integrity": "sha512-FlX/P54x1FOqZvng41N/qnzHi4e+s0fPeA1MS9AUO2Gu2/0Q5BZX62DO7u06lkhoqZ0nNqjelDNjMjMXcrsNWQ==",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
}
},
"node_modules/abab": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz",
@@ -9176,6 +9186,19 @@
"he": "bin/he"
}
},
"node_modules/hoist-non-react-statics": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
"integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==",
"dependencies": {
"react-is": "^16.7.0"
}
},
"node_modules/hoist-non-react-statics/node_modules/react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
},
"node_modules/hoopy": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/hoopy/-/hoopy-0.1.4.tgz",
@@ -15024,6 +15047,18 @@
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",
"integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg=="
},
"node_modules/react-async-script": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/react-async-script/-/react-async-script-1.2.0.tgz",
"integrity": "sha512-bCpkbm9JiAuMGhkqoAiC0lLkb40DJ0HOEJIku+9JDjxX3Rcs+ztEOG13wbrOskt3n2DTrjshhaQ/iay+SnGg5Q==",
"dependencies": {
"hoist-non-react-statics": "^3.3.0",
"prop-types": "^15.5.0"
},
"peerDependencies": {
"react": ">=16.4.1"
}
},
"node_modules/react-dev-utils": {
"version": "12.0.1",
"resolved": "https://registry.npmjs.org/react-dev-utils/-/react-dev-utils-12.0.1.tgz",
@@ -15158,6 +15193,18 @@
"resolved": "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-6.0.11.tgz",
"integrity": "sha512-/6UZ2qgEyH2aqzYZgQPxEnz33NJ2gNsnHA2o5+o4wW9bLM/JYQitNP9xPhsXwC08hMMovfGe/8retsdDsczPRg=="
},
"node_modules/react-google-recaptcha": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/react-google-recaptcha/-/react-google-recaptcha-3.1.0.tgz",
"integrity": "sha512-cYW2/DWas8nEKZGD7SCu9BSuVz8iOcOLHChHyi7upUuVhkpkhYG/6N3KDiTQ3XAiZ2UAZkfvYKMfAHOzBOcGEg==",
"dependencies": {
"prop-types": "^15.5.0",
"react-async-script": "^1.2.0"
},
"peerDependencies": {
"react": ">=16.4.1"
}
},
"node_modules/react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
+2
View File
@@ -7,10 +7,12 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@yandex/smart-captcha": "2.6.1",
"html-react-parser": "^5.1.10",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-google-recaptcha": "^3.1.0",
"react-router-dom": "^6.22.0",
"react-router-hash-link": "^2.4.3",
"react-scripts": "5.0.1",
+25
View File
@@ -15,6 +15,31 @@ const wp = new WPAPI(
: { endpoint: reactPress.api.rest_url, nonce: reactPress.api.nonce }
);
console.log(wp);
export async function sendContactForm(formData) {
console.log('Форма отправляется');
for (let el of formData.entries()) {
console.log(el[0] + ': ' + el[1]);
}
try {
const response = await fetch(`${wp._options.endpoint}skbkit/v1/sendcontactform`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
console.log(response);
console.log(response.body);
throw new Error('Ошибка сети', response);
}
return response;
} catch (error) {
console.error('Ошибка отправки формы (api):', error);
}
}
function parseContent(str) {
if (typeof str !== 'string') return str;
const content = Parse(str);
+1
View File
@@ -0,0 +1 @@
<!-- icon666.com - MILLIONS vector ICONS FREE --><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><g><polygon points="512,59.076 452.922,0 256,196.922 59.076,0 0,59.076 196.922,256 0,452.922 59.076,512 256,315.076 452.922,512 512,452.922 315.076,256 " fill="#000000" style="fill: rgb(255, 0, 0);"></polygon></g></g></svg>

After

Width:  |  Height:  |  Size: 487 B

+1
View File
@@ -2,5 +2,6 @@ export { default as car } from './car.jpeg';
export { default as newsMock } from './newsMock.png';
export { default as scb } from './scb.svg';
export { default as fileUpload } from './fileUpload.svg';
export { default as cross } from './cross.svg';
export { default as arrow } from './arrow.svg';
export { default as labMock } from './labMock.jpeg';
+107 -5
View File
@@ -1,14 +1,87 @@
import { useCallback, useState } from "react";
import { Form } from "react-router-dom";
import { SmartCaptcha } from "@yandex/smart-captcha";
import { sendContactForm } from "../../api";
import Field from "../Field";
import "./ContactForm.styles.scss";
import { fileUpload } from "../../assets/images";
function ContactForm() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: '',
file: null,
captcha: '',
});
const [isSubmitting, setIsSubmitting] = useState(false);
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const handleFileChange = (e) => {
const extension = e.target.files[0].name.match(/\.([^.]+)$/)[1];
switch (extension) {
case 'doc':
case 'docx':
case 'pdf':
case 'txt':
case 'pptx':
case 'ppt':
setFormData({ ...formData, file: e.target.files[0] });
break;
default:
alert('Неверный формат файла.');
}
};
const handleRemoveFile = () => {
setFormData({ ...formData, file: null });
};
const handleCaptchaChange = (token) => {
setFormData({ ...formData, captcha: token });
console.log('Капча пришла');
};
const handleTokenExpired = useCallback(() => {
setFormData({ ...formData, captcha: null });
console.log('Капча просрочилась');
}, []);
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
console.log('handleSubmit isSubmitting: ', isSubmitting);
const formDataObj = new FormData();
formDataObj.append('name', formData.name);
formDataObj.append('email', formData.email);
formDataObj.append('message', formData.message);
formDataObj.append('file', formData.file);
formDataObj.append('captcha', formData.captcha);
try {
const response = await sendContactForm(formDataObj);
if (response) {
alert('Сообщение отправлено!');
console.log('response', response);
} else {
alert('Ошибка отправки.');
}
} catch (error) {
console.error('Ошибка:', error);
alert('Ошибка отправки.');
} finally {
setIsSubmitting(false);
}
};
return (
<Form method="post" className="half contact-form">
<Form method="post" onSubmit={handleSubmit} className="half contact-form">
<h2>Свяжитесь с нами!</h2>
<div className="inputs">
<div className="row">
@@ -17,31 +90,60 @@ function ContactForm() {
type="text"
name="name"
placeholder="Имя"
value={formData.name}
onChange={handleChange}
required
isDisabled={isSubmitting}
/>
<Field
key={2}
type="email"
name="email"
placeholder="E-mail"
value={formData.email}
onChange={handleChange}
required
isDisabled={isSubmitting}
/>
</div>
<Field
key={3}
type="textarea"
name="text"
name="message"
placeholder="Опишите в этом поле свой проект и, по возможности, прикрепите файл с ТЗ"
value={formData.message}
onChange={handleChange}
required
isDisabled={isSubmitting}
/>
<div className="row">
<Field
key={4}
type="file"
name="file"
icon={fileUpload}
onChange={handleFileChange}
handleRemoveFile={handleRemoveFile}
fileAttached={formData && formData.file ? true : false}
isDisabled={isSubmitting}
/>
<div className="submit-container">
{formData.captcha ? (
<Field
key={5}
type="submit"
value={isSubmitting ? 'Отправляется' : 'Отправить'}
isDisabled={isSubmitting}
/>
) : (
<SmartCaptcha
key={6}
sitekey="ysc1_8nFqhYasby2fJ9J7pCTxdBMe0Xc3Y6CrWk4aylB03d4f0045"
onSuccess={handleCaptchaChange}
onTokenExpired={handleTokenExpired}
style={formData.captcha ? { display: 'none' } : { display: 'block' }}
/>
)}
</div>
</div>
</div>
</Form>
@@ -26,22 +26,94 @@ $color-file-button: rgb(7, 42, 200);
box-sizing: border-box;
}
*:disabled {
background: dimgrey;
}
.row {
display: flex;
gap: $gap;
}
.file-input * {
.field {
padding: 12px 16px;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 400;
}
.field.big {
height: 200px;
line-height: 30px;
resize: none;
}
.file-input-container {
display: flex;
flex-direction: row;
align-items: center;
.file-input {
position: relative;
width: fit-content;
color: $color-file-button;
font-weight: 500;
input {
position: absolute;
z-index: -1;
opacity: 0;
display: block;
width: 0;
height: 0;
}
.upload-file-btn {
display: flex;
cursor: pointer;
.icon {
filter: invert(15%) sepia(100%) saturate(2861%) hue-rotate(229deg) brightness(93%) contrast(120%);
}
span {
display: inline-block;
font-size: 18px;
}
}
}
.icon {
margin-right: 6px;
height: $icon-size;
width: $icon-size;
filter: invert(15%) sepia(100%) saturate(2861%) hue-rotate(229deg) brightness(93%) contrast(120%);;
}
.remove-btn {
display: flex;
width: fit-content;
height: fit-content;
padding: 0;
background: transparent;
border: none;
cursor: pointer;
.icon.remove {
margin-left: 6px;
filter: hue-rotate(0) !important;
height: calc($icon-size * 0.75);
width: calc($icon-size * 0.75);
}
}
}
.file-input input:focus+.upload-file-btn {
outline: -webkit-focus-ring-color auto 1px;
}
.submit-container {
.submit {
width: 100%;
@@ -51,5 +123,11 @@ $color-file-button: rgb(7, 42, 200);
font-size: 18px;
line-height: normal;
}
>div>div>div {
margin-left: auto;
margin-right: auto;
}
}
}
}
+27 -4
View File
@@ -1,6 +1,7 @@
import "./Field.styles.scss";
import { fileUpload, cross } from "../../assets/images";
function Field({ type, name, placeholder, icon }) {
function Field({ type, name, placeholder, value, onChange, isDisabled = false, fileAttached = false, handleRemoveFile = null }) {
const className = type === "submit" ? "submit btn"
: type === "textarea" ? "field big"
: "field";
@@ -12,21 +13,43 @@ function Field({ type, name, placeholder, icon }) {
className={className}
name={name}
placeholder={placeholder}
value={value}
onChange={onChange}
required
disabled={isDisabled}
/>
) : type === "file" ? (
<div className="file-input-container">
<label className="file-input">
<input type="file" name="file" />
<input
type="file"
name="file"
value={value}
onChange={onChange}
disabled={isDisabled}
accept=".doc,.docx,.txt,.pdf,.ppt,.pptx"
/>
<div className="upload-file-btn">
<img src={icon} alt="" className="icon" />
<span>Прикрепить файл</span>
<img src={fileUpload} alt="" className="icon" />
<span>{fileAttached ? 'Файл прикреплен' : 'Прикрепить файл'}</span>
</div>
</label>
{fileAttached &&
<button className="remove-btn icon" onClick={handleRemoveFile}>
<img src={cross} alt="Открепить файл" className="icon remove" />
</button>
}
</div>
) : (
<input
className={className}
type={type}
name={name}
placeholder={placeholder}
value={value}
onChange={onChange}
required
disabled={isDisabled}
/>
)}
</>
+39 -39
View File
@@ -1,47 +1,47 @@
.field {
padding: 12px 16px;
border: none;
border-radius: 8px;
// .field {
// padding: 12px 16px;
// border: none;
// border-radius: 8px;
font-size: 16px;
font-weight: 400;
}
// font-size: 16px;
// font-weight: 400;
// }
.field.big {
height: 200px;
line-height: 30px;
resize: none;
}
// .field.big {
// height: 200px;
// line-height: 30px;
// resize: none;
// }
.file-input {
position: relative;
width: fit-content;
// .file-input {
// position: relative;
// width: fit-content;
input {
position: absolute;
z-index: -1;
opacity: 0;
display: block;
width: 0;
height: 0;
}
// input {
// position: absolute;
// z-index: -1;
// opacity: 0;
// display: block;
// width: 0;
// height: 0;
// }
.upload-file-btn {
display: flex;
cursor: pointer;
// .upload-file-btn {
// display: flex;
// cursor: pointer;
.icon {
margin-right: 6px;
height: 22px;
}
// .icon {
// margin-right: 6px;
// height: 22px;
// }
span {
display: inline-block;
font-size: 18px;
}
}
}
// span {
// display: inline-block;
// font-size: 18px;
// }
// }
// }
.file-input input:focus + .upload-file-btn {
outline: -webkit-focus-ring-color auto 1px;
}
// .file-input input:focus + .upload-file-btn {
// outline: -webkit-focus-ring-color auto 1px;
// }