sldshr commited on
Commit
5aee7f0
·
verified ·
1 Parent(s): 66d5367

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +176 -106
index.html CHANGED
@@ -171,7 +171,7 @@
171
 
172
  .sidebar {
173
  width: 200px;
174
- min-width: 160px; /* Исправление багов со сжатием интерфейса */
175
  flex-shrink: 0;
176
  display: flex;
177
  flex-direction: column;
@@ -222,7 +222,17 @@
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; }
@@ -235,20 +245,29 @@
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 {
@@ -302,7 +321,6 @@
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; }
@@ -330,7 +348,7 @@
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;
@@ -369,15 +387,9 @@
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>
@@ -389,7 +401,6 @@
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>
@@ -404,11 +415,16 @@
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
 
@@ -435,7 +451,6 @@
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>
@@ -452,7 +467,6 @@
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">
@@ -618,6 +632,17 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
618
  </div>
619
  </div>
620
 
 
 
 
 
 
 
 
 
 
 
 
621
  <script>
622
  // --- 1. Логика перетаскивания окон ---
623
  function makeDraggable(el) {
@@ -660,7 +685,6 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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";
@@ -683,7 +707,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');
@@ -693,7 +717,6 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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);
@@ -703,7 +726,6 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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);
@@ -719,14 +741,15 @@ 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
 
@@ -747,7 +770,6 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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) {
@@ -770,9 +792,9 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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
  }
@@ -787,16 +809,12 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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');
@@ -815,7 +833,6 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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];
@@ -839,7 +856,6 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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
 
@@ -859,11 +875,9 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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
  }
@@ -874,6 +888,8 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
874
  state.channels = [];
875
  state.usersCache = {};
876
  state.editingId = null;
 
 
877
  if(state.polling) clearInterval(state.polling);
878
 
879
  document.getElementById('user-status').innerText = 'Не подключен';
