sldshr commited on
Commit
f62fb35
·
verified ·
1 Parent(s): 2768e84

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +965 -404
index.html CHANGED
@@ -5,48 +5,119 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <title>WebClient 2010 - SQL Edition</title>
7
  <style>
 
8
  :root {
9
- --bg-color: #f4f7f9;
10
- --panel-bg: #ffffff;
 
 
11
  --text-dark: #1e395b;
12
- --menubar-top: #4a88c7;
 
13
  --menubar-bot: #3371b6;
14
- --border-color: #8ba0bc;
15
- --hover-bg: #e4eff8;
 
 
 
16
  }
17
 
18
  body {
19
- font-family: Tahoma, "Trebuchet MS", sans-serif;
20
- background-color: var(--bg-color);
21
  margin: 0;
22
  padding: 0;
23
- display: flex;
24
- justify-content: center;
25
- align-items: center;
26
- height: 100vh;
27
- color: var(--text-dark);
28
  font-size: 13px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  }
30
 
31
  .window {
32
- background: var(--panel-bg);
 
 
33
  border: 1px solid var(--border-color);
34
- box-shadow: 2px 2px 5px rgba(0,0,0,0.2);
35
  border-radius: 4px;
 
 
 
 
36
  overflow: hidden;
 
 
 
37
  display: flex;
38
- flex-direction: column;
39
  }
40
 
41
  .window-header {
42
- background: linear-gradient(to bottom, var(--menubar-top), var(--menubar-bot));
43
- color: white;
44
- padding: 5px 10px;
45
  font-weight: bold;
46
- font-size: 12px;
 
 
47
  display: flex;
48
  justify-content: space-between;
49
  align-items: center;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  }
51
 
52
  .window-body {
@@ -54,92 +125,121 @@
54
  display: flex;
55
  flex-direction: column;
56
  gap: 10px;
 
57
  }
58
 
59
- input[type="text"], input[type="password"] {
60
- border: 1px solid #7f9db9;
61
- padding: 4px;
62
- font-family: Tahoma, sans-serif;
63
- font-size: 12px;
64
  }
65
 
