Spaces:
Running

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

Update index.html

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