sldshr commited on
Commit
8499360
·
verified ·
1 Parent(s): 6fbf5a5

Update index.html

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