66
- .btn {
67
- background: linear-gradient(to bottom, #f2f5f6, #cddae3);
68
- border: 1px solid #7a96df;
69
- padding: 4px 15px;
 
70
  font-family: Tahoma, sans-serif;
71
- font-size: 12px;
72
- cursor: pointer;
73
- border-radius: 3px;
74
- color: #1e395b;
75
  }
76
- .btn:hover { background: linear-gradient(to bottom, #ffffff, #e4eff8); }
77
- .btn:active { background: #cddae3; }
78
-
79
- .hidden { display: none !important; }
80
 
81
- /* App Layout */
82
- #app-layout {
83
- width: 900px;
84
- height: 600px;
85
  display: flex;
86
- flex-direction: row;
 
 
87
  }
88
 
89
  .panel {
90
- border-right: 1px solid var(--border-color);
 
 
 
91
  display: flex;
92
  flex-direction: column;
93
- background: #fff;
94
  }
95
- .panel:last-child { border-right: none; }
96
-
97
  .panel-header {
98
- background: #d8e1e7;
99
- padding: 5px;
100
- font-weight: bold;
101
  border-bottom: 1px solid var(--border-color);
102
- text-align: center;
 
103
  font-size: 11px;
 
104
  }
105
 
106
- .sidebar { width: 200px; }
107
- .chat-area { flex-grow: 1; }
108
-
109
- .list-container { flex-grow: 1; overflow-y: auto; }
110
- .list-item {
111
- padding: 5px 10px;
112
- cursor: pointer;
113
- border-bottom: 1px solid #f0f0f0;
114
  }
115
- .list-item:hover { background-color: var(--hover-bg); }
116
- .list-item.active {
117
- background-color: var(--menubar-bot);
118
- color: white;
 
119
  }
120
 
121
  .chat-messages {
122
- flex-grow: 1;
123
- overflow-y: auto;
124
  padding: 10px;
125
- background: #fff;
 
126
  display: flex;
127
  flex-direction: column;
128
- gap: 4px;
129
  }
130
 
131
- .msg {
132
- font-family: Verdana, sans-serif;
133
- font-size: 12px;
134
- border-radius: 3px;
135
- position: relative;
 
 
 
 
 
 
 
 
136
  padding: 4px 8px;
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  }
138
- .msg:hover { background-color: rgba(0,0,0,0.03); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  .msg .time { color: #888; font-size: 10px; margin-right: 5px; }
140
  .msg .author { font-weight: bold; color: #1e5799; margin-right: 5px; }
141
  .msg.system .author { color: #cc3333; }
142
- .msg.pinged { background-color: #fffde7; border-left: 3px solid #fbc02d; }
143
 
144
  .msg .content {
145
  word-wrap: break-word;
@@ -147,37 +247,9 @@
147
  white-space: pre-wrap;
148
  display: inline-block;
149
  max-width: 100%;
 
150
  }
151
 
152
- .msg-actions {
153
- display: none;
154
- position: absolute;
155
- right: 10px;
156
- top: 50%;
157
- transform: translateY(-50%);
158
- background: rgba(255, 255, 255, 0.95);
159
- border: 1px solid var(--border-color);
160
- border-radius: 4px;
161
- padding: 2px;
162
- box-shadow: 0 1px 3px rgba(0,0,0,0.15);
163
- z-index: 10;
164
- }
165
-
166
- .msg:hover .msg-actions {
167
- display: flex;
168
- gap: 2px;
169
- }
170
-
171
- .msg-actions button {
172
- background: transparent;
173
- border: none;
174
- cursor: pointer;
175
- padding: 4px 6px;
176
- border-radius: 3px;
177
- font-size: 14px;
178
- }
179
- .msg-actions button:hover { background: var(--hover-bg); }
180
-
181
  .quote-block {
182
  border-left: 3px solid var(--menubar-bot);
183
  background: #f0f4f8;
@@ -186,7 +258,9 @@
186
  border-radius: 0 3px 3px 0;
187
  font-size: 11px;
188
  color: #555;
 
189
  }
 
190
  .quote-block .q-author { font-weight: bold; color: var(--menubar-bot); }
191
  .quote-block .q-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }
192
 
@@ -202,104 +276,460 @@
202
  color: var(--text-dark);
203
  }
204
 
205
- .chat-input-area {
 
 
 
 
 
 
206
  border-top: 1px solid var(--border-color);
207
- padding: 10px;
208
- background: #f4f7f9;
209
- display: flex;
210
- gap: 10px;
 
 
 
 
 
 
 
211
  }
212
 
213
- #msg-input { flex-grow: 1; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
- .poll-box {
216
- background: #f0f4f8; border: 1px solid #d8e1e7; padding: 10px;
217
- margin-top: 5px; border-radius: 4px; display: inline-block; min-width: 200px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  }
219
- .poll-q { font-weight: bold; color: #1e395b; margin-bottom: 8px; }
220
- .poll-opt { display: flex; align-items: center; justify-content: space-between; margin-bottom: 5px; cursor: pointer; padding: 3px; border-radius: 3px; }
221
- .poll-opt:hover { background: #e4eff8; }
222
- .poll-bar-bg { height: 6px; background: #ddd; border-radius: 3px; flex-grow: 1; margin: 0 10px; overflow: hidden;}
223
- .poll-bar-fg { height: 100%; background: var(--menubar-bot); width: 0%; transition: width 0.3s; }
224
  </style>
225
  </head>
226
  <body>
227
 
228
- <!-- Окно авторизации -->
229
- <div id="login-window" class="window" style="width: 320px;">
230
- <div class="window-header">WebClient :: Вход</div>
231
- <div class="window-body">
232
- <div style="font-size: 11px; color: #666;">Настройки сервера (Supabase):</div>
233
- <input type="text" id="db-url" placeholder="URL проекта (https://...)">
234
- <input type="text" id="db-key" placeholder="Anon Key">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
- <div style="font-size: 11px; color: #666; margin-top: 10px;">Учетная запись:</div>
237
- <input type="text" id="db-user" placeholder="Имя пользователя">
238
- <input type="password" id="db-pass" placeholder="Пароль" onkeydown="if(event.key==='Enter') login()">
 
 
239
 
240
- <label style="font-size: 11px; display: flex; align-items: center; gap: 5px; cursor: pointer;">
241
- <input type="checkbox" id="save-profile" checked> Сохранить профиль
242
- </label>
 
 
243
 
244
- <button class="btn" onclick="login()" style="margin-top: 10px; font-weight: bold;">Подключиться</button>
245
- <div id="auth-error" style="color: #cc3333; font-size: 11px; text-align: center;"></div>
246
-
247
- <div id="profiles-list" style="margin-top: 10px; display:flex; flex-direction: column; gap: 5px;"></div>
 
 
 
 
248
  </div>
249
  </div>
250
 
251
- <!-- Основное окно приложения -->
252
- <div id="app-window" class="window hidden" style="width: 800px; height: 500px;">
 
 
 
 
 
253
  <div class="window-header">
254
- <span>WebClient - <span id="current-username"></span></span>
255
- <button class="btn" style="padding: 2px 8px;" onclick="logout()">Выход</button>
256
  </div>
257
 
258
- <div id="app-layout">
259
- <!-- Левая колонка: Каналы -->
260
- <div class="panel sidebar">
261
- <div class="panel-header">КАНАЛЫ</div>
262
- <div class="list-container" id="channels-list"></div>
 
 
 
 
 
 
263
  </div>
 
 
 
264
 
265
- <!-- Центральная колонка: Чат -->
266
- <div class="panel chat-area" id="panel-chat">
267
- <div class="panel-header" id="chat-title">Чат</div>
268
- <div class="chat-messages" id="messages-list">
269
- <div style="color: #999; text-align: center; margin-top: 20px;">Ожидание подключения к серверу...</div>
270
- </div>
271
-
272
- <div id="action-banner" class="action-banner hidden">
273
- <span id="action-banner-text">Действие...</span>
274
- <button class="btn" style="padding: 1px 5px; background: #cc3333; color: white; border:none;" onclick="cancelAction()">X</button>
275
- </div>
276
-
277
- <div class="chat-input-area">
278
- <input type="text" id="msg-input" placeholder="Сообщение или команда (например, !опрос Вопрос Ответ1 Ответ2)" onkeydown="handleEnter(event)">
279
- <button class="btn" onclick="sendMessage()">Отправить</button>
280
- </div>
281
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
- <!-- Правая колонка: Пользователи -->
284
- <div class="panel sidebar">
285
- <div class="panel-header">ПОЛЬЗОВАТЕЛИ</div>
286
- <div class="list-container" id="users-list"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  </div>
288
  </div>
289
  </div>
290
 
291
  <script>
292
- // --- 1. Утилиты ---
293
- function escapeHTML(str) {
294
- return str.replace(/[&<>'"]/g,
295
- tag => ({
296
- '&': '&amp;',
297
- '<': '&lt;',
298
- '>': '&gt;',
299
- "'": '&#39;',
300
- '"': '&quot;'
301
- }[tag])
302
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  }
304
 
305
  // --- 2. Состояние приложения и REST API ---
@@ -319,190 +749,306 @@
319
  };
320
 
321
  async function api(table, method = 'GET', body = null, query = '') {
 
 
322
  const endpoint = `${state.url}/rest/v1/${table}${query ? '?' + query : ''}`;
323
  const headers = {
324
  'apikey': state.key,
325
  'Authorization': `Bearer ${state.key}`,
326
- 'Content-Type': 'application/json'
 
327
  };
328
-
329
- if (method === 'POST' || method === 'PATCH') {
330
- headers['Prefer'] = 'return=representation';
331
- }
332
 
333
- const options = { method, headers };
334
- if (body) options.body = JSON.stringify(body);
335
 
336
- const res = await fetch(endpoint, options);
337
- if (!res.ok) {
338
- const errText = await res.text();
339
- throw new Error(`HTTP ${res.status}: ${errText}`);
 
 
 
 
 
 
 
340
  }
341
- // DELETE usually returns 204 No Content
342
- if (res.status === 204) return null;
343
- return await res.json();
344
  }
345
 
346
- // --- 3. Авторизация и Профили ---
347
- function loadProfiles() {
348
- const profiles = JSON.parse(localStorage.getItem('webclient_profiles') || '[]');
349
- const container = document.getElementById('profiles-list');
350
- container.innerHTML = '';
351
-
352
- profiles.forEach(p => {
353
- const btn = document.createElement('button');
354
- btn.className = 'btn';
355
- btn.style.textAlign = 'left';
356
- const cleanUrl = p.url.replace('https://', '').replace('.supabase.co', '');
357
- btn.innerText = `👤 ${p.username} @ ${cleanUrl}`;
358
- btn.onclick = () => {
359
- document.getElementById('db-url').value = p.url;
360
- document.getElementById('db-key').value = p.key;
361
- document.getElementById('db-user').value = p.username;
362
- document.getElementById('db-pass').value = p.password;
363
- };
364
- container.appendChild(btn);
365
- });
366
  }
367
 
368
- function saveProfile(url, key, username, password) {
369
- if (!document.getElementById('save-profile').checked) return;
370
- let profiles = JSON.parse(localStorage.getItem('webclient_profiles') || '[]');
 
 
 
 
 
 
 
 
 
 
371
 
372
- const existing = profiles.find(p => p.url === url && p.username === username);
373
- if (existing) {
374
- existing.key = key;
375
- existing.password = password;
376
- } else {
377
- profiles.push({ url, key, username, password });
 
 
 
 
 
 
 
 
 
 
 
 
378
  }
379
-
380
- localStorage.setItem('webclient_profiles', JSON.stringify(profiles));
381
- loadProfiles();
382
  }
383
 
384
  async function login() {
385
- const errDiv = document.getElementById('auth-error');
386
- errDiv.innerText = 'Подключение...';
387
-
388
- let url = document.getElementById('db-url').value.trim();
389
- if (url.endsWith('/')) url = url.slice(0, -1);
390
-
391
- state.url = url;
392
- state.key = document.getElementById('db-key').value.trim();
393
- const u = document.getElementById('db-user').value.trim();
394
- const p = document.getElementById('db-pass').value.trim();
395
 
396
- if (!state.url || !state.key || !u || !p) {
397
- errDiv.innerText = 'Заполните все поля';
398
- return;
399
- }
400
 
401
  try {
402
  const users = await api('users', 'GET', null, `username=eq.${encodeURIComponent(u)}&password=eq.${encodeURIComponent(p)}`);
403
-
404
- if (users.length > 0) {
405
  state.user = users[0];
406
- if (state.user.role === 'banned') throw new Error("Ваш аккаунт заблокирован.");
407
- finishLogin(u, p);
408
- } else {
409
- // Пытаемся зарегистрировать
410
- try {
411
- const newUsers = await api('users', 'POST', { username: u, password: p, role: 'user' });
412
- state.user = newUsers[0];
413
- finishLogin(u, p);
414
- } catch (regErr) {
415
- throw new Error("Неверный логин/пароль или имя занято.");
416
  }
 
 
 
417
  }
418
- } catch (e) {
419
- errDiv.innerText = e.message;
420
  }
421
  }
422
 
423
- function finishLogin(u, p) {
424
- saveProfile(state.url, state.key, u, p);
425
- document.getElementById('login-window').classList.add('hidden');
426
- document.getElementById('app-window').classList.remove('hidden');
427
- document.getElementById('current-username').innerText = u;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
 
429
- startApp();
 
430
  }
431
 
432
- function logout() {
433
- if (state.polling) clearInterval(state.polling);
434
  state.user = null;
435
  state.activeChannel = null;
436
- document.getElementById('app-window').classList.add('hidden');
437
- document.getElementById('login-window').classList.remove('hidden');
438
- }
439
-
440
- // --- 4. Основная логика приложения ---
441
- async function startApp() {
442
- await fetchUsers();
443
- await fetchChannels();
444
- state.polling = setInterval(() => {
445
- fetchMessages();
446
- fetchUsers(); // Обновляем список пользователей периодически
447
- }, 3000);
 
 
 
448
  }
449
-
450
- async function fetchUsers() {
451
  try {
452
  const users = await api('users', 'GET', null, 'select=id,username,role');
453
- const ul = document.getElementById('users-list');
454
- ul.innerHTML = '';
455
- state.usersCache = {};
456
-
457
- users.forEach(u => {
458
- state.usersCache[u.id] = u;
459
- const div = document.createElement('div');
460
- div.className = 'list-item';
461
- div.innerHTML = (u.role === 'admin' ? '@ ' : '') + escapeHTML(u.username);
462
- if(u.role === 'banned') div.style.textDecoration = 'line-through';
463
- ul.appendChild(div);
464
- });
465
- } catch (e) {}
466
  }
467
 
468
- async function fetchChannels() {
 
 
469
  try {
470
- state.channels = await api('channels', 'GET', null, 'order=id.asc');
471
- renderChannels();
472
- if (state.channels.length > 0) {
473
- selectChannel(state.channels[0].id, state.channels[0].name);
 
 
 
474
  }
475
- } catch(e) { alert("Ошибка загрузки каналов: " + e.message); }
476
  }
477
 
478
  function renderChannels() {
479
  const cl = document.getElementById('channels-list');
480
  cl.innerHTML = '';
481
- state.channels.forEach(c => {
 
 
 
 
 
 
 
 
482
  const div = document.createElement('div');
483
- div.className = `list-item ${c.id === state.activeChannel ? 'active' : ''}`;
484
- div.innerText = '# ' + c.name;
485
- div.onclick = () => selectChannel(c.id, c.name);
486
- cl.appendChild(div);
487
- });
 
 
 
 
 
 
 
 
 
 
 
 
488
  }
489
 
490
- function selectChannel(id, name) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
  state.activeChannel = id;
492
- document.getElementById('chat-title').innerText = 'Чат :: #' + name;
493
  state.lastMsgId = 0;
494
- document.getElementById('messages-list').innerHTML = '';
 
 
 
495
  renderChannels();
496
- cancelAction();
497
- fetchMessages();
498
  }
499
 
500
- function startReply(id) {
501
- const el = document.getElementById('msg-' + id);
502
- if (!el) return;
503
- const rawContent = el.dataset.raw;
504
- const username = el.dataset.username;
505
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506
  cancelAction();
507
  state.replyingToName = username;
508
  let cleanText = rawContent.replace(/\[R:.*?\](.*?)\[\/R\]/g, "").trim();
@@ -513,17 +1059,14 @@
513
  document.getElementById('msg-input').focus();
514
  }
515
 
516
- function startEdit(id) {
517
- const el = document.getElementById('msg-' + id);
518
- if (!el) return;
519
-
520
  cancelAction();
521
  state.editingId = id;
522
  document.getElementById('action-banner-text').innerText = `Редактирование сообщения`;
523
  document.getElementById('action-banner').classList.remove('hidden');
524
 
525
  const input = document.getElementById('msg-input');
526
- input.value = el.dataset.raw;
527
  input.focus();
528
  }
529
 
@@ -539,7 +1082,7 @@
539
  if(confirm("Удалить это сообщение?")) {
540
  try {
541
  await api('messages', 'DELETE', null, `id=eq.${id}`);
542
- fetchMessages();
543
  } catch(e) { alert("Ошибка: " + e.message); }
544
  }
545
  }
@@ -548,29 +1091,26 @@
548
  if (!state.activeChannel || !state.user) return;
549
  try {
550
  const msgs = await api('messages', 'GET', null, `channel_id=eq.${state.activeChannel}&order=id.desc&limit=50`);
551
- msgs.reverse(); // Чтобы новые были внизу
552
-
553
- const ml = document.getElementById('messages-list');
554
- let isScrolledToBottom = ml.scrollHeight - ml.clientHeight <= ml.scrollTop + 10;
555
 
556
- // Простая синхронизация удалений: если в DOM есть сообщение, которого нет в ответе, удаляем его
557
- const domMsgs = Array.from(ml.querySelectorAll('.msg'));
558
- const fetchedIds = msgs.map(m => m.id);
559
- domMsgs.forEach(el => {
560
- const elId = parseInt(el.dataset.id);
561
- if (!fetchedIds.includes(elId) && elId <= Math.max(...fetchedIds)) {
562
- el.remove();
 
 
 
563
  }
564
  });
565
-
566
- for (let m of msgs) {
567
- const u = state.usersCache[m.user_id] || { username: 'Unknown', role: 'user' };
568
- const time = new Date(m.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
569
 
570
- // Обновляем max id
571
- if (m.id > state.lastMsgId) state.lastMsgId = m.id;
572
-
573
- // Обработка скрытых сообщений голосования
574
  if (m.content.startsWith('[VOTE] ')) {
575
  const parts = m.content.split(' ');
576
  const pId = parseInt(parts[1]);
@@ -584,114 +1124,127 @@
584
 
585
  let el = document.getElementById('msg-' + m.id);
586
 
587
- // Парсинг красивых ответов
588
- let displayContent = m.content;
589
- let quoteHTML = '';
590
- const match = m.content.match(/^\[R:(.+?)\](.*?)\[\/R\](.*)/s);
591
- if (match) {
592
- const rName = match[1];
593
- const rSnippet = match[2];
594
- displayContent = match[3];
595
- quoteHTML = `<div class="quote-block"><div class="q-author">Ответ ${escapeHTML(rName)}:</div><div class="q-text">${escapeHTML(rSnippet)}</div></div>`;
596
- }
597
-
598
- // Если существует - проверяем редактирование
599
  if (el) {
600
  if (el.dataset.raw !== m.content) {
601
  el.dataset.raw = m.content;
602
  if (!m.content.startsWith('[POLL] ')) {
603
- el.querySelector('.content').innerHTML = quoteHTML + escapeHTML(displayContent);
 
 
 
 
 
 
 
 
 
 
 
604
  }
605
  }
606
  continue;
607
  }
608
 
609
- // Создание нового сообщения
610
  const div = document.createElement('div');
611
  div.id = 'msg-' + m.id;
612
  div.dataset.id = m.id;
613
  div.dataset.raw = m.content;
614
- div.dataset.username = u.username;
615
 
616
  const isPing = m.content.includes('@' + state.user.username);
617
  div.className = `msg ${isPing ? 'pinged' : ''}`;
618
 
619
- const isOwn = m.user_id === state.user.id;
620
- const isAdmin = state.user.role === 'admin';
621
-
622
- // --- Генерация кнопок действий (Hover) ---
623
- let actionsHTML = `<div class="msg-actions">
624
- <button onclick="startReply(${m.id})" title="Ответить">↩️</button>`;
625
- if (isOwn && !m.content.startsWith('[POLL]')) {
626
- actionsHTML += `<button onclick="startEdit(${m.id})" title="Редактировать">✏️</button>`;
627
- }
628
- if (isOwn || isAdmin) {
629
- actionsHTML += `<button onclick="deleteMsg(${m.id})" title="Удалить">🗑️</button>`;
630
- }
631
- actionsHTML += `</div>`;
632
-
633
- // Обработка Опросов
634
  if (m.content.startsWith('[POLL] ')) {
635
  try {
636
  const pData = JSON.parse(m.content.substring(7));
637
  const pId = m.id;
638
  if(!state.polls[pId]) state.polls[pId] = { q: pData[0], opts: pData.slice(1), votes: {} };
639
 
640
- div.innerHTML = `<span class="time">[${time}]</span> <span class="author">&lt;${u.role==='admin'?'@':''}${escapeHTML(u.username)}&gt;</span> <div id="poll-container-${pId}"></div> ${actionsHTML}`;
641
  ml.appendChild(div);
642
  renderPollHTML(pId);
643
  } catch(e) {}
644
  } else {
645
- div.innerHTML = `<span class="time">[${time}]</span> <span class="author">&lt;${u.role==='admin'?'@':''}${escapeHTML(u.username)}&gt;</span> <span class="content">${quoteHTML}${escapeHTML(displayContent)}</span> ${actionsHTML}`;
 
 
 
 
 
 
 
 
 
646
  ml.appendChild(div);
 
647
  }
648
  }
649
-
650
- if (isScrolledToBottom) {
651
  ml.scrollTop = ml.scrollHeight;
652
  }
653
- } catch(e) {}
654
  }
655
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656
  function renderPollHTML(pId) {
657
- const container = document.getElementById('poll-container-' + pId);
658
- if (!container) return;
659
- const p = state.polls[pId];
660
- if (!p) return;
661
-
662
- let totalVotes = Object.keys(p.votes).length;
663
- let counts = {};
664
- p.opts.forEach((_, i) => counts[i] = 0);
665
- Object.values(p.votes).forEach(v => counts[v] = (counts[v] || 0) + 1);
666
-
667
- let html = `<div class="poll-box"><div class="poll-q">📊 ${escapeHTML(p.q)}</div>`;
668
- p.opts.forEach((opt, i) => {
669
- let pct = totalVotes === 0 ? 0 : Math.round((counts[i] / totalVotes) * 100);
670
- let isMyVote = p.votes[state.user.id] === i;
671
- html += `<div class="poll-opt" onclick="vote(${pId}, ${i})">
672
- <div style="width: 20px; font-weight: bold; color: ${isMyVote ? 'var(--menubar-bot)' : '#ccc'}">${isMyVote ? '✓' : '○'}</div>
673
- <div style="flex-grow: 1; min-width: 60px;">${escapeHTML(opt)}</div>
674
- <div class="poll-bar-bg"><div class="poll-bar-fg" style="width: ${pct}%"></div></div>
675
- <div style="width: 30px; text-align: right; font-size: 10px; color: #777;">${pct}%</div>
676
- </div>`;
677
  });
678
- html += `<div style="font-size: 10px; color: #888; text-align: right; margin-top: 5px;">Всего голосов: ${totalVotes}</div></div>`;
679
  container.innerHTML = html;
680
  }
681
 
682
- async function vote(pollId, optIdx) {
 
683
  try {
684
  await api('messages', 'POST', {
685
  channel_id: state.activeChannel,
686
  user_id: state.user.id,
687
- content: `[VOTE] ${pollId} ${optIdx}`
688
  });
689
- fetchMessages();
690
  } catch(e) { alert("Ошибка голосования: " + e.message); }
691
  }
692
 
693
  function handleEnter(e) {
694
- if (e.key === 'Enter') sendMessage();
 
 
 
695
  }
696
 
697
  async function sendMessage() {
@@ -701,19 +1254,13 @@
701
 
702
  input.disabled = true;
703
  try {
704
- // Команда создания опроса
705
  const pollMatch = text.match(/^!опрос\s+(.+)/i);
706
  if (pollMatch) {
707
- const args = pollMatch[1].match(/(?:[^\s"]+|"[^"]*")+/g).map(s => s.replace(/^"|"$/g, ''));
708
- if (args.length >= 3) {
709
- await api('messages', 'POST', {
710
- channel_id: state.activeChannel,
711
- user_id: state.user.id,
712
- content: `[POLL] ${JSON.stringify(args)}`
713
- });
714
- input.value = '';
715
- cancelAction();
716
- fetchMessages();
717
  input.disabled = false;
718
  return;
719
  }
@@ -737,7 +1284,7 @@
737
  }
738
 
739
  input.value = '';
740
- await fetchMessages();
741
  } catch(e) {
742
  alert("Не удалось отправить: " + e.message);
743
  } finally {
@@ -746,8 +1293,22 @@
746
  }
747
  }
748
 
749
- // Init
750
- loadProfiles();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
751
  </script>
752
  </body>
753
  </html>
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <title>WebClient 2010 - SQL Edition</title>
7
  <style>
8
+ /* Стили в духе 2010-х годов (Windows 7 Aero / Старые мессенджеры) */
9
  :root {
10
+ --bg-color: #d8e6f3;
11
+ --grad-top: #e4eff8;
12
+ --grad-bot: #b8d4eb;
13
+ --border-color: #799aab;
14
  --text-dark: #1e395b;
15
+ --win-bg: #f4f7f9;
16
+ --menubar-top: #6ba2d4;
17
  --menubar-bot: #3371b6;
18
+ }
19
+
20
+ * {
21
+ box-sizing: border-box;
22
+ user-select: none;
23
  }
24
 
25
  body {
 
 
26
  margin: 0;
27
  padding: 0;
28
+ font-family: Tahoma, Verdana, Arial, sans-serif;
 
 
 
 
29
  font-size: 13px;
30
+ background-color: var(--bg-color);
31
+ color: var(--text-dark);
32
+ height: 100vh;
33
+ display: flex;
34
+ flex-direction: column;
35
+ overflow: hidden;
36
+ }
37
+
38
+ .menubar {
39
+ background: linear-gradient(to bottom, var(--menubar-top) 0%, var(--menubar-bot) 100%);
40
+ border-bottom: 1px solid #14406f;
41
+ padding: 5px 10px;
42
+ display: flex;
43
+ gap: 10px;
44
+ box-shadow: 0 2px 5px rgba(0,0,0,0.2);
45
+ z-index: 100;
46
+ }
47
+
48
+ .btn {
49
+ background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%);
50
+ border: 1px solid var(--border-color);
51
+ border-radius: 3px;
52
+ padding: 4px 12px;
53
+ color: #0f2c4c;
54
+ font-family: Tahoma, sans-serif;
55
+ font-size: 12px;
56
+ cursor: pointer;
57
+ box-shadow: inset 1px 1px 1px rgba(255,255,255,0.8), 1px 1px 2px rgba(0,0,0,0.1);
58
+ text-shadow: 1px 1px 0px rgba(255,255,255,0.5);
59
+ transition: all 0.1s;
60
+ }
61
+
62
+ .btn:hover {
63
+ background: linear-gradient(to bottom, #fff 0%, #eef3f7 50%, #d4e3ef 51%, #f0f7fb 100%);
64
+ }
65
+
66
+ .btn:active {
67
+ background: linear-gradient(to bottom, #b5c6d0 0%, #d8e1e7 100%);
68
+ box-shadow: inset 1px 1px 3px rgba(0,0,0,0.3);
69
+ padding-top: 5px;
70
+ padding-bottom: 3px;
71
  }
72
 
73
  .window {
74
+ position: absolute;
75
+ width: 350px;
76
+ background: var(--win-bg);
77
  border: 1px solid var(--border-color);
 
78
  border-radius: 4px;
79
+ box-shadow: 3px 3px 10px rgba(0,0,0,0.4);
80
+ display: none;
81
+ z-index: 1000;
82
+ flex-direction: column;
83
  overflow: hidden;
84
+ }
85
+
86
+ .window.active {
87
  display: flex;
 
88
  }
89
 
90
  .window-header {
91
+ background: linear-gradient(to bottom, #d4e4ef 0%, #86aecc 100%);
92
+ padding: 5px 8px;
 
93
  font-weight: bold;
94
+ color: #0f2c4c;
95
+ border-bottom: 1px solid var(--border-color);
96
+ cursor: move;
97
  display: flex;
98
  justify-content: space-between;
99
  align-items: center;
100
+ border-radius: 3px 3px 0 0;
101
+ text-shadow: 1px 1px 0px rgba(255,255,255,0.5);
102
+ }
103
+
104
+ .window-close {
105
+ background: linear-gradient(to bottom, #e8a2a2 0%, #cc3333 100%);
106
+ border: 1px solid #7a1c1c;
107
+ color: white;
108
+ font-weight: bold;
109
+ width: 18px;
110
+ height: 18px;
111
+ line-height: 14px;
112
+ text-align: center;
113
+ cursor: pointer;
114
+ border-radius: 2px;
115
+ font-size: 10px;
116
+ box-shadow: inset 1px 1px 1px rgba(255,255,255,0.4);
117
+ }
118
+
119
+ .window-close:hover {
120
+ background: linear-gradient(to bottom, #ffb3b3 0%, #ff4d4d 100%);
121
  }
122
 
123
  .window-body {
 
125
  display: flex;
126
  flex-direction: column;
127
  gap: 10px;
128
+ min-height: 0;
129
  }
130
 
131
+ .input-group {
132
+ display: flex;
133
+ flex-direction: column;
134
+ gap: 3px;
 
135
  }
136
 
137
+ input[type="text"], input[type="password"] {
138
+ border: 1px solid #999;
139
+ box-shadow: inset 1px 1px 2px #ccc;
140
+ padding: 5px;
141
+ border-radius: 2px;
142
  font-family: Tahoma, sans-serif;
143
+ user-select: text;
 
 
 
144
  }
 
 
 
 
145
 
146
+ .workspace {
147
+ flex: 1;
 
 
148
  display: flex;
149
+ padding: 5px;
150
+ gap: 5px;
151
+ height: calc(100vh - 35px);
152
  }
153
 
154
  .panel {
155
+ background: white;
156
+ border: 1px solid var(--border-color);
157
+ border-radius: 2px;
158
+ box-shadow: inset 1px 1px 3px rgba(0,0,0,0.1);
159
  display: flex;
160
  flex-direction: column;
 
161
  }
162
+
 
163
  .panel-header {
164
+ background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 100%);
 
 
165
  border-bottom: 1px solid var(--border-color);
166
+ padding: 4px 8px;
167
+ font-weight: bold;
168
  font-size: 11px;
169
+ color: #555;
170
  }
171
 
172
+ .sidebar {
173
+ width: 200px;
174
+ min-width: 160px;
175
+ flex-shrink: 0;
176
+ display: flex;
177
+ flex-direction: column;
 
 
178
  }
179
+
180
+ .chat-area {
181
+ flex: 1;
182
+ display: flex;
183
+ flex-direction: column;
184
  }
185
 
186
  .chat-messages {
187
+ flex: 1;
 
188
  padding: 10px;
189
+ overflow-y: auto;
190
+ user-select: text;
191
  display: flex;
192
  flex-direction: column;
193
+ gap: 5px;
194
  }
195
 
196
+ .chat-input-area {
197
+ border-top: 1px solid var(--border-color);
198
+ padding: 5px;
199
+ display: flex;
200
+ gap: 5px;
201
+ background: #f4f7f9;
202
+ }
203
+
204
+ .chat-input-area input {
205
+ flex: 1;
206
+ }
207
+
208
+ .list-item {
209
  padding: 4px 8px;
210
+ cursor: pointer;
211
+ border-bottom: 1px solid #eee;
212
+ display: flex;
213
+ justify-content: space-between;
214
+ }
215
+
216
+ .list-item:hover {
217
+ background-color: #e4eff8;
218
+ }
219
+
220
+ .list-item.active {
221
+ background-color: #3371b6;
222
+ color: white;
223
  }
224
+
225
+ .msg {
226
+ font-family: Verdana, sans-serif;
227
+ font-size: 12px;
228
+ border-radius: 3px;
229
+ display: flex;
230
+ flex-wrap: wrap;
231
+ align-items: baseline;
232
+ gap: 5px;
233
+ padding: 2px 0;
234
+ }
235
+
236
+ .msg:hover {
237
+ background-color: rgba(0,0,0,0.03);
238
+ }
239
+
240
  .msg .time { color: #888; font-size: 10px; margin-right: 5px; }
241
  .msg .author { font-weight: bold; color: #1e5799; margin-right: 5px; }
242
  .msg.system .author { color: #cc3333; }
 
243
 
244
  .msg .content {
245
  word-wrap: break-word;
 
247
  white-space: pre-wrap;
248
  display: inline-block;
249
  max-width: 100%;
250
+ flex: 1;
251
  }
252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  .quote-block {
254
  border-left: 3px solid var(--menubar-bot);
255
  background: #f0f4f8;
 
258
  border-radius: 0 3px 3px 0;
259
  font-size: 11px;
260
  color: #555;
261
+ width: 100%;
262
  }
263
+
264
  .quote-block .q-author { font-weight: bold; color: var(--menubar-bot); }
265
  .quote-block .q-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }
266
 
 
276
  color: var(--text-dark);
277
  }
278
 
279
+ .category-header {
280
+ background: linear-gradient(to right, #d4e4ef 0%, #f4f7f9 100%);
281
+ padding: 2px 8px;
282
+ font-size: 10px;
283
+ font-weight: bold;
284
+ color: #555;
285
+ margin-top: 5px;
286
  border-top: 1px solid var(--border-color);
287
+ border-bottom: 1px solid #eee;
288
+ }
289
+
290
+ .code-block {
291
+ background: #fdfdfd;
292
+ border: 1px solid #ccc;
293
+ border-radius: 2px;
294
+ margin: 5px 0;
295
+ font-family: monospace;
296
+ font-size: 11px;
297
+ position: relative;
298
  }
299
 
300
+ .code-header {
301
+ background: #eee;
302
+ border-bottom: 1px solid #ccc;
303
+ padding: 2px 5px;
304
+ text-align: right;
305
+ }
306
+
307
+ .code-block pre {
308
+ margin: 0;
309
+ padding: 5px;
310
+ overflow-x: auto;
311
+ white-space: pre-wrap;
312
+ font-family: inherit;
313
+ }
314
+
315
+ .mobile-tabs {
316
+ display: none;
317
+ background: linear-gradient(to bottom, var(--menubar-top) 0%, var(--menubar-bot) 100%);
318
+ padding: 5px;
319
+ gap: 5px;
320
+ }
321
+
322
+ .mobile-tabs .btn { flex: 1; }
323
+
324
+ @media (max-width: 768px) {
325
+ .workspace { flex-direction: column; gap: 0; padding: 0; height: calc(100vh - 70px); }
326
+ .sidebar { width: 100%; height: 100%; display: none; border: none; }
327
+ .chat-area { display: none; border: none; height: 100%; }
328
+ .mobile-tabs { display: flex; }
329
+
330
+ .workspace[data-tab="channels"] .sidebar-left { display: flex; }
331
+ .workspace[data-tab="chat"] .chat-area { display: flex; }
332
+ .workspace[data-tab="users"] .sidebar-right { display: flex; }
333
+
334
+ .window { width: 90%; left: 5% !important; top: 10% !important; }
335
+ }
336
 
337
+ /* Утилиты */
338
+ .hidden { display: none !important; }
339
+ #docx-window { width: 600px; max-width: 95vw; height: 400px; max-height: 90vh; }
340
+ #docx-content { overflow-y: auto; flex: 1; user-select: text; font-family: monospace; white-space: pre-wrap; font-size: 12px; padding: 10px; background: white;}
341
+
342
+ /* НОВЫЕ СТИЛИ (Resizers, Tabs, Polls, Ping) */
343
+ .resizer {
344
+ width: 5px;
345
+ background: linear-gradient(to right, #e4eff8 0%, #b8d4eb 100%);
346
+ cursor: col-resize;
347
+ flex-shrink: 0;
348
+ border-left: 1px solid var(--border-color);
349
+ border-right: 1px solid #fff;
350
+ }
351
+ .resizer:hover, .resizer:active { background: #86aecc; }
352
+
353
+ .tabs-header {
354
+ display: flex;
355
+ flex-wrap: wrap;
356
+ background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 100%);
357
+ border-bottom: 1px solid var(--border-color);
358
+ padding: 2px 2px 0 2px;
359
+ gap: 2px;
360
+ }
361
+ .tab-btn {
362
+ background: #e4eff8;
363
+ border: 1px solid var(--border-color);
364
+ border-bottom: none;
365
+ padding: 4px 10px;
366
+ cursor: pointer;
367
+ border-radius: 3px 3px 0 0;
368
+ font-size: 11px;
369
+ font-family: Tahoma, sans-serif;
370
+ color: #555;
371
+ }
372
+ .tab-btn.active { background: white; font-weight: bold; color: #1e395b; padding-bottom: 5px; margin-bottom: -1px; z-index: 2; border-bottom: 1px solid white;}
373
+ .docx-tab { overflow-y: auto; flex: 1; user-select: text; font-family: monospace; white-space: pre-wrap; font-size: 12px; padding: 10px; background: white; display: none; }
374
+ .docx-tab.active { display: block; }
375
+
376
+ .msg.pinged {
377
+ background-color: #ffffe0;
378
+ border-left: 2px solid #ffcc00;
379
+ padding-left: 3px;
380
+ }
381
+ .poll-container {
382
+ background: #f4f7f9; border: 1px solid var(--border-color); border-radius: 3px; padding: 8px; margin: 5px 0; font-family: Tahoma; font-size: 11px; width: fit-content; min-width: 200px; box-shadow: inset 1px 1px 2px #fff;
383
+ }
384
+ .poll-opt { display: flex; align-items: center; justify-content: space-between; margin-top: 5px; gap: 10px;}
385
+ .poll-opt .btn { font-size: 10px; padding: 2px 6px; }
386
+
387
+ .recent-servers { border: 1px solid #ccc; background: white; max-height: 60px; overflow-y: auto; margin-bottom: 10px; border-radius: 2px; box-shadow: inset 1px 1px 3px #eee; }
388
+ .recent-servers .list-item { font-size: 11px; padding: 2px 5px; }
389
+
390
+ /* Кнопки действий у сообщений */
391
+ .msg-actions {
392
+ display: none;
393
+ margin-left: 10px;
394
+ vertical-align: top;
395
+ }
396
+ .msg:hover .msg-actions {
397
+ display: inline-flex;
398
+ gap: 3px;
399
+ }
400
+ .msg-actions .btn {
401
+ padding: 1px 4px;
402
+ font-size: 9px;
403
+ margin-right: 2px;
404
+ }
405
+ @media (max-width: 768px) {
406
+ .msg-actions {
407
+ display: inline-flex;
408
+ gap: 3px;
409
+ }
410
  }
 
 
 
 
 
411
  </style>
412
  </head>
413
  <body>
414
 
415
+ <div class="menubar">
416
+ <button class="btn" onclick="openWindow('connect-window')">Подключиться</button>
417
+ <button class="btn hidden" id="btn-disconnect" onclick="disconnect()">Отключиться</button>
418
+ <button class="btn" onclick="openWindow('docx-window')">DOCX / FAQ</button>
419
+ <div style="flex:1"></div>
420
+ <div id="user-status" style="color: white; line-height: 24px; text-shadow: 1px 1px 1px #000; font-weight: bold;">Не подключен</div>
421
+ </div>
422
+
423
+ <div class="workspace" data-tab="chat">
424
+ <!-- Левая колонка: Каналы -->
425
+ <div class="panel sidebar sidebar-left" id="panel-left">
426
+ <div class="panel-header">Каналы</div>
427
+ <div id="channels-list" style="overflow-y: auto; flex: 1;">
428
+ <div style="padding: 10px; color: #888;">Подключитесь для загрузки...</div>
429
+ </div>
430
+ <div style="padding: 5px; border-top: 1px solid var(--border-color); background: #f4f7f9; display: flex; gap:4px; flex-shrink: 0;">
431
+ <input type="text" id="new-channel-name" placeholder="Имя канала" style="flex: 1; min-width: 50px;">
432
+ <button class="btn" onclick="createChannel()" style="flex-shrink: 0;">+</button>
433
+ </div>
434
+ </div>
435
+
436
+ <div class="resizer" id="resizer-left"></div>
437
+
438
+ <!-- Центральная колонка: Чат -->
439
+ <div class="panel chat-area" id="panel-chat">
440
+ <div class="panel-header" id="chat-title">Чат</div>
441
+ <div class="chat-messages" id="messages-list">
442
+ <div style="color: #999; text-align: center; margin-top: 20px;">Ожидание подключения к серверу...</div>
443
+ </div>
444
 
445
+ <!-- Баннер действия (ответ/редактирование) -->
446
+ <div id="action-banner" class="action-banner hidden">
447
+ <span id="action-banner-text">Действие...</span>
448
+ <button class="btn" style="padding: 1px 5px; background: #cc3333; color: white; border:none;" onclick="cancelAction()">X</button>
449
+ </div>
450
 
451
+ <div class="chat-input-area">
452
+ <input type="text" id="msg-input" placeholder="Сообщение или команда (например, !опрос Вопрос Ответ1 Ответ2)" onkeydown="handleEnter(event)">
453
+ <button class="btn" onclick="sendMessage()">Отправить</button>
454
+ </div>
455
+ </div>
456
 
457
+ <div class="resizer" id="resizer-right"></div>
458
+
459
+ <!-- Правая колонка: Пользователи -->
460
+ <div class="panel sidebar sidebar-right" id="panel-right">
461
+ <div class="panel-header">Пользователи</div>
462
+ <div id="users-list" style="overflow-y: auto; flex: 1;">
463
+ <div style="padding: 10px; color: #888;">Пусто</div>
464
+ </div>
465
  </div>
466
  </div>
467
 
468
+ <div class="mobile-tabs">
469
+ <button class="btn" onclick="setMobileTab('channels')">Каналы</button>
470
+ <button class="btn" onclick="setMobileTab('chat')">Чат</button>
471
+ <button class="btn" onclick="setMobileTab('users')">Люди</button>
472
+ </div>
473
+
474
+ <div id="connect-window" class="window" style="top: 100px; left: 100px;">
475
  <div class="window-header">
476
+ <span>⚙️ Настройки подключения</span>
477
+ <div class="window-close" onclick="closeWindow('connect-window')">X</div>
478
  </div>
479
 
480
+ <div class="window-body" id="connect-step-1">
481
+ <div style="font-size: 11px; color: #555; margin-bottom: 2px;">Последние серверы:</div>
482
+ <div class="recent-servers" id="recent-servers-list"></div>
483
+
484
+ <div class="input-group">
485
+ <label>Supabase Project URL:</label>
486
+ <input type="text" id="supa-url" placeholder="https://xxxx.supabase.co" value="">
487
+ </div>
488
+ <div class="input-group">
489
+ <label>Anon Key:</label>
490
+ <input type="password" id="supa-key" placeholder="eyJhbGciOiJIUzI1NiIsInR5c...">
491
  </div>
492
+ <button class="btn" style="margin-top: 10px;" onclick="checkConnection()">Check (Проверить)</button>
493
+ <div id="connect-error" style="color: red; font-size: 11px; margin-top: 5px;"></div>
494
+ </div>
495
 
496
+ <div class="window-body hidden" id="connect-step-2">
497
+ <div style="color: green; font-size: 11px; margin-bottom: 10px;">✅ Сервер доступен!</div>
498
+ <div class="input-group">
499
+ <label>Имя пользователя (Ник):</label>
500
+ <input type="text" id="auth-user" placeholder="Например: admin">
 
 
 
 
 
 
 
 
 
 
 
501
  </div>
502
+ <div class="input-group">
503
+ <label>Пароль (Пинкод):</label>
504
+ <input type="password" id="auth-pass" placeholder="***">
505
+ </div>
506
+ <div style="display: flex; gap: 10px; margin-top: 10px;">
507
+ <button class="btn" style="flex:1" onclick="login()">Вход</button>
508
+ <button class="btn" style="flex:1" onclick="register()">Регистрация</button>
509
+ </div>
510
+ <div id="auth-error" style="color: red; font-size: 11px; margin-top: 5px;"></div>
511
+ </div>
512
+ </div>
513
+
514
+ <div id="docx-window" class="window" style="top: 50px; left: 50px;">
515
+ <div class="window-header">
516
+ <span>📄 DOCX - Руководство WebClient</span>
517
+ <div class="window-close" onclick="closeWindow('docx-window')">X</div>
518
+ </div>
519
+ <div class="tabs-header">
520
+ <button class="tab-btn active" onclick="switchDocxTab('tab-setup', this)">Настройка проекта</button>
521
+ <button class="tab-btn" onclick="switchDocxTab('tab-sql', this)">SQL код</button>
522
+ <button class="tab-btn" onclick="switchDocxTab('tab-rls', this)">RLS защита (обязательно)</button>
523
+ <button class="tab-btn" onclick="switchDocxTab('tab-cmd', this)">Команды</button>
524
+ <button class="tab-btn" onclick="switchDocxTab('tab-faq', this)">FAQ</button>
525
+ </div>
526
+ <div class="window-body" style="padding: 0; flex: 1; display: flex; flex-direction: column; min-height: 0;">
527
+
528
+ <div id="tab-setup" class="docx-tab active">
529
+ = НАСТРОЙКА ПРОЕКТА SUPABASE =
530
+
531
+ WebClient работает на базе Supabase (бесплатная альтернатива Firebase с SQL под капотом). Вам нужно создать свой сервер баз данных.
532
+
533
+ ШАГ 1: РЕГИСТРАЦИЯ И СОЗДАНИЕ
534
+ 1. Перейдите на сайт supabase.com и зарегистрируйтесь (можно через GitHub).
535
+ 2. Нажмите кнопку "New Project". Выберите организацию, введите название проекта и надежный пароль для базы данных.
536
+ 3. Выберите регион (например, Central EU) и нажмите "Create new project".
537
+ 4. Подождите пару минут, пока сервер инициализируется.
538
+
539
+ ШАГ 2: ПОЛУЧЕНИЕ КЛЮЧЕЙ (ДЛЯ ПОДКЛЮЧЕНИЯ)
540
+ 1. В левом меню панели Supabase найдите иконку шестеренки ("Project Settings").
541
+ 2. Перейдите во вкладку "API".
542
+ 3. Здесь вам нужны два значения:
543
+ - Project URL (выглядит как https://xxxxxx.supabase.co)
544
+ - Project API keys -> anon / public (длинный токен)
545
+ 4. Именно эти два значения нужно вводить в WebClient при нажатии кнопки "Подключиться".
546
+
547
+ ШАГ 3: БАЗА ДАННЫХ
548
+ После создания проекта перейдите во вкладку "SQL Editor" (иконка с символами SQL в левом меню).
549
+ Перейдите в следующие вкладки "SQL код" и "RLS защита" в этом окне, чтобы получить нужные скрипты.
550
+ </div>
551
+
552
+ <div id="tab-sql" class="docx-tab">
553
+ = СОЗДАНИЕ ТАБЛИЦ (SQL) =
554
+
555
+ Скопируйте код ниже, вставьте его в SQL Editor в панели Supabase и нажмите "Run" (Выполнить). Это создаст структуру базы данных для чата.
556
+
557
+ <div class="code-block">
558
+ <div class="code-header"><button class="btn" style="padding:1px 5px; font-size:9px;" onclick="copyCode('sql-tables')">Копировать</button></div>
559
+ <pre id="sql-tables">-- 1. Таблица пользователей
560
+ CREATE TABLE users (
561
+ id SERIAL PRIMARY KEY,
562
+ username TEXT UNIQUE NOT NULL,
563
+ password TEXT NOT NULL,
564
+ role TEXT DEFAULT 'user' -- 'admin' или 'user', 'banned'
565
+ );
566
+
567
+ -- 2. Таблица каналов
568
+ CREATE TABLE channels (
569
+ id SERIAL PRIMARY KEY,
570
+ name TEXT UNIQUE NOT NULL
571
+ );
572
+
573
+ -- 3. Таблица сообщений
574
+ CREATE TABLE messages (
575
+ id SERIAL PRIMARY KEY,
576
+ channel_id INTEGER REFERENCES channels(id) ON DELETE CASCADE,
577
+ user_id INTEGER REFERENCES users(id),
578
+ content TEXT NOT NULL,
579
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
580
+ );
581
+
582
+ -- 4. Базовые данные (Создаем канал по умолчанию)
583
+ INSERT INTO channels (name) VALUES ('general');</pre>
584
+ </div>
585
+ </div>
586
+
587
+ <div id="tab-rls" class="docx-tab">
588
+ = RLS ЗАЩИТА (ОБЯЗАТЕЛЬНО) =
589
+
590
+ Supabase PostgREST API (через который работает клиент) по умолчанию блокирует любые запросы к таблицам, если не настроены политики доступа (Row Level Security).
591
+ Без этого шага WebClient будет выдавать ошибки доступа!
592
+
593
+ Скопируйте и выполните этот код в SQL Editor после создания таблиц:
594
+
595
+ <div class="code-block">
596
+ <div class="code-header"><button class="btn" style="padding:1px 5px; font-size:9px;" onclick="copyCode('sql-rls')">Копировать</button></div>
597
+ <pre id="sql-rls">-- Включаем защиту для всех таблиц
598
+ ALTER TABLE users ENABLE ROW LEVEL SECURITY;
599
+ ALTER TABLE channels ENABLE ROW LEVEL SECURITY;
600
+ ALTER TABLE messages ENABLE ROW LEVEL SECURITY;
601
+
602
+ -- Так как наш "old school" WebClient сам занимается аутентификацией
603
+ -- и хранит пароли в открытом виде (в рамках эксперимента/стиля),
604
+ -- мы разрешаем публичный доступ к REST API для этих таблиц:
605
+ CREATE POLICY "Allow all users" ON users FOR ALL USING (true);
606
+ CREATE POLICY "Allow all channels" ON channels FOR ALL USING (true);
607
+ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
608
+ </div>
609
 
610
+ Внимание: Этот метод аутентификации (просто хранение пароля в таблице users) не является безопасным для реальных проектов с конфиденциальными данными. Он используется здесь исключительно в образовательных целях для имитации простых систем начала 2010-х годов!
611
+ </div>
612
+
613
+ <div id="tab-cmd" class="docx-tab">
614
+ = КОМАНДЫ ЧАТА =
615
+
616
+ В WebClient поддерживаются встроенные команды, которые можно вводить в поле сообщения:
617
+
618
+ 1. Опросы (Голосования)
619
+ Синтаксис: !опрос Название Вариант1 Вариант2 ...
620
+ Пример: !опрос Какой_язык_лучше? JS Python C++
621
+ (Используйте нижние подчеркивания вместо пробелов в названиях вариантов)
622
+
623
+ 2. Пинги (Упоминания)
624
+ Синтаксис: @имяпользователя
625
+ Пример: Привет, @admin !
626
+ Если кто-то напишет ваше имя через @, сообщение подсветится желтым фоном. Вы также можете нажать кнопку "Ответить" рядом с чужим сообщением, чтобы упомянуть автора.
627
+ </div>
628
+
629
+ <div id="tab-faq" class="docx-tab">
630
+ = ЧАСТЫЕ ВОПРОСЫ (FAQ) =
631
+
632
+ В: Как редактировать/удалять/пересылать сообщения?
633
+ О: Наведите курсор на сообщение (на телефоне кнопки видны всегда). Справа появятся кнопки действий. Вы можете удалять/редактировать только свои сообщения (если вы не admin).
634
+
635
+ В: Как сделать себя администратором?
636
+ О: Зарегистрируйте аккаунт через клиент. Затем зайдите в панель управления Supabase -> Table Editor -> таблица 'users'. Найдите свою учетную запись и вручную измените значение колонки 'role' с 'user' на 'admin'. После этого в клиенте у вас появятся красные кнопки [BAN] в списке пользователей и права на удаление чужих сообщений.
637
+
638
+ В: Как работают окна и панели?
639
+ О: Окна можно перетаскивать за синий заголовок. Также можно изменять ширину боковых панелей (каналов и пользователей), потянув за узкие разделители между панелями. Они не могут быть сжаты слишком сильно для сохранения целостности интерфейса.
640
+
641
+ В: Как отключиться от текущего сервера и войти на другой?
642
+ О: На верхней панели при успешном подключении появляется кнопка "Отключиться". Нажмите её, чтобы сбросить соединение и вернуться в начальное меню выбора сервера.
643
  </div>
644
  </div>
645
  </div>
646
 
647
  <script>
648
+ // --- 1. Логика перетаскивания окон ---
649
+ function makeDraggable(el) {
650
+ const header = el.querySelector('.window-header');
651
+ let startX, startY, initialX, initialY;
652
+
653
+ const target = header ? header : el;
654
+
655
+ target.addEventListener('mousedown', (e) => {
656
+ if (e.target.classList.contains('window-close')) return;
657
+ e.preventDefault();
658
+
659
+ document.querySelectorAll('.window').forEach(w => w.style.zIndex = 1000);
660
+ el.style.zIndex = 1001;
661
+
662
+ startX = e.clientX;
663
+ startY = e.clientY;
664
+ initialX = el.offsetLeft;
665
+ initialY = el.offsetTop;
666
+
667
+ const onMouseMove = (ev) => {
668
+ el.style.left = initialX + (ev.clientX - startX) + "px";
669
+ el.style.top = initialY + (ev.clientY - startY) + "px";
670
+ };
671
+
672
+ const onMouseUp = () => {
673
+ document.removeEventListener('mousemove', onMouseMove);
674
+ document.removeEventListener('mouseup', onMouseUp);
675
+ };
676
+
677
+ document.addEventListener('mousemove', onMouseMove);
678
+ document.addEventListener('mouseup', onMouseUp);
679
+ });
680
+ }
681
+
682
+ document.querySelectorAll('.window').forEach(makeDraggable);
683
+
684
+ function openWindow(id) {
685
+ const win = document.getElementById(id);
686
+ win.classList.add('active');
687
+ if(win.style.top === "100px") {
688
+ win.style.top = (window.innerHeight / 2 - win.offsetHeight / 2) + "px";
689
+ win.style.left = (window.innerWidth / 2 - win.offsetWidth / 2) + "px";
690
+ }
691
+ }
692
+
693
+ function closeWindow(id) {
694
+ document.getElementById(id).classList.remove('active');
695
+ }
696
+
697
+ function setMobileTab(tab) {
698
+ document.querySelector('.workspace').setAttribute('data-tab', tab);
699
+ }
700
+
701
+ // --- Логика вкладок DOCX ---
702
+ function switchDocxTab(tabId, btn) {
703
+ document.querySelectorAll('.docx-tab').forEach(t => t.classList.remove('active'));
704
+ document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
705
+ document.getElementById(tabId).classList.add('active');
706
+ if(btn) btn.classList.add('active');
707
+ }
708
+
709
+ // --- Логика ресайзеров ---
710
+ function initResizers() {
711
+ const resLeft = document.getElementById('resizer-left');
712
+ const resRight = document.getElementById('resizer-right');
713
+ const pLeft = document.getElementById('panel-left');
714
+ const pRight = document.getElementById('panel-right');
715
+
716
+ resLeft.addEventListener('mousedown', (e) => {
717
+ e.preventDefault();
718
+ document.body.style.cursor = 'col-resize';
719
+ const onMouseMove = (ev) => { pLeft.style.width = Math.max(160, Math.min(ev.clientX, 400)) + 'px'; };
720
+ const onMouseUp = () => { document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); document.body.style.cursor = 'default'; };
721
+ document.addEventListener('mousemove', onMouseMove);
722
+ document.addEventListener('mouseup', onMouseUp);
723
+ });
724
+
725
+ resRight.addEventListener('mousedown', (e) => {
726
+ e.preventDefault();
727
+ document.body.style.cursor = 'col-resize';
728
+ const onMouseMove = (ev) => { pRight.style.width = Math.max(160, Math.min(document.body.clientWidth - ev.clientX, 400)) + 'px'; };
729
+ const onMouseUp = () => { document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); document.body.style.cursor = 'default'; };
730
+ document.addEventListener('mousemove', onMouseMove);
731
+ document.addEventListener('mouseup', onMouseUp);
732
+ });
733
  }
734
 
735
  // --- 2. Состояние приложения и REST API ---
 
749
  };
750
 
751
  async function api(table, method = 'GET', body = null, query = '') {
752
+ if (!state.url || !state.key) return null;
753
+
754
  const endpoint = `${state.url}/rest/v1/${table}${query ? '?' + query : ''}`;
755
  const headers = {
756
  'apikey': state.key,
757
  'Authorization': `Bearer ${state.key}`,
758
+ 'Content-Type': 'application/json',
759
+ 'Prefer': 'return=representation'
760
  };
 
 
 
 
761
 
762
+ const config = { method, headers };
763
+ if (body) config.body = JSON.stringify(body);
764
 
765
+ try {
766
+ const res = await fetch(endpoint, config);
767
+ if (!res.ok) {
768
+ const errText = await res.text();
769
+ throw new Error(errText || `HTTP ${res.status}`);
770
+ }
771
+ if (method === 'DELETE' || res.status === 204) return true;
772
+ return await res.json();
773
+ } catch (e) {
774
+ console.error("API Error:", e);
775
+ throw e;
776
  }
 
 
 
777
  }
778
 
779
+ // --- 3. Логика Подключения и Авторизации ---
780
+
781
+ function loadRecentServers() {
782
+ let list = JSON.parse(localStorage.getItem('webclient_recent') || '[]');
783
+ const container = document.getElementById('recent-servers-list');
784
+ if(list.length === 0) {
785
+ container.innerHTML = '<div style="padding: 5px; color:#888; font-size:10px;">Нет сохраненных серверов</div>';
786
+ return;
787
+ }
788
+ container.innerHTML = list.map(s => `<div class="list-item" onclick="document.getElementById('supa-url').value='${s.url}'; document.getElementById('supa-key').value='${s.key}';">🔌 ${s.url.replace('https://','')}</div>`).join('');
 
 
 
 
 
 
 
 
 
 
789
  }
790
 
791
+ function saveRecentServer(url, key) {
792
+ let list = JSON.parse(localStorage.getItem('webclient_recent') || '[]');
793
+ list = list.filter(s => s.url !== url);
794
+ list.unshift({url, key});
795
+ if(list.length > 5) list.pop();
796
+ localStorage.setItem('webclient_recent', JSON.stringify(list));
797
+ loadRecentServers();
798
+ }
799
+
800
+ async function checkConnection() {
801
+ const urlInput = document.getElementById('supa-url').value.trim();
802
+ const keyInput = document.getElementById('supa-key').value.trim();
803
+ const errDiv = document.getElementById('connect-error');
804
 
805
+ if (!urlInput || !keyInput) {
806
+ errDiv.innerText = "Заполните URL и Key";
807
+ return;
808
+ }
809
+
810
+ state.url = urlInput.endsWith('/') ? urlInput.slice(0, -1) : urlInput;
811
+ state.key = keyInput;
812
+ errDiv.innerText = "Проверка...";
813
+
814
+ try {
815
+ await api('channels', 'GET', null, 'select=id&limit=1');
816
+ saveRecentServer(state.url, state.key);
817
+ document.getElementById('connect-step-1').classList.add('hidden');
818
+ document.getElementById('connect-step-2').classList.remove('hidden');
819
+ errDiv.innerText = "";
820
+ } catch (e) {
821
+ errDiv.innerText = "Ошибка: Проверьте данные или права (RLS). " + e.message;
822
+ state.url = ''; state.key = '';
823
  }
 
 
 
824
  }
825
 
826
  async function login() {
827
+ const u = document.getElementById('auth-user').value.trim();
828
+ const p = document.getElementById('auth-pass').value.trim();
829
+ const err = document.getElementById('auth-error');
 
 
 
 
 
 
 
830
 
831
+ if (!u || !p) return err.innerText = "Введите логин и пароль";
 
 
 
832
 
833
  try {
834
  const users = await api('users', 'GET', null, `username=eq.${encodeURIComponent(u)}&password=eq.${encodeURIComponent(p)}`);
835
+ if (users && users.length > 0) {
 
836
  state.user = users[0];
837
+ if (state.user.role === 'banned') {
838
+ throw new Error("Вы забанены на этом сервере!");
 
 
 
 
 
 
 
 
839
  }
840
+ finishAuth();
841
+ } else {
842
+ err.innerText = "Неверный логин или пароль";
843
  }
844
+ } catch(e) {
845
+ err.innerText = e.message;
846
  }
847
  }
848
 
849
+ async function register() {
850
+ const u = document.getElementById('auth-user').value.trim();
851
+ const p = document.getElementById('auth-pass').value.trim();
852
+ const err = document.getElementById('auth-error');
853
+
854
+ if (!u || !p) return err.innerText = "Введите логин и пароль";
855
+
856
+ try {
857
+ const exist = await api('users', 'GET', null, `username=eq.${encodeURIComponent(u)}`);
858
+ if (exist && exist.length > 0) throw new Error("Ник уже занят");
859
+
860
+ const res = await api('users', 'POST', { username: u, password: p, role: 'user' });
861
+ if (res && res.length > 0) {
862
+ state.user = res[0];
863
+ finishAuth();
864
+ }
865
+ } catch(e) {
866
+ err.innerText = e.message;
867
+ }
868
+ }
869
+
870
+ function finishAuth() {
871
+ closeWindow('connect-window');
872
+ document.getElementById('user-status').innerText = `👤 ${state.user.username} [${state.user.role}]`;
873
+ document.getElementById('messages-list').innerHTML = `<div class="msg system"><span class="author">***</span> SYSTEM: Соединение установлено. Авторизация успешна.</div>`;
874
+ document.getElementById('btn-disconnect').classList.remove('hidden');
875
+
876
+ fetchAllUsers();
877
+ loadChannels();
878
 
879
+ if(state.polling) clearInterval(state.polling);
880
+ state.polling = setInterval(appTick, 2000);
881
  }
882
 
883
+ function disconnect() {
 
884
  state.user = null;
885
  state.activeChannel = null;
886
+ state.channels = [];
887
+ state.usersCache = {};
888
+ state.editingId = null;
889
+ state.replyingToName = null;
890
+ state.replyingToSnippet = null;
891
+ if(state.polling) clearInterval(state.polling);
892
+
893
+ document.getElementById('user-status').innerText = 'Не подключен';
894
+ document.getElementById('messages-list').innerHTML = '<div style="color: #999; text-align: center; margin-top: 20px;">Ожидание подключения к серверу...</div>';
895
+ document.getElementById('btn-disconnect').classList.add('hidden');
896
+ document.getElementById('chat-title').innerText = 'Чат';
897
+
898
+ renderChannels();
899
+ renderUsersList();
900
+ openWindow('connect-window');
901
  }
902
+
903
+ async function fetchAllUsers() {
904
  try {
905
  const users = await api('users', 'GET', null, 'select=id,username,role');
906
+ if (users) {
907
+ users.forEach(u => state.usersCache[u.id] = u);
908
+ renderUsersList();
909
+ }
910
+ } catch(e) {}
 
 
 
 
 
 
 
 
911
  }
912
 
913
+ // --- 4. Логика Чата (Каналы, Сообщения) ---
914
+
915
+ async function loadChannels() {
916
  try {
917
+ const chans = await api('channels', 'GET', null, 'order=id.asc');
918
+ if (chans) {
919
+ state.channels = chans;
920
+ renderChannels();
921
+ if (chans.length > 0 && !state.activeChannel) {
922
+ joinChannel(chans[0].id);
923
+ }
924
  }
925
+ } catch(e) { console.error("Load channels err", e); }
926
  }
927
 
928
  function renderChannels() {
929
  const cl = document.getElementById('channels-list');
930
  cl.innerHTML = '';
931
+ if(!state.user) {
932
+ cl.innerHTML = '<div style="padding: 10px; color: #888;">Подключитесь для загрузки...</div>';
933
+ return;
934
+ }
935
+
936
+ const serverChans = state.channels.filter(c => c.name === 'general');
937
+ const userChans = state.channels.filter(c => c.name !== 'general');
938
+
939
+ const createChanEl = (c) => {
940
  const div = document.createElement('div');
941
+ div.className = `list-item ${state.activeChannel === c.id ? 'active' : ''}`;
942
+ div.innerHTML = `<span>#${c.name}</span>`;
943
+ if (state.user && state.user.role === 'admin' && c.name !== 'general') {
944
+ div.innerHTML += `<span style="color:#ffb3b3;" onclick="deleteChannel(${c.id}, event)">x</span>`;
945
+ }
946
+ div.onclick = () => joinChannel(c.id);
947
+ return div;
948
+ };
949
+
950
+ if(serverChans.length > 0) {
951
+ cl.innerHTML += '<div class="category-header">Серверные каналы</div>';
952
+ serverChans.forEach(c => cl.appendChild(createChanEl(c)));
953
+ }
954
+ if(userChans.length > 0) {
955
+ cl.innerHTML += '<div class="category-header">Пользовательские каналы</div>';
956
+ userChans.forEach(c => cl.appendChild(createChanEl(c)));
957
+ }
958
  }
959
 
960
+ async function createChannel() {
961
+ if(!state.user) return;
962
+ const input = document.getElementById('new-channel-name');
963
+ const name = input.value.trim().toLowerCase().replace(/[^a-z0-9_-]/g, '');
964
+ if (!name) return;
965
+
966
+ try {
967
+ await api('channels', 'POST', { name });
968
+ input.value = '';
969
+ loadChannels();
970
+ } catch(e) { alert("Ошибка создания канала: " + e.message); }
971
+ }
972
+
973
+ async function deleteChannel(id, event) {
974
+ event.stopPropagation();
975
+ if(!confirm("Удалить канал?")) return;
976
+ try {
977
+ await api('channels', 'DELETE', null, `id=eq.${id}`);
978
+ if (state.activeChannel === id) state.activeChannel = null;
979
+ loadChannels();
980
+ } catch(e) {}
981
+ }
982
+
983
+ async function joinChannel(id) {
984
  state.activeChannel = id;
 
985
  state.lastMsgId = 0;
986
+ state.polls = {};
987
+ const c = state.channels.find(x => x.id === id);
988
+ document.getElementById('chat-title').innerText = `Чат :: #${c ? c.name : 'Unknown'}`;
989
+ document.getElementById('messages-list').innerHTML = `<div class="msg system"><span class="author">***</span> SYSTEM: Вы вошли в канал #${c ? c.name : 'Unknown'}</div>`;
990
  renderChannels();
991
+ await fetchMessages();
 
992
  }
993
 
994
+ async function getUser(id) {
995
+ if (state.usersCache[id]) return state.usersCache[id];
996
+ try {
997
+ const u = await api('users', 'GET', null, `id=eq.${id}&select=id,username,role`);
998
+ if (u && u.length > 0) {
999
+ state.usersCache[id] = u[0];
1000
+ renderUsersList();
1001
+ return u[0];
1002
+ }
1003
+ } catch(e) {}
1004
+ return { username: 'Unknown' };
1005
+ }
1006
+
1007
+ function renderUsersList() {
1008
+ const ul = document.getElementById('users-list');
1009
+ ul.innerHTML = '';
1010
+ Object.values(state.usersCache).forEach(u => {
1011
+ const div = document.createElement('div');
1012
+ div.className = 'list-item';
1013
+ div.innerHTML = `<span>${u.role === 'admin' ? '@' : ''}${u.username}</span>`;
1014
+
1015
+ if (state.user && state.user.role === 'admin' && u.id !== state.user.id) {
1016
+ div.innerHTML += `<span style="color:red; font-size:10px;" onclick="banUser(${u.id}, event)">[BAN]</span>`;
1017
+ }
1018
+ ul.appendChild(div);
1019
+ });
1020
+ }
1021
+
1022
+ async function banUser(userId, event) {
1023
+ event.stopPropagation();
1024
+ if(!confirm("Забанить пользователя?")) return;
1025
+ try {
1026
+ await api('users', 'PATCH', { role: 'banned' }, `id=eq.${userId}`);
1027
+ alert("Пользователь забанен!");
1028
+ delete state.usersCache[userId];
1029
+ } catch(e) { alert("Ошибка: " + e.message); }
1030
+ }
1031
+
1032
+ function escapeHTML(str) {
1033
+ return str.replace(/[&<>'"]/g, tag => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' }[tag]));
1034
+ }
1035
+
1036
+ function copyCode(id) {
1037
+ const text = document.getElementById(id).innerText;
1038
+ const ta = document.createElement('textarea');
1039
+ ta.value = text;
1040
+ document.body.appendChild(ta);
1041
+ ta.select();
1042
+ try { document.execCommand('copy'); } catch(e){}
1043
+ document.body.removeChild(ta);
1044
+ }
1045
+
1046
+ function formatContent(text) {
1047
+ return escapeHTML(text);
1048
+ }
1049
+
1050
+ // Функции для ответа и редактирования (баннер)
1051
+ function startReply(username, rawContent) {
1052
  cancelAction();
1053
  state.replyingToName = username;
1054
  let cleanText = rawContent.replace(/\[R:.*?\](.*?)\[\/R\]/g, "").trim();
 
1059
  document.getElementById('msg-input').focus();
1060
  }
1061
 
1062
+ function startEdit(id, rawContent) {
 
 
 
1063
  cancelAction();
1064
  state.editingId = id;
1065
  document.getElementById('action-banner-text').innerText = `Редактирование сообщения`;
1066
  document.getElementById('action-banner').classList.remove('hidden');
1067
 
1068
  const input = document.getElementById('msg-input');
1069
+ input.value = rawContent;
1070
  input.focus();
1071
  }
1072
 
 
1082
  if(confirm("Удалить это сообщение?")) {
1083
  try {
1084
  await api('messages', 'DELETE', null, `id=eq.${id}`);
1085
+ fetchMessages();
1086
  } catch(e) { alert("Ошибка: " + e.message); }
1087
  }
1088
  }
 
1091
  if (!state.activeChannel || !state.user) return;
1092
  try {
1093
  const msgs = await api('messages', 'GET', null, `channel_id=eq.${state.activeChannel}&order=id.desc&limit=50`);
1094
+ if (!msgs) return;
1095
+ msgs.reverse();
 
 
1096
 
1097
+ const ml = document.getElementById('messages-list');
1098
+ const isAtBottom = (ml.scrollHeight - ml.scrollTop - ml.clientHeight) < 20;
1099
+
1100
+ const currentMsgIds = new Set(Array.from(ml.querySelectorAll('.msg[data-id]')).map(el => parseInt(el.dataset.id)));
1101
+ const fetchedMsgIds = new Set(msgs.map(m => m.id));
1102
+
1103
+ currentMsgIds.forEach(id => {
1104
+ if (!fetchedMsgIds.has(id)) {
1105
+ const el = document.getElementById('msg-' + id);
1106
+ if (el) el.remove();
1107
  }
1108
  });
 
 
 
 
1109
 
1110
+ for (const m of msgs) {
1111
+ const u = await getUser(m.user_id);
1112
+ const time = new Date(m.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', second:'2-digit'});
1113
+
1114
  if (m.content.startsWith('[VOTE] ')) {
1115
  const parts = m.content.split(' ');
1116
  const pId = parseInt(parts[1]);
 
1124
 
1125
  let el = document.getElementById('msg-' + m.id);
1126
 
 
 
 
 
 
 
 
 
 
 
 
 
1127
  if (el) {
1128
  if (el.dataset.raw !== m.content) {
1129
  el.dataset.raw = m.content;
1130
  if (!m.content.startsWith('[POLL] ')) {
1131
+ let displayContent = m.content;
1132
+ let quoteHTML = '';
1133
+ const match = m.content.match(/^\[R:(.+?)\](.*?)\[\/R\](.*)/s);
1134
+ if (match) {
1135
+ const rName = match[1];
1136
+ const rSnippet = match[2];
1137
+ displayContent = match[3];
1138
+ quoteHTML = `<div class="quote-block"><div class="q-author">Ответ ${escapeHTML(rName)}:</div><div class="q-text">${escapeHTML(rSnippet)}</div></div>`;
1139
+ }
1140
+ el.querySelector('.content').innerHTML = quoteHTML + formatContent(displayContent);
1141
+ // Обновляем кнопки действий (вдруг права изменились)
1142
+ updateMessageActions(el, m, u);
1143
  }
1144
  }
1145
  continue;
1146
  }
1147
 
 
1148
  const div = document.createElement('div');
1149
  div.id = 'msg-' + m.id;
1150
  div.dataset.id = m.id;
1151
  div.dataset.raw = m.content;
 
1152
 
1153
  const isPing = m.content.includes('@' + state.user.username);
1154
  div.className = `msg ${isPing ? 'pinged' : ''}`;
1155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1156
  if (m.content.startsWith('[POLL] ')) {
1157
  try {
1158
  const pData = JSON.parse(m.content.substring(7));
1159
  const pId = m.id;
1160
  if(!state.polls[pId]) state.polls[pId] = { q: pData[0], opts: pData.slice(1), votes: {} };
1161
 
1162
+ div.innerHTML = `<span class="time">[${time}]</span> <span class="author">&lt;${u.role==='admin'?'@':''}${u.username}&gt;</span> <div id="poll-container-${pId}"></div>`;
1163
  ml.appendChild(div);
1164
  renderPollHTML(pId);
1165
  } catch(e) {}
1166
  } else {
1167
+ let displayContent = m.content;
1168
+ let quoteHTML = '';
1169
+ const match = m.content.match(/^\[R:(.+?)\](.*?)\[\/R\](.*)/s);
1170
+ if (match) {
1171
+ const rName = match[1];
1172
+ const rSnippet = match[2];
1173
+ displayContent = match[3];
1174
+ quoteHTML = `<div class="quote-block"><div class="q-author">Ответ ${escapeHTML(rName)}:</div><div class="q-text">${escapeHTML(rSnippet)}</div></div>`;
1175
+ }
1176
+ div.innerHTML = `<span class="time">[${time}]</span> <span class="author">&lt;${u.role==='admin'?'@':''}${u.username}&gt;</span> <span class="content">${quoteHTML}${formatContent(displayContent)}</span>`;
1177
  ml.appendChild(div);
1178
+ updateMessageActions(div, m, u);
1179
  }
1180
  }
1181
+ if (isAtBottom) {
 
1182
  ml.scrollTop = ml.scrollHeight;
1183
  }
1184
+ } catch(e) { console.error("Msg fetch err", e); }
1185
  }
1186
+
1187
+ function updateMessageActions(el, m, u) {
1188
+ // Добавляем или обновляем блок кнопок действий
1189
+ let actionsDiv = el.querySelector('.msg-actions');
1190
+ if (!actionsDiv) {
1191
+ actionsDiv = document.createElement('div');
1192
+ actionsDiv.className = 'msg-actions';
1193
+ el.appendChild(actionsDiv);
1194
+ }
1195
+
1196
+ let actionsHtml = '';
1197
+ // Кнопка "Ответить" доступна всегда
1198
+ actionsHtml += `<button class="btn" onclick="startReply('${u.username}', '${m.content.replace(/'/g, "\\'").replace(/"/g, '&quot;')}')">Ответить</button>`;
1199
+
1200
+ // Кнопка "Ред." только для своих не-опросов
1201
+ if (m.user_id === state.user.id && !m.content.startsWith('[POLL] ')) {
1202
+ actionsHtml += `<button class="btn" onclick="startEdit(${m.id}, '${m.content.replace(/'/g, "\\'").replace(/"/g, '&quot;')}')">Ред.</button>`;
1203
+ }
1204
+
1205
+ // Кнопка "Удал." для своих или для админа
1206
+ if (m.user_id === state.user.id || state.user.role === 'admin') {
1207
+ actionsHtml += `<button class="btn" onclick="deleteMsg(${m.id})">Удал.</button>`;
1208
+ }
1209
+
1210
+ actionsDiv.innerHTML = actionsHtml;
1211
+ }
1212
+
1213
  function renderPollHTML(pId) {
1214
+ const container = document.getElementById(`poll-container-${pId}`);
1215
+ if (!container || !state.polls[pId]) return;
1216
+ const poll = state.polls[pId];
1217
+
1218
+ let html = `<div class="poll-container"><b>📊 ${poll.q}</b>`;
1219
+ poll.opts.forEach((opt, idx) => {
1220
+ let count = Object.values(poll.votes).filter(v => v === idx).length;
1221
+ let activeVote = poll.votes[state.user.id] === idx ? 'style="font-weight:bold; color:#0f2c4c;"' : '';
1222
+ html += `<div class="poll-opt">
1223
+ <button class="btn" onclick="votePoll(${pId}, ${idx})">${opt}</button>
1224
+ <span ${activeVote}>Голосов: ${count}</span>
1225
+ </div>`;
 
 
 
 
 
 
 
 
1226
  });
1227
+ html += `</div>`;
1228
  container.innerHTML = html;
1229
  }
1230
 
1231
+ async function votePoll(msgId, optIdx) {
1232
+ if(!state.user || !state.activeChannel) return;
1233
  try {
1234
  await api('messages', 'POST', {
1235
  channel_id: state.activeChannel,
1236
  user_id: state.user.id,
1237
+ content: `[VOTE] ${msgId} ${optIdx}`
1238
  });
1239
+ await fetchMessages();
1240
  } catch(e) { alert("Ошибка голосования: " + e.message); }
1241
  }
1242
 
1243
  function handleEnter(e) {
1244
+ if (e.key === 'Enter') {
1245
+ e.preventDefault();
1246
+ sendMessage();
1247
+ }
1248
  }
1249
 
1250
  async function sendMessage() {
 
1254
 
1255
  input.disabled = true;
1256
  try {
 
1257
  const pollMatch = text.match(/^!опрос\s+(.+)/i);
1258
  if (pollMatch) {
1259
+ const parts = pollMatch[1].split(/\s+/);
1260
+ if (parts.length >= 3) {
1261
+ text = `[POLL] ${JSON.stringify(parts)}`;
1262
+ } else {
1263
+ alert("Синтаксис: !опрос Название Вариант1 Вариант2");
 
 
 
 
 
1264
  input.disabled = false;
1265
  return;
1266
  }
 
1284
  }
1285
 
1286
  input.value = '';
1287
+ await fetchMessages();
1288
  } catch(e) {
1289
  alert("Не удалось отправить: " + e.message);
1290
  } finally {
 
1293
  }
1294
  }
1295
 
1296
+ let tickCounter = 0;
1297
+ function appTick() {
1298
+ fetchMessages();
1299
+
1300
+ tickCounter++;
1301
+ if (tickCounter % 5 === 0) {
1302
+ loadChannels();
1303
+ fetchAllUsers();
1304
+ }
1305
+ }
1306
+
1307
+ window.onload = () => {
1308
+ initResizers();
1309
+ loadRecentServers();
1310
+ };
1311
+
1312
  </script>
1313
  </body>
1314
  </html>