@@ -904,7 +920,6 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
904
  if (chans) {
905
  state.channels = chans;
906
  renderChannels();
907
- // Заходим в первый канал по умолчанию
908
  if (chans.length > 0 && !state.activeChannel) {
909
  joinChannel(chans[0].id);
910
  }
@@ -970,7 +985,7 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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>`;
@@ -978,14 +993,13 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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) {}
@@ -1013,7 +1027,7 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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
 
@@ -1032,17 +1046,88 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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 +1135,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,7 +1146,6 @@ 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]);
@@ -1070,90 +1153,78 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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
  }
@@ -1181,7 +1252,6 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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;
@@ -1203,13 +1273,12 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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
 
@@ -1225,10 +1294,8 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
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+/);
@@ -1241,19 +1308,25 @@ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);</pre>
1241
  }
1242
  }
1243
 
 
 
 
 
 
1244
  if (state.editingId) {
1245
- await api('messages', 'PATCH', { content: text }, `id=eq.${state.editingId}`);
1246
- state.editingId = null;
1247
  } else {
1248
  await api('messages', 'POST', {
1249
  channel_id: state.activeChannel,
1250
  user_id: state.user.id,
1251
- content: text
1252
  });
 
1253
  }
1254
 
1255
  input.value = '';
1256
- await fetchMessages(); // Сразу запрашиваем обнову
1257
  } catch(e) {
1258
  alert("Не удалось отправить: " + e.message);
1259
  } finally {
@@ -1262,20 +1335,17 @@ 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();
 
171
 
172
  .sidebar {
173
  width: 200px;
174
+ min-width: 160px;
175
  flex-shrink: 0;
176
  display: flex;
177
  flex-direction: column;
 
222
  color: white;
223
  }
224
 
225
+ .msg {
226
+ font-family: Verdana, sans-serif;
227
+ font-size: 12px;
228
+ cursor: pointer;
229
+ border-radius: 3px;
230
+ }
231
+
232
+ .msg:hover {
233
+ background-color: rgba(0,0,0,0.03);
234
+ }
235
+
236
  .msg .time { color: #888; font-size: 10px; margin-right: 5px; }
237
  .msg .author { font-weight: bold; color: #1e5799; margin-right: 5px; }
238
  .msg.system .author { color: #cc3333; }
 
245
  max-width: 100%;
246
  }
247
 
248
+ .quote-block {
249
+ border-left: 3px solid var(--menubar-bot);
250
+ background: #f0f4f8;
251
+ padding: 5px 8px;
252
+ margin: 3px 0 5px 0;
253
+ border-radius: 0 3px 3px 0;
254
+ font-size: 11px;
255
+ color: #555;
256
  }
257
 
258
+ .quote-block .q-author { font-weight: bold; color: var(--menubar-bot); }
259
+ .quote-block .q-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }
 
 
 
260
 
261
+ .action-banner {
262
+ background: #e4eff8;
263
+ border-top: 1px solid var(--border-color);
264
+ padding: 5px 10px;
265
+ display: flex;
266
+ justify-content: space-between;
267
+ align-items: center;
268
+ font-weight: bold;
269
+ font-size: 11px;
270
+ color: var(--text-dark);
271
  }
272
 
273
  .category-header {
 
321
  .chat-area { display: none; border: none; height: 100%; }
322
  .mobile-tabs { display: flex; }
323
 
 
324
  .workspace[data-tab="channels"] .sidebar-left { display: flex; }
325
  .workspace[data-tab="chat"] .chat-area { display: flex; }
326
  .workspace[data-tab="users"] .sidebar-right { display: flex; }
 
348
 
349
  .tabs-header {
350
  display: flex;
351
+ flex-wrap: wrap;
352
  background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 100%);
353
  border-bottom: 1px solid var(--border-color);
354
  padding: 2px 2px 0 2px;
 
387
  <body>
388
 
389
  <div class="menubar">
390
+ <button class="btn" onclick="openWindow('connect-window')">Подключиться</button>
391
+ <button class="btn hidden" id="btn-disconnect" onclick="disconnect()">Отключиться</button>
392
+ <button class="btn" onclick="openWindow('docx-window')">DOCX / FAQ</button>
 
 
 
 
 
 
393
  <div style="flex:1"></div>
394
  <div id="user-status" style="color: white; line-height: 24px; text-shadow: 1px 1px 1px #000; font-weight: bold;">Не подключен</div>
395
  </div>
 
401
  <div id="channels-list" style="overflow-y: auto; flex: 1;">
402
  <div style="padding: 10px; color: #888;">Подключитесь для загрузки...</div>
403
  </div>
 
404
  <div style="padding: 5px; border-top: 1px solid var(--border-color); background: #f4f7f9; display: flex; gap:4px; flex-shrink: 0;">
405
  <input type="text" id="new-channel-name" placeholder="Имя канала" style="flex: 1; min-width: 50px;">
406
  <button class="btn" onclick="createChannel()" style="flex-shrink: 0;">+</button>
 
415
  <div class="chat-messages" id="messages-list">
416
  <div style="color: #999; text-align: center; margin-top: 20px;">Ожидание подключения к серверу...</div>
417
  </div>
418
+
419
+ <!-- Баннер действия (ответ/редактирование) -->
420
+ <div id="action-banner" class="action-banner hidden">
421
+ <span id="action-banner-text">Действие...</span>
422
+ <button class="btn" style="padding: 1px 5px; background: #cc3333; color: white; border:none;" onclick="cancelAction()">X</button>
423
+ </div>
424
+
425
  <div class="chat-input-area">
426
  <input type="text" id="msg-input" placeholder="Сообщение или команда (например, !опрос Вопрос Ответ1 Ответ2)" onkeydown="handleEnter(event)">
427
+ <button class="btn" onclick="sendMessage()">Отправить</button>
 
 
428
  </div>
429
  </div>
430
 
 
451
  <div class="window-close" onclick="closeWindow('connect-window')">X</div>
452
  </div>
453
 
 
454
  <div class="window-body" id="connect-step-1">
455
  <div style="font-size: 11px; color: #555; margin-bottom: 2px;">Последние серверы:</div>
456
  <div class="recent-servers" id="recent-servers-list"></div>
 
467
  <div id="connect-error" style="color: red; font-size: 11px; margin-top: 5px;"></div>
468
  </div>
469
 
 
470
  <div class="window-body hidden" id="connect-step-2">
471
  <div style="color: green; font-size: 11px; margin-bottom: 10px;">✅ Сервер доступен!</div>
472
  <div class="input-group">
 
632
  </div>
633
  </div>
634
 
635
+ <!-- Модальное окно действий над сообщением -->
636
+ <div id="msg-action-window" class="window" style="top: 200px; left: 50%; transform: translateX(-50%); width: 220px; z-index: 1005;">
637
+ <div class="window-header">
638
+ <span>⚙️ Действие</span>
639
+ <div class="window-close" onclick="closeWindow('msg-action-window')">X</div>
640
+ </div>
641
+ <div class="window-body" id="msg-action-body" style="gap: 5px;">
642
+ <!-- Кнопки добавляются через JS -->
643
+ </div>
644
+ </div>
645
+
646
  <script>
647
  // --- 1. Логика перетаскивания окон ---
648
  function makeDraggable(el) {
 
685
  function openWindow(id) {
686
  const win = document.getElementById(id);
687
  win.classList.add('active');
 
688
  if(win.style.top === "100px") {
689
  win.style.top = (window.innerHeight / 2 - win.offsetHeight / 2) + "px";
690
  win.style.left = (window.innerWidth / 2 - win.offsetWidth / 2) + "px";
 
707
  if(btn) btn.classList.add('active');
708
  }
709
 
710
+ // --- Логика ресайзеров ---
711
  function initResizers() {
712
  const resLeft = document.getElementById('resizer-left');
713
  const resRight = document.getElementById('resizer-right');
 
717
  resLeft.addEventListener('mousedown', (e) => {
718
  e.preventDefault();
719
  document.body.style.cursor = 'col-resize';
 
720
  const onMouseMove = (ev) => { pLeft.style.width = Math.max(160, Math.min(ev.clientX, 400)) + 'px'; };
721
  const onMouseUp = () => { document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); document.body.style.cursor = 'default'; };
722
  document.addEventListener('mousemove', onMouseMove);
 
726
  resRight.addEventListener('mousedown', (e) => {
727
  e.preventDefault();
728
  document.body.style.cursor = 'col-resize';
 
729
  const onMouseMove = (ev) => { pRight.style.width = Math.max(160, Math.min(document.body.clientWidth - ev.clientX, 400)) + 'px'; };
730
  const onMouseUp = () => { document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); document.body.style.cursor = 'default'; };
731
  document.addEventListener('mousemove', onMouseMove);
 
741
  channels: [],
742
  activeChannel: null,
743
  usersCache: {},
744
+ polls: {},
745
  lastMsgId: 0,
746
  polling: null,
747
  editingId: null,
748
+ replyingToName: null,
749
+ replyingToSnippet: null,
750
  forwardMsgId: null
751
  };
752
 
 
753
  async function api(table, method = 'GET', body = null, query = '') {
754
  if (!state.url || !state.key) return null;
755
 
 
770
  const errText = await res.text();
771
  throw new Error(errText || `HTTP ${res.status}`);
772
  }
 
773
  if (method === 'DELETE' || res.status === 204) return true;
774
  return await res.json();
775
  } catch (e) {
 
792
 
793
  function saveRecentServer(url, key) {
794
  let list = JSON.parse(localStorage.getItem('webclient_recent') || '[]');
795
+ list = list.filter(s => s.url !== url);
796
  list.unshift({url, key});
797
+ if(list.length > 5) list.pop();
798
  localStorage.setItem('webclient_recent', JSON.stringify(list));
799
  loadRecentServers();
800
  }
 
809
  return;
810
  }
811
 
 
812
  state.url = urlInput.endsWith('/') ? urlInput.slice(0, -1) : urlInput;
813
  state.key = keyInput;
814
  errDiv.innerText = "Проверка...";
815
 
816
  try {
 
817
  await api('channels', 'GET', null, 'select=id&limit=1');
 
 
818
  saveRecentServer(state.url, state.key);
819
  document.getElementById('connect-step-1').classList.add('hidden');
820
  document.getElementById('connect-step-2').classList.remove('hidden');
 
833
  if (!u || !p) return err.innerText = "Введите логин и пароль";
834
 
835
  try {
 
836
  const users = await api('users', 'GET', null, `username=eq.${encodeURIComponent(u)}&password=eq.${encodeURIComponent(p)}`);
837
  if (users && users.length > 0) {
838
  state.user = users[0];
 
856
  if (!u || !p) return err.innerText = "Введите логин и пароль";
857
 
858
  try {
 
859
  const exist = await api('users', 'GET', null, `username=eq.${encodeURIComponent(u)}`);
860
  if (exist && exist.length > 0) throw new Error("Ник уже занят");
861
 
 
875
  document.getElementById('messages-list').innerHTML = `<div class="msg system"><span class="author">***</span> SYSTEM: Соединение установлено. Авторизация успешна.</div>`;
876
  document.getElementById('btn-disconnect').classList.remove('hidden');
877
 
 
878
  fetchAllUsers();
879
  loadChannels();
880
 
 
881
  if(state.polling) clearInterval(state.polling);
882
  state.polling = setInterval(appTick, 2000);
883
  }
 
888
  state.channels = [];
889
  state.usersCache = {};
890
  state.editingId = null;
891
+ state.replyingToName = null;
892
+ state.replyingToSnippet = null;
893
  if(state.polling) clearInterval(state.polling);
894
 
895
  document.getElementById('user-status').innerText = 'Не подключен';
 
920
  if (chans) {
921
  state.channels = chans;
922
  renderChannels();
 
923
  if (chans.length > 0 && !state.activeChannel) {
924
  joinChannel(chans[0].id);
925
  }
 
985
  async function joinChannel(id) {
986
  state.activeChannel = id;
987
  state.lastMsgId = 0;
988
+ state.polls = {};
989
  const c = state.channels.find(x => x.id === id);
990
  document.getElementById('chat-title').innerText = `Чат :: #${c ? c.name : 'Unknown'}`;
991
  document.getElementById('messages-list').innerHTML = `<div class="msg system"><span class="author">***</span> SYSTEM: Вы вошли в канал #${c ? c.name : 'Unknown'}</div>`;
 
993
  await fetchMessages();
994
  }
