-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
238 lines (195 loc) · 8.68 KB
/
script.js
File metadata and controls
238 lines (195 loc) · 8.68 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
const createUserForm = document.querySelector("[data-create-user-form]");
const editUserFormDialog = document.querySelector("[data-edit-user-form-dialog]");
const usersContainer = document.querySelector("[data-users-container]");
const MOCK_API_URL = "https://675c54bafe09df667f63812c.mockapi.io/users";
let users = [];
// ------- Клик по всему контейнеру (делегирование событий) -------
usersContainer.addEventListener("click", (e) => {
if (e.target.hasAttribute("data-user-remove-btn")) {
// console.log("userRemoveBtn" in e.target.dataset)
const isRemoveUser = confirm("Вы точно хотите удалить этого красавчика?");
isRemoveUser && removeExistingUserAsync(e.target.dataset.userId);
return;
}
if (e.target.hasAttribute("data-user-edit-btn")) {
populateDialog(e.target.dataset.userId);
editUserFormDialog.showModal();
}
})
// ------- Событие отравки формы создания пользователя -------
createUserForm.addEventListener("submit", (e) => {
e.preventDefault();
const formData = new FormData(createUserForm);
const formUserData = Object.fromEntries(formData);
const newUserData = {
name: formUserData.userName,
city: formUserData.userCity,
email: formUserData.userEmail,
avatar: formUserData.userImageUrl,
}
createNewUserAsync(newUserData);
})
// ------- Редактирование существующего пользователя -------
const editExistingUserAsync = async (newUserData) => {
try {
const response = await fetch(`${MOCK_API_URL}/${newUserData.id}`, {
method: "PUT",
body: JSON.stringify(newUserData),
headers: {
"Content-type": "application/json"
}
});
if (response.status === 400) {
throw new Error(`клиентская ошибка`)
}
const editedUser = await response.json();
users = users.map((user) => {
if (user.id === editedUser.id) {
return editedUser;
}
return user;
})
editUserFormDialog.close();
renderUsers();
alert("ПОЛЬЗОВАТЕЛЬ УСПЕШНО ОТРЕДАКТИРОВАН")
} catch (error) {
console.error("ОШИБКА при редактировании пользователя пользователя: ", error.message)
}
}
// ------- Удаление существующего пользователя -------
const removeExistingUserAsync = async (userId) => {
try {
const response = await fetch(`${MOCK_API_URL}/${userId}`, {
method: "DELETE"
});
if (response.status === 404) {
throw new Error(`${userId} не найден`)
}
const removedUser = await response.json();
users = users.filter(user => user.id !== removedUser.id);
renderUsers();
alert("ПОЛЬЗОВАТЕЛЬ УСПЕШНО УДАЛЕН");
} catch (error) {
console.error("ОШИБКА при удалении пользователя: ", error.message)
}
}
// ------- Создание нового пользователя -------
const createNewUserAsync = async (newUserData) => {
try {
const response = await fetch(MOCK_API_URL, {
method: "POST",
body: JSON.stringify(newUserData),
headers: {
"Content-type": "application/json"
}
});
const newCreatedUser = await response.json();
users.unshift(newCreatedUser);
renderUsers();
createUserForm.reset();
alert("НОВЫЙ ПОЛЬЗОВАТЕЛЬ УСПЕШНО СОЗДАН")
} catch (error) {
console.error("ОШИБКА создания нового пользователя: ", error.message)
}
}
// ------- Получение всех пользователей -------
const getUsersAsync = async () => {
try {
const response = await fetch(MOCK_API_URL);
users = await response.json();
renderUsers();
} catch (error) {
console.error("ПОЙМАННАЯ ОШИБКА: ", error.message)
}
}
// ------- Отрисовка пользователей -------
const renderUsers = () => {
usersContainer.innerHTML = "";
users.forEach((user) => {
usersContainer.insertAdjacentHTML("beforeend", `
<div class="user-card">
<h3>${user.name}</h3>
<p>City: ${user.city}</p>
<span>Email: ${user.email}</span>
<img src="${user.avatar}"/>
<button class="user-edit-btn" data-user-id="${user.id}" data-user-edit-btn>🛠️</button>
<button class="user-remove-btn" data-user-id="${user.id}" data-user-remove-btn>❌</button>
</div>
`)
})
}
// ------- Заполнение модального окна разметкой формы -------
const populateDialog = (userId) => {
editUserFormDialog.innerHTML = "";
const editForm = document.createElement("form");
const closeFormBtn = document.createElement("button");
closeFormBtn.classList.add("close-edit-form-btn");
closeFormBtn.textContent = "❌";
closeFormBtn.addEventListener("click", () => editUserFormDialog.close());
editForm.addEventListener("submit", (e) => {
e.preventDefault();
const formData = new FormData(editForm);
const formUserData = Object.fromEntries(formData);
const newUserData = {
id: formUserData.userId,
name: formUserData.userName,
city: formUserData.userCity,
email: formUserData.userEmail,
avatar: formUserData.userImageUrl,
}
editExistingUserAsync(newUserData);
})
editForm.classList.add("form");
editForm.innerHTML = `
<input type="text" name="userId" value="${userId}" hidden/>
<div class="control-field">
<label for="nameId" class="form-label">Name</label>
<input type="text" class="form-control" id="nameId" name="userName" required minlength="2"
maxlength="23">
</div>
<div class="control-field">
<label for="cityId" class="form-label">City</label>
<input type="text" class="form-control" id="cityId" name="userCity" required minlength="2"
maxlength="20">
</div>
<div class="control-field">
<label for="emailId" class="form-label">Email</label>
<input type="email" class="form-control form-control--email" id="cityemailIdId" name="userEmail"
required>
</div>
<div class="control-field">
<label for="imagesUrlId" class="form-label">Images</label>
<select name="userImageUrl" id="imagesUrlId" class="form-control form-control--images" required>
<option value="">Image URL</option>
<hr>
<option
value="https://avatars.mds.yandex.net/i?id=88cc30ba21222ee61db2d32974a5b380259ee41f-3380069-images-thumbs&n=13">
Cat 1</option>
<option
value="https://avatars.mds.yandex.net/i?id=6444bd82bce43803b8ad0601c12a80e7-5230955-images-thumbs&n=13">
Cat 2</option>
<option
value="https://avatars.mds.yandex.net/i?id=60f5028735fd33706fd8e50bb1d7f636062b21a4-8210619-images-thumbs&n=13">
Cat 3</option>
<option
value="https://avatars.mds.yandex.net/i?id=ae0521f7a56e37beaa15c3469ab4c338e350c501-4453150-images-thumbs&n=13">
Dog 1</option>
<option
value="https://avatars.mds.yandex.net/i?id=fec854b859968252cfa2ac789041838662475e7e-4667938-images-thumbs&n=13">
Dog 2</option>
<option
value="https://avatars.mds.yandex.net/i?id=26253ff7e734e6fd0431b2fbc2b4a1a669ed2685be8a39d1-9148232-images-thumbs&n=13">
Dog 3</option>
<option
value="https://avatars.mds.yandex.net/i?id=eaed52ea5bd298c60ff850710e5d05ddd9d26b49-8082760-images-thumbs&n=13">
Wolf 1</option>
<option
value="https://avatars.mds.yandex.net/i?id=730e0bcc75f17fff296adf3dcdaae2036067665ec12d546e-12645552-images-thumbs&n=13">
Fox 1</option>
</select>
</div>
<button type="submit" class="btn submit-btn">Edit User</button>
`
editUserFormDialog.append(editForm, closeFormBtn);
}
getUsersAsync();