This commit is contained in:
DavidMakarov 2023-12-01 18:59:00 +04:00
parent 6f6a125355
commit 039f4dd392
20 changed files with 3369 additions and 137 deletions

21
.eslintrc.json Normal file
View File

@ -0,0 +1,21 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": "airbnb-base",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
"quotes": "off",
"indent": "off",
"no-console": "off",
"no-use-before-define": "off",
"no-alert": "off",
"no-restricted-globals": "off",
"quote-props": "off",
"linebreak-style": 0
}
}

View File

@ -7,7 +7,8 @@
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header class="border-bottom ps-5 pe-5" style="background-color: #6376D7;">
@ -37,125 +38,19 @@
<main class="container-fluid">
<div class="table-responsive">
<h1 class="p-3">Товары</h1>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Название</th>
<th scope="col">Цена</th>
<th scope="col">Фотографии</th>
<th scope="col">Наличие в магазинах</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>SSD-накопитель Kingston A400</td>
<td>5 400 ₽</td>
<td>/content/catalog/Kingston A400.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Смартфон Samsung A54 6/128GB</td>
<td>35 750 ₽</td>
<td>/content/catalog/Samsung A54.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Смартфон Samsung S23+ 8/256GB</td>
<td>110 990 ₽</td>
<td>/content/catalog/Samsung S23+.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">4</th>
<td>Смартфон POCO X5 Pro 5G 8/256GB</td>
<td>39 990 ₽</td>
<td>/content/catalog/POCO X5 Pro.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">5</th>
<td>Беспроводная игровая мышь SteelSeries AEROX 3</td>
<td>9 490 ₽</td>
<td>/content/catalog/Steelseries Aerox 3 Wireless.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">6</th>
<td>Консоль Microsoft XBOX Series X</td>
<td>82 000 ₽</td>
<td>/content/catalog/XBOX Series X.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">7</th>
<td>Видеокарта ASUS NVIDIA DUAL RTX4070</td>
<td>76 000 ₽</td>
<td>/content/catalog/GeForce RTX4070.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">8</th>
<td>Игровая приставка Sony PlayStation 5</td>
<td>58 990 ₽</td>
<td>/content/catalog/PS5.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">9</th>
<td>Процессор AMD Ryzen 7 5800X3D OEM</td>
<td>44 290 ₽</td>
<td>/content/catalog/Ryzen 7 5800X3D.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">10</th>
<td>Процессор AMD Ryzen 5 5600G OEM</td>
<td>14 590 ₽</td>
<td>/content/catalog/Ryzen 5 5600G.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">11</th>
<td>Процессор AMD Ryzen 5 7600X OEM</td>
<td>29 590 ₽</td>
<td>/content/catalog/Ryzen 5 7600X.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">12</th>
<td>Кулер для процессора DEEPCOOL AG200</td>
<td>1 590 ₽</td>
<td>/content/catalog/DEEPCOOL AG200.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">13</th>
<td>Оперативная память Kingston 16Gb DDR4</td>
<td>5 190 ₽</td>
<td>/content/catalog/Kingston 16GB DDR4 3200MHz.jp</td>
<td>3</td>
</tr>
<tr>
<th scope="row">14</th>
<td>SSD накопитель Samsung 980 PRO 1TB M.2</td>
<td>15 190 ₽</td>
<td>/content/catalog/Samsung 980 PRO.jpg</td>
<td>3</td>
</tr>
<tr>
<th scope="row">15</th>
<td>Процессор Intel Core i5 13600KF OEM</td>
<td>42 613 ₽</td>
<td>/content/catalog/Intel Core i5 13600KF.jpg</td>
<td>3</td>
</tr>
</tbody>
</table>
<button class="btn btn-main mb-5">Редактировать</button>
<table id="items-table" class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Название</th>
<th scope="col">Цена</th>
<th scope="col">Количество в магазинах</th>
<th scope="col">Изображение</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button id="items-add" class="btn btn-main mb-5">Добавить</button>
</div>
</main>
<footer class="container-fluid py-5" style="background-color: #6376D7;">
@ -173,5 +68,55 @@
</div>
</div>
</footer>
<div id="items-update" class="modal fade" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
<div class="modal-dialog">
<form id="items-form" class="needs-validation" novalidate>
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="items-update-title"></h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="text-center">
<img id="image-preview" src="https://via.placeholder.com/200" class="rounded rounded-circle"
alt="placeholder">
</div>
<input id="items-line-id" type="number" hidden>
<div class="mb-2">
<label for="name" class="form-label">Название</label>
<input id="name" class="form-control" name="selected" required>
</div>
<div class="mb-2">
<label class="form-label" for="price">Цена</label>
<input id="price" name="price" class="form-control" type="number" value="0.00" min="0.00"
step="0.50" required>
</div>
<div class="mb-2">
<label class="form-label" for="count">Количество</label>
<input id="count" name="count" class="form-control" type="number" value="0" min="1" step="1"
required>
</div>
<div class="mb-2">
<label class="form-label" for="image">Изображение</label>
<input id="image" name="image" type="file" class="form-control" accept="image/*" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="submit" class="btn btn-primary">Сохранить</button>
</div>
</div>
</form>
</div>
</div>
<script type="module">
import validation from "./js/validation";
import { linesForm } from "./js/lines";
document.addEventListener('DOMContentLoaded', () => {
validation();
linesForm();
});
</script>
</body>
</html>