995
 
 
996
  async function getUser(id) {
997
  if (state.usersCache[id]) return state.usersCache[id];
998
  try {
999
  const u = await api('users', 'GET', null, `id=eq.${id}&select=id,username,role`);
1000
  if (u && u.length > 0) {
1001
  state.usersCache[id] = u[0];
1002
+ renderUsersList();
1003
  return u[0];
1004
  }
1005
  } catch(e) {}
 
1027
  try {
1028
  await api('users', 'PATCH', { role: 'banned' }, `id=eq.${userId}`);
1029
  alert("Пользователь забанен!");
1030
+ delete state.usersCache[userId];
1031
  } catch(e) { alert("Ошибка: " + e.message); }
1032
  }
1033
 
 
1046
  }
1047
 
1048
  function formatContent(text) {
 
1049
  return escapeHTML(text);
1050
  }
1051
 
1052
+ // --- NEW: Логика взаимодействия с сообщениями (долгое нажатие/ПКМ) ---
1053
+ function makeLongPressable(el, msgData) {
1054
+ let timer;
1055
+ const handler = (e) => {
1056
+ e.preventDefault();
1057
+ showMsgActionModal(msgData);
1058
+ };
1059
+
1060
+ const start = (e) => {
1061
+ if (e.type === 'mousedown' && e.button !== 0) return;
1062
+ timer = setTimeout(() => { timer = null; handler(e); }, 400);
1063
+ };
1064
+ const cancel = () => { if(timer) { clearTimeout(timer); timer = null; } };
1065
+
1066
+ el.addEventListener('mousedown', start);
1067
+ el.addEventListener('touchstart', start, {passive: true});
1068
+ el.addEventListener('mouseup', cancel);
1069
+ el.addEventListener('touchend', cancel);
1070
+ el.addEventListener('mousemove', cancel);
1071
+ el.addEventListener('touchmove', cancel);
1072
+ el.addEventListener('contextmenu', handler);
1073
+ }
1074
+
1075
+ function showMsgActionModal(msg) {
1076
+ const isOwn = msg.user_id === state.user.id;
1077
+ const isAdmin = state.user.role === 'admin';
1078
+
1079
+ const body = document.getElementById('msg-action-body');
1080
+ let safeContent = msg.content.replace(/'/g, "\\'").replace(/"/g, '&quot;');
1081
+
1082
+ let html = `<button class="btn" onclick="startReply('${msg.username}', '${safeContent}'); closeWindow('msg-action-window')">Ответить</button>`;
1083
+ html += `<button class="btn" onclick="openForward(${msg.id}); closeWindow('msg-action-window')">Переслать</button>`;
1084
+ if (isOwn && !msg.content.startsWith('[POLL]')) {
1085
+ html += `<button class="btn" onclick="startEdit(${msg.id}, '${safeContent}'); closeWindow('msg-action-window')">Редактировать</button>`;
1086
+ }
1087
+ if (isOwn || isAdmin) {
1088
+ html += `<button class="btn" onclick="deleteMsg(${msg.id}); closeWindow('msg-action-window')">Удалить</button>`;
1089
+ }
1090
+
1091
+ body.innerHTML = html;
1092
+ openWindow('msg-action-window');
1093
+ }
1094
+
1095
+ function startReply(username, rawContent) {
1096
+ cancelAction();
1097
+ state.replyingToName = username;
1098
+ let cleanText = rawContent.replace(/\[R:.*?\](.*?)\[\/R\]/g, "").trim();
1099
+ state.replyingToSnippet = cleanText.length > 40 ? cleanText.substring(0, 40) + '...' : cleanText;
1100
+
1101
+ document.getElementById('action-banner-text').innerText = `Отвечая ${username}: ${state.replyingToSnippet}`;
1102
+ document.getElementById('action-banner').classList.remove('hidden');
1103
+ document.getElementById('msg-input').focus();
1104
+ }
1105
+
1106
+ function startEdit(id, rawContent) {
1107
+ cancelAction();
1108
+ state.editingId = id;
1109
+ document.getElementById('action-banner-text').innerText = `Редактирование сообщения`;
1110
+ document.getElementById('action-banner').classList.remove('hidden');
1111
+
1112
+ const input = document.getElementById('msg-input');
1113
+ input.value = rawContent;
1114
+ input.focus();
1115
+ }
1116
+
1117
+ function cancelAction() {
1118
+ state.editingId = null;
1119
+ state.replyingToName = null;
1120
+ state.replyingToSnippet = null;
1121
+ document.getElementById('action-banner').classList.add('hidden');
1122
+ document.getElementById('msg-input').value = '';
1123
+ }
1124
+
1125
  async function fetchMessages() {
1126
  if (!state.activeChannel || !state.user) return;
1127
  try {
 
1128
  const msgs = await api('messages', 'GET', null, `channel_id=eq.${state.activeChannel}&order=id.desc&limit=50`);
1129
  if (!msgs) return;
1130
+ msgs.reverse();
1131
 
1132
  const ml = document.getElementById('messages-list');
1133
  const isAtBottom = (ml.scrollHeight - ml.scrollTop - ml.clientHeight) < 20;
 
1135
  const currentMsgIds = new Set(Array.from(ml.querySelectorAll('.msg[data-id]')).map(el => parseInt(el.dataset.id)));
1136
  const fetchedMsgIds = new Set(msgs.map(m => m.id));
1137
 
 
1138
  currentMsgIds.forEach(id => {
1139
  if (!fetchedMsgIds.has(id)) {
1140
  const el = document.getElementById('msg-' + id);
 
1146
  const u = await getUser(m.user_id);
1147
  const time = new Date(m.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', second:'2-digit'});
1148
 
 
1149
  if (m.content.startsWith('[VOTE] ')) {
1150
  const parts = m.content.split(' ');
1151
  const pId = parseInt(parts[1]);
 
1153
  if (!state.polls[pId]) state.polls[pId] = { q: '', opts: [], votes: {} };
1154
  state.polls[pId].votes[m.user_id] = optIdx;
1155
 
1156
+ renderPollHTML(pId);
1157
  continue;
1158
  }
1159
 
1160
  let el = document.getElementById('msg-' + m.id);
1161
 
 
1162
  if (el) {
1163
  if (el.dataset.raw !== m.content) {
1164
  el.dataset.raw = m.content;
1165
  if (!m.content.startsWith('[POLL] ')) {
1166
+ let displayContent = m.content;
1167
+ let quoteHTML = '';
1168
+ const match = m.content.match(/^\[R:(.+?)\](.*?)\[\/R\](.*)/s);
1169
+ if (match) {
1170
+ const rName = match[1];
1171
+ const rSnippet = match[2];
1172
+ displayContent = match[3];
1173
+ quoteHTML = `<div class="quote-block"><div class="q-author">Ответ ${escapeHTML(rName)}:</div><div class="q-text">${escapeHTML(rSnippet)}</div></div>`;
1174
+ }
1175
+ el.querySelector('.content').innerHTML = quoteHTML + formatContent(displayContent);
1176
  }
1177
  }
1178
  continue;
1179
  }
1180
 
 
1181
  const div = document.createElement('div');
1182
  div.id = 'msg-' + m.id;
1183
  div.dataset.id = m.id;
1184
  div.dataset.raw = m.content;
1185
 
 
1186
  const isPing = m.content.includes('@' + state.user.username);
1187
  div.className = `msg ${isPing ? 'pinged' : ''}`;
1188
 
1189
+ makeLongPressable(div, { id: m.id, user_id: m.user_id, username: u.username, content: m.content });
 
 
 
 
 
 
 
 
 
 
 
1190
 
 
1191
  if (m.content.startsWith('[POLL] ')) {
1192
  try {
1193
  const pData = JSON.parse(m.content.substring(7));
1194
  const pId = m.id;
1195
  if(!state.polls[pId]) state.polls[pId] = { q: pData[0], opts: pData.slice(1), votes: {} };
1196
 
1197
+ div.innerHTML = `<span class="time">[${time}]</span> <span class="author">&lt;${u.role==='admin'?'@':''}${u.username}&gt;</span> <div id="poll-container-${pId}"></div>`;
1198
  ml.appendChild(div);
1199
  renderPollHTML(pId);
1200
  } catch(e) {}
1201
  } else {
1202
+ let displayContent = m.content;
1203
+ let quoteHTML = '';
1204
+ const match = m.content.match(/^\[R:(.+?)\](.*?)\[\/R\](.*)/s);
1205
+ if (match) {
1206
+ const rName = match[1];
1207
+ const rSnippet = match[2];
1208
+ displayContent = match[3];
1209
+ quoteHTML = `<div class="quote-block"><div class="q-author">Ответ ${escapeHTML(rName)}:</div><div class="q-text">${escapeHTML(rSnippet)}</div></div>`;
1210
+ }
1211
+ div.innerHTML = `<span class="time">[${time}]</span> <span class="author">&lt;${u.role==='admin'?'@':''}${u.username}&gt;</span> <span class="content">${quoteHTML}${formatContent(displayContent)}</span>`;
1212
  ml.appendChild(div);
1213
  }
1214
  }
 
1215
  if (isAtBottom) {
1216
  ml.scrollTop = ml.scrollHeight;
1217
  }
1218
  } catch(e) { console.error("Msg fetch err", e); }
1219
  }
1220
 
1221
+ // Старые функции replyMsg и editMsg удалены, заменены новым модальным окном
 
 
 
 
 
 
 
 
 
 
 
 
 
1222
 
1223
  async function deleteMsg(id) {
1224
  if(confirm("Удалить это сообщение?")) {
1225
  try {
1226
  await api('messages', 'DELETE', null, `id=eq.${id}`);
1227
+ fetchMessages();
1228
  } catch(e) { alert("Ошибка: " + e.message); }
1229
  }
1230
  }
 
1252
  } catch(e) {}
1253
  }
1254
 
 
1255
  function renderPollHTML(pId) {
1256
  const container = document.getElementById(`poll-container-${pId}`);
1257
  if (!container || !state.polls[pId]) return;
 
1273
  async function votePoll(msgId, optIdx) {
1274
  if(!state.user || !state.activeChannel) return;
1275
  try {
 
1276
  await api('messages', 'POST', {
1277
  channel_id: state.activeChannel,
1278
  user_id: state.user.id,
1279
  content: `[VOTE] ${msgId} ${optIdx}`
1280
  });
1281
+ await fetchMessages();
1282
  } catch(e) { alert("Ошибка голосования: " + e.message); }
1283
  }
1284
 
 
1294
  let text = input.value.trim();
1295
  if (!text || !state.user || !state.activeChannel) return;
1296
 
 
1297
  input.disabled = true;
1298
  try {
 
1299
  const pollMatch = text.match(/^!опрос\s+(.+)/i);
1300
  if (pollMatch) {
1301
  const parts = pollMatch[1].split(/\s+/);
 
1308
  }
1309
  }
1310
 
1311
+ let finalContent = text;
1312
+ if (state.replyingToName && !state.editingId) {
1313
+ finalContent = `[R:${state.replyingToName}]${state.replyingToSnippet}[/R]${text}`;
1314
+ }
1315
+
1316
  if (state.editingId) {
1317
+ await api('messages', 'PATCH', { content: finalContent }, `id=eq.${state.editingId}`);
1318
+ cancelAction();
1319
  } else {
1320
  await api('messages', 'POST', {
1321
  channel_id: state.activeChannel,
1322
  user_id: state.user.id,
1323
+ content: finalContent
1324
  });
1325
+ cancelAction();
1326
  }
1327
 
1328
  input.value = '';
1329
+ await fetchMessages();
1330
  } catch(e) {
1331
  alert("Не удалось отправить: " + e.message);
1332
  } finally {
 
1335
  }
1336
  }
1337
 
 
1338
  let tickCounter = 0;
1339
  function appTick() {
1340
  fetchMessages();
1341
 
1342
  tickCounter++;
 
1343
  if (tickCounter % 5 === 0) {
1344
  loadChannels();
1345
  fetchAllUsers();
1346
  }
1347
  }
1348
 
 
1349
  window.onload = () => {
1350
  initResizers();
1351
  loadRecentServers();