View File

@ -7,8 +7,8 @@
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="css/style.css">
<!--- https://stackoverflow.com/questions/9456289/how-to-make-a-div-visible-and-invisible-with-javascript --->
</head>
<body>
<header class="border-bottom ps-5 pe-5 sticky-top" style="background-color: #6376D7;">

232
css/style.css Normal file
View File

@ -0,0 +1,232 @@
main, body {
min-height: 100%;
}
form {
height: 100%;
}
.form-horizontal{
display:block;
height:50%;
margin:0 auto;
}
@media only screen and (max-width: 768px) {
.picmin.box {
display: none;
}
.picture-preview.box {
max-width: 100%;
width: 450px;
}
.product-menu.box{
display: none;
}
.pr-menu-btn.btn {
display: none;
}
#innerbox.xl-only, .catalog-menu.xl-only {
display: none !important;
}
.xl-only {
display: none !important;
}
}
#cart-pic.picmin.box {
display: block !important;
}
.registerbox {
max-width: 725px;
width: 100%;
background: #D1D9FF;
box-shadow: 0px 5px 8px rgba(0, 0, 0, 0.25);
border-radius: 20px;
}
.inputbox {
height: 52px;
background: white;
border-radius: 12px;
border: 0px;
font-size: 24px;
}
.btn.btn-primary {
border-radius: 12px;
border: 0px;
color: #FFFFFF;
font-size: 24px;
cursor: pointer;
filter: drop-shadow(0px 5px 5px rgba(0, 0, 0, 0.25));
}
.btn.btn-main {
border-radius: 12px;
border: 0px;
color: #FFFFFF;
font-size: 24px;
cursor: pointer;
filter: drop-shadow(0px 5px 5px rgba(0, 0, 0, 0.25));
}
.btn.btn-light {
width: 197px;
height: 62px;
border-radius: 12px;
border: 0px;
color: #000000;
font-size: 20px;
cursor: pointer;
text-align: left;
padding-left: 5%;
filter: drop-shadow(0px 5px 5px rgba(0, 0, 0, 0.25));
}
.box {
background: #D1D9FF;
box-shadow: 0px 5px 6px rgba(0, 0, 0, 0.25);
border-radius: 20px
}
.inputbox {
background: white;
border-radius: 12px;
}
#menu.box {
width: 250px;
max-height: 250px;
}
#settings-menu.box {
max-width: 250px;
height: 550px;
}
.catalog-menu.box {
width: 250px;
}
#catalog.box {
width: 1250px;
}
#innerbox.catalog.box {
background: #6376D7;
}
#item.catalog.box {
background: white;
height: 365px;
width: 215px;
}
.item-img {
height: 180px;
width: 180px;
}
#product-box.box {
max-width: 925px;
width: 100%;
}
#product-menu.box {
max-width: 250px;
width: 100%;
}
.picture-preview.box {
background-color: white;
width: 450px;
max-height: 450px;
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.25);
}
.picmin.box {
background-color: white;
width: 100px !important;
height: 100px !important;
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.25);
}
#order-box.box {
background-color: white;
max-width: 300px;
height: 450px;
box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.25);
}
#cart.box {
width: 970px;
min-height: 725px;
}
#orders.box {
width: 970px;
height: 725px;
}
#favorite.box {
width: 970px;
height: 725px;
}
#personal-info.box {
max-width: 970px;
min-height: 550px;
height: 100%;
}
.innerbox {
background: #ffffff;
border-radius: 20px
}
#cart-box.innerbox {
max-width: 550px;
height: 600px;
}
#order-cart-box.innerbox {
height: 300px;
}
.btn-main {
--bs-btn-bg: #4156C2 !important;
--bs-btn-border-color: #33449d;
--bs-btn-hover-color: #fff;
--bs-btn-hover-bg: #2c3c8a;
--bs-btn-hover-border-color: #1a2350;
--bs-btn-focus-shadow-rgb: 51, 68, 157;
--bs-btn-active-color: #fff;
--bs-btn-active-bg: #1a2350;
--bs-btn-active-border-color: #fff;
--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
--bs-btn-disabled-color: #fff;
--bs-btn-disabled-bg: #4156C2;
--bs-btn-disabled-border-color: #33449d;
}
.btn-quit {
--bs-btn-color: #fff !important;
--bs-btn-bg: #152683 !important;
--bs-btn-border-color: rgba(0, 0, 0, 0);
--bs-btn-hover-color: #fff;
--bs-btn-hover-bg: #12206f;
--bs-btn-hover-border-color: rgba(0, 0, 0, 0.2);
--bs-btn-focus-shadow-rgb: 255, 255, 255;
--bs-btn-active-color: #fff;
--bs-btn-active-bg: #111e69;
--bs-btn-active-border-color: rgba(0, 0, 0, 0.25);
--bs-btn-active-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
--bs-btn-disabled-color: #fff;
--bs-btn-disabled-bg: #152683;
--bs-btn-disabled-border-color: rgba(0, 0, 0, 0);
}

123
data.json Normal file

File diff suppressed because one or more lines are too long

View File

@ -7,7 +7,7 @@
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>

55
js/lines-modal.js Normal file
View File

@ -0,0 +1,55 @@
// Модуль для работы с модальным окном
// импорт компонента Modal из bootstrap
import { Modal } from "bootstrap";
import { cntrls, imagePlaceholder } from "./lines-ui";
// поиск модального окна на странице
const modal = document.getElementById("items-update");
// если он найден, то создается экземпляр компонента Modal
// для программного управления модальным окном
const myModal = modal ? new Modal(modal, {}) : null;
// поиск тега с заголовком модального кона для его смены
const modalTitle = document.getElementById("items-update-title");
// обнуление значений модального окна, т. к.
// используется одно окно для всех операций
function resetValues() {
cntrls.lineId.value = "";
cntrls.name.value = "";
cntrls.price.value = parseFloat(0).toFixed(2);
cntrls.count.value = 0;
cntrls.image.value = "";
cntrls.imagePreview.src = imagePlaceholder;
}
// функция для показа модального окна
// перед показом происходит заполнение формы для редактирования
// если объект item не пуст
export function showUpdateModal(item) {
modalTitle.innerHTML = item === null ? "Добавить" : "Изменить";
console.info(item);
if (item) {
cntrls.lineId.value = item.id;
cntrls.name.value = item.name;
cntrls.price.value = item.price;
cntrls.count.value = item.count;
cntrls.count.value = item.count;
cntrls.imagePreview.src = item.image ? item.image : imagePlaceholder;
} else {
resetValues();
}
myModal.show();
}
// функция для скрытия модального окна
export function hideUpdateModal() {
resetValues();
// удаление класса was-validated для скрытия результатов валидации
cntrls.form.classList.remove("was-validated");
myModal.hide();
}

80
js/lines-rest-api.js Normal file
View File

@ -0,0 +1,80 @@
// модуль для работы с REST API сервера
// адрес сервера
const serverUrl = "http://localhost:8082";
// функция возвращает объект нужной структуры для отправки на сервер
function createLineObject(name, price, count, image) {
return {
name,
price: parseFloat(price).toFixed(2),
count,
image,
};
}
// обращение к серверу для получения всех записей (get)
export async function getAllLines() {
const response = await fetch(`${serverUrl}/lines`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// обращение к серверу для создания записи (post)
// объект отправляется в теле запроса (body)
export async function createLine(name, price, count, image) {
const itemObject = createLineObject(name, price, count, image);
const options = {
method: "POST",
body: JSON.stringify(itemObject),
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
const response = await fetch(`${serverUrl}/lines`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// обращение к серверу для обновления записи по id (put)
// объект отправляется в теле запроса (body)
// id передается в качестве части пути URL get-запроса
export async function updateLine(id, name, price, count, image) {
const itemObject = createLineObject(name, price, count, image);
const options = {
method: "PUT",
body: JSON.stringify(itemObject),
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
const response = await fetch(`${serverUrl}/lines/${id}`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// обращение к серверу для удаления записи по id (delete)
// id передается в качестве части пути URL get-запроса
export async function deleteLine(id) {
const options = {
method: "DELETE",
};
const response = await fetch(`${serverUrl}/lines/${id}`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}

85
js/lines-ui.js Normal file
View File

@ -0,0 +1,85 @@
// модуль для работы с элементами управления
// объект для удобного получения элементов
// при обращении к атрибуту объекта вызывается
// нужная функция для поиска элемента
export const cntrls = {
button: document.getElementById("items-add"),
table: document.querySelector("#items-table tbody"),
form: document.getElementById("items-form"),
lineId: document.getElementById("items-line-id"),
name: document.getElementById("name"),
price: document.getElementById("price"),
count: document.getElementById("count"),
image: document.getElementById("image"),
imagePreview: document.getElementById("image-preview"),
};
export const imagePlaceholder = "https://via.placeholder.com/200";
// функция создает ссылку (a) для таблицы
// содержимое тега a заполняется необходимой иконкой (icon)
// при нажатии вызывается callback
// ссылка "оборачивается" тегом td
// <td><a href="#" onclick="callback()"><i class="fa-solid icon"></i></a></td>
function createTableAnchor(icon, callback) {
const i = document.createElement("i");
i.classList.add("fa-solid", icon);
const a = document.createElement("a");
a.href = "#";
a.appendChild(i);
a.onclick = (event) => {
// чтобы в URL не добавлялась решетка
event.preventDefault();
event.stopPropagation();
callback();
};
const td = document.createElement("td");
td.appendChild(a);
return td;
}
function createTableColumn(value) {
const td = document.createElement("td");
td.textContent = value;
return td;
}
function createImgColumn(value) {
const td = document.createElement("td");
td.appendChild(value);
return td;
}
export function createTableRow(item, index, editCallback, deleteCallback) {
const rowNumber = document.createElement("th");
rowNumber.scope = "row";
rowNumber.textContent = index + 1;
const row = document.createElement("tr");
row.id = `line-${item.id}`;
const img = document.createElement("img");
if (item.image === undefined) {
img.src = imagePlaceholder;
}
else {
img.src = item.image;
}
img.style.width = "70px";
img.style.height = "70px";
row.appendChild(rowNumber);
row.appendChild(createTableColumn(item.name));
row.appendChild(createTableColumn(parseFloat(item.price).toFixed(2)));
row.appendChild(createTableColumn(item.count));
row.appendChild(createImgColumn(img));
// редактировать в модальном окне
row.appendChild(createTableAnchor("fa-pencil", editCallback));
// удаление
row.appendChild(createTableAnchor("fa-trash", deleteCallback));
return row;
}

183
js/lines.js Normal file
View File

@ -0,0 +1,183 @@
// модуль с логикой
import { hideUpdateModal, showUpdateModal } from "./lines-modal";
import {
createLine, deleteLine, getAllLines, updateLine,
} from "./lines-rest-api";
import {
cntrls, createTableRow, imagePlaceholder,
} from "./lines-ui";
async function drawLinesTable() {
console.info("Try to load data");
console.log(cntrls);
if (!cntrls.table) {
console.info("No table!");
return;
}
// вызов метода REST API для получения всех записей
const data = await getAllLines();
cntrls.table.innerHTML = "";
// цикл по результату ответа от сервера
// используется лямбда-выражение
// (item, index) => {} аналогично function(item, index) {}
data.forEach((item, index) => {
cntrls.table.appendChild(
createTableRow(
item,
index,
() => showUpdateModal(item),
() => removeLine(item.id),
),
);
});
}
async function addLine(name, price, count, image) {
console.info("Try to add item");
// вызов метода REST API для добавления записи
const data = await createLine(name, price, count, image);
console.info("Added");
console.info(data);
// загрузка и заполнение table
drawLinesTable();
}
async function editLine(id, name, price, count, image) {
console.info("Try to update item");
// вызов метода REST API для обновления записи
const data = await updateLine(id, name, price, count, image);
console.info("Updated");
console.info(data);
// загрузка и заполнение table
drawLinesTable();
}
async function removeLine(id) {
if (!confirm("Вы уверены, что вы хотите удалить объект?")) {
console.info("Canceled");
return;
}
console.info("Try to remove item");
// вызов метода REST API для удаления записи
const data = await deleteLine(id);
console.info(data);
// загрузка и заполнение table
drawLinesTable();
}
// Функция для обработки создания и редактирования элементов таблицы через модальное окно
// Если хотите делать через страницу, то удалите эту функцию
// eslint-disable-next-line import/prefer-default-export
export function linesForm() {
console.info("linesForm");
// загрузка и заполнение table
drawLinesTable();
// обработчик события нажатия на кнопку для показа модального окна
cntrls.button.addEventListener("click", () => showUpdateModal(null));
cntrls.image.addEventListener("change", () => updateImagePreview());
// обработчик события отправки формы
// возникает при нажатии на кнопку (button) с типом submit
// кнопка должна находится внутри тега form
cntrls.form.addEventListener("submit", async (event) => {
console.info("Form onSubmit");
// отключение стандартного поведения формы при отправке
// при отправке страница обновляется и JS перестает работать
event.preventDefault();
event.stopPropagation();
// если форма не прошла валидацию, то ничего делать не нужно
if (!cntrls.form.checkValidity()) {
return;
}
let imageBase64 = "";
// Получение выбранного пользователем изображения в виде base64 строки
// Если пользователь ничего не выбрал, то не нужно сохранять в БД
// дефолтное изображение
if (cntrls.imagePreview.src !== imagePlaceholder) {
// Загрузка содержимого атрибута src тэга img с id image-preview
// Здесь выполняется HTTP запрос с типом GET
const result = await fetch(cntrls.imagePreview.src);
// Получение из HTTP-ответа бинарного содержимого
const blob = await result.blob();
// Получение base64 строки для файла
// Здесь выполняется Promise из функции readFile
// Promise позволяет писать линейный код для работы с асинхронными методами
// без использования обработчиков (callback) с помощью await
imageBase64 = await readFile(blob);
}
// получение id строки для редактирования
// это значение содержится в скрытом input
const currentId = cntrls.lineId.value;
// если значение id не задано,
// то необходимо выполнить добавление записи
// иначе обновление записи
if (!currentId) {
await addLine(
cntrls.name.value,
cntrls.price.value,
cntrls.count.value,
imageBase64,
);
} else {
await editLine(
currentId,
cntrls.name.value,
cntrls.price.value,
cntrls.count.value,
imageBase64,
);
}
// после выполнения добавления/обновления модальное окно скрывается
hideUpdateModal();
});
}
// функция для получения содержимого файла в виде base64 строки
// https://ru.wikipedia.org/wiki/Base64
async function readFile(file) {
const reader = new FileReader();
// создание Promise-объекта для использования функции
// с помощью await (асинхронно) без коллбэков (callback)
// https://learn.javascript.ru/promise
return new Promise((resolve, reject) => {
// 2. "Возвращаем" содержимое когда файл прочитан
// через вызов resolve
// Если не использовать Promise, то всю работу по взаимодействию
// с REST API пришлось бы делать в обработчике (callback) функции
// onloadend
reader.onloadend = () => {
const fileContent = reader.result;
// Здесь могла бы быть работа с REST API
// Чтение заканчивает выполняться здесь
resolve(fileContent);
};
// 3. Возвращаем ошибку
reader.onerror = () => {
// Или здесь в случае ошибки
reject(new Error("oops, something went wrong with the file reader."));
};
// Шаг 1. Сначала читаем файл
// Чтение начинает выполняться здесь
reader.readAsDataURL(file);
});
}
// функция для обновления блока с превью выбранного изображения
async function updateImagePreview() {
// получение выбранного файла
// возможен выбор нескольких файлов, поэтому необходимо получить только первый
const file = cntrls.image.files[0];
// чтение содержимого файла в виде base64 строки
const fileContent = await readFile(file);
console.info("base64 ", fileContent);
// обновление атрибута src для тега img с id image-preview
cntrls.imagePreview.src = fileContent;
}

25
js/validation.js Normal file
View File

@ -0,0 +1,25 @@
// модуль используется для валидации форма на странице
function validation() {
// поиск всех форма с классом .needs-validation
const forms = document.querySelectorAll("form.needs-validation");
for (let i = 0; i < forms.length; i += 1) {
const form = forms[i];
// для каждой формы добавляется обработчик события отправки
form.addEventListener("submit", (event) => {
// если форма не прошла валидацию
// то выключить стандартное действие
if (!form.checkValidity()) {
event.preventDefault();
// предотвращает распространение preventDefault
// на другие объекты
event.stopPropagation();
}
// добавляет к форме класс was-validated
form.classList.add("was-validated");
});
}
}
export default validation;

14
jsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Node",
"target": "ES2020",
"jsx": "preserve",
"strictNullChecks": true,
"strictFunctionTypes": true
},
"exclude": [
"node_modules",
"**/node_modules/*"
]
}

View File

@ -8,7 +8,7 @@
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>

2439
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,9 +4,12 @@
"description": "",
"main": "login.html",
"scripts": {
"start": "vite",
"vite": "vite",
"serve": "http-server -p 3000 ./",
"test": "echo \"Error: no test specified\" && exit 1"
"build": "vite build",
"rest": "json-server --watch data.json -p 8082",
"dev": "npm-run-all --parallel rest vite",
"prod": "npm-run-all build --parallel serve rest"
},
"dependencies": {
"@fortawesome/fontawesome-free": "6.4.2",
@ -15,8 +18,12 @@
},
"devDependencies": {
"http-server": "14.1.1",
"json-server": "0.17.4",
"npm-run-all": "4.1.5",
"eslint": "8.50.0",
"eslint-config-airbnb-base": "15.0.0",
"eslint-plugin-import": "2.28.1",
"sass": "1.69.5",
"vite": "4.4.9"
}
}
}

View File

@ -7,8 +7,8 @@
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="css/style.css">
<!--- https://stackoverflow.com/questions/9456289/how-to-make-a-div-visible-and-invisible-with-javascript --->
</head>
<body>
<header class="border-bottom ps-5 pe-5 sticky-top" style="background-color: #6376D7;">

View File

@ -7,8 +7,8 @@
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="css/style.css">
<!--- https://stackoverflow.com/questions/9456289/how-to-make-a-div-visible-and-invisible-with-javascript --->
</head>
<body>
<header class="border-bottom ps-5 pe-5 sticky-top" style="background-color: #6376D7;">
@ -59,12 +59,12 @@
</div>
<div id="order-cart-box" class="innerbox ms-4 me-4 mb-3 d-flex flex-column">
<div id="total-sum" class="d-flex flex-row mt-4">
<p class="ms-4 me-auto"style="font-size: 22; text-align: left;">Итого</p>
<p class="ms-auto me-4" style="font-size: 22; text-align: right;">120 290 ₽</p>
<p class="ms-4 me-auto" style="font-size: 22; text-align: left">Итого</p>
<p class="ms-auto me-4" style="font-size: 22; text-align: right">120 290 ₽</p>
</div>
<div id="total-itemsincart" class="d-flex flex-row mb-3">
<p class="ms-4 me-auto"style="font-size: 16; color: #7e7e7e; text-align: left;">Товаров</p>
<p class="ms-auto me-4" style="font-size: 16; color: #7e7e7e; text-align: right;">2 шт.</p>
<p class="ms-4 me-auto" style="font-size: 16; color: #7e7e7e; text-align: left">Товаров</p>
<p class="ms-auto me-4" style="font-size: 16; color: #7e7e7e; text-align: right">2 шт.</p>
</div>
<button type="button" class="btn btn-main mt-auto me-5 ms-5 mb-3" style="min-height: 55px">Оформить заказ</button>
</div>

View File

@ -7,7 +7,7 @@
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>

View File

@ -7,7 +7,8 @@
<script type="module" src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="./node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="css/style.css">
<!--- https://stackoverflow.com/questions/9456289/how-to-make-a-div-visible-and-invisible-with-javascript --->
</head>
<body>
<header class="border-bottom ps-5 pe-5 sticky-top" style="background-color: #6376D7;">

22
vite.config.js Normal file
View File

@ -0,0 +1,22 @@
import { resolve } from "path";
// eslint-disable-next-line import/no-extraneous-dependencies
import { defineConfig } from "vite";
export default defineConfig({
build: {
sourcemap: true,
emptyOutDir: true,
rollupOptions: {
input: {
main: resolve(__dirname, "index.html"),
login: resolve(__dirname, "login.html"),
register: resolve(__dirname, "register.html"),
profile: resolve(__dirname, "profile.html"),
catalog: resolve(__dirname, "catalog.html"),
admin: resolve(__dirname, "admin.html"),
product: resolve(__dirname, "product.html"),
settings: resolve(__dirname, "settings.html"),
},
},
},
});