sldshr commited on
Commit
f8beaa2
·
verified ·
1 Parent(s): f908100

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +602 -376
index.html CHANGED
@@ -194,28 +194,70 @@
194
  flex-direction: column;
195
  align-items: center;
196
  justify-content: center;
197
- text-align: center;
198
  padding: 40px 20px;
199
  flex: 1;
 
 
200
  }
201
  .landing-hero {
202
- max-width: 800px;
203
  background: var(--bg-card);
204
- padding: 40px;
205
- border-radius: 4px;
206
  box-shadow: var(--shadow-card);
 
 
 
207
  }
208
  .landing-title {
209
- font-size: 36px;
210
  font-weight: 700;
211
- margin: 20px 0;
212
  color: var(--text-primary);
 
213
  }
214
  .landing-desc {
215
- font-size: 17px;
216
  color: var(--text-secondary);
217
  line-height: 1.6;
218
- margin-bottom: 30px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  }
220
 
221
  /* Документация */
@@ -231,19 +273,26 @@
231
  overflow: hidden;
232
  }
233
  .docs-sidebar {
234
- width: 280px;
235
  border-right: 1px solid var(--border-color);
236
  background: var(--bg-card);
237
  padding: 20px 0;
 
238
  }
239
  .docs-menu-item {
240
- padding: 12px 24px;
241
- font-size: 14px;
242
  font-weight: 500;
243
  color: var(--text-primary);
244
  cursor: pointer;
245
  border-left: 3px solid transparent;
246
  display: block;
 
 
 
 
 
 
247
  }
248
  .docs-menu-item:hover, .docs-menu-item.active {
249
  background: var(--quote-bg);
@@ -256,28 +305,41 @@
256
  overflow-y: auto;
257
  max-height: calc(100vh - 120px);
258
  }
259
- .docs-content h1 { font-size: 28px; margin-bottom: 15px; border-bottom: 2px solid var(--border-color); padding-bottom: 10px; }
260
- .docs-content h2 { font-size: 20px; color: var(--brand-color); margin: 25px 0 10px 0; }
261
- .docs-content p { font-size: 15px; color: var(--text-secondary); line-height: 1.6; margin-bottom: 15px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
- code.inline {
264
- background: var(--quote-bg);
265
- color: var(--brand-color);
266
- padding: 2px 6px;
267
- border-radius: 3px;
268
- font-family: monospace;
269
- font-size: 13px;
 
270
  }
271
- pre.code-block {
272
- background: #1e1e1e;
273
- color: #d4d4d4;
274
- padding: 16px;
275
  border-radius: 4px;
276
- font-family: monospace;
277
- font-size: 13px;
278
- overflow-x: auto;
279
- margin: 15px 0;
280
- line-height: 1.5;
281
  border: 1px solid var(--border-color);
282
  }
283
 
@@ -606,15 +668,32 @@
606
  <div id="screen-landing" class="screen active">
607
  <div class="landing-container">
608
  <div class="landing-hero">
609
- <i class="fa-solid fa-cloud-bolt text-brand" style="font-size: 70px; color: var(--brand-color);"></i>
610
- <h1 class="landing-title">Будущее децентрализованных коммуникаций</h1>
611
  <p class="landing-desc">
612
- ClientLess — легковесный протокол для создания собственных независимых серверов общения.
613
- Полная изоляция данных, поддержку WebSocket в реальном времени, встроенное шифрование и минимальная нагрузка на клиентские устройства.
614
  </p>
615
- <div style="display: flex; gap: 15px; justify-content: center;">
616
- <button onclick="navigate('server')" class="btn-md" style="padding: 12px 28px; font-size: 15px;">Запустить WCL</button>
617
- <button onclick="navigate('docs')" class="btn-md btn-secondary" style="padding: 12px 28px; font-size: 15px;">Документация сервера</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
618
  </div>
619
  </div>
620
  </div>
@@ -624,25 +703,46 @@
624
  <div id="screen-docs" class="screen">
625
  <div class="docs-wrapper">
626
  <div class="docs-sidebar">
627
- <span class="docs-menu-item active" onclick="switchDocSection('overview', this)">1. Обзор архитектуры</span>
628
- <span class="docs-menu-item" onclick="switchDocSection('schema', this)">2. Схема БД Supabase (SQL)</span>
629
- <span class="docs-menu-item" onclick="switchDocSection('rls', this)">3. Защита и RLS Политики</span>
630
- <span class="docs-menu-item" onclick="switchDocSection('wss', this)">4. WebSocket API</span>
 
 
 
 
 
 
 
 
 
 
631
  </div>
632
  <div class="docs-content" id="docs-content-container">
633
 
634
- <div id="doc-overview">
635
  <h1>1. Обзор архитектуры ClientLess</h1>
636
- <p>ClientLess спроектирован по принципу <strong>Zero-Trust Server Frontend Interface</strong>. Наш веб-клиент не привязан к единому центральному бэкенду. Каждый администратор разворачивает собственный узел (Node) на базе PostgreSQL / Supabase.</p>
637
- <p>Клиент осуществляет подключение с помощью двух ключей: <code class="inline">Project URL</code> и публичного API-ключа <code class="inline">Anon Key</code>.</p>
 
 
 
 
 
 
 
 
 
 
638
  </div>
639
 
640
- <div id="doc-schema" class="hidden">
641
- <h1>2. Полный SQL-скрипт развертывания Supabase</h1>
642
- <p>Выполните этот код в SQL Editor вашего Supabase проекта, чтобы создать реальную рабочую базу.</p>
643
 
 
644
  <pre class="code-block"><code>-- =====================================================
645
- -- ClientLess Working Database Schema
646
  -- =====================================================
647
 
648
  -- 1. Таблица Пользователей
@@ -665,64 +765,61 @@ CREATE TABLE public.messages (
665
  channel_id UUID REFERENCES public.channels(id) ON DELETE CASCADE NOT NULL,
666
  user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL,
667
  content TEXT NOT NULL,
 
668
  reply_to_id UUID REFERENCES public.messages(id) ON DELETE SET NULL,
669
  created_at TIMESTAMPTZ DEFAULT NOW()
670
- );
671
 
672
- -- Включаем Realtime для таблиц
 
673
  ALTER PUBLICATION supabase_realtime ADD TABLE public.users;
674
  ALTER PUBLICATION supabase_realtime ADD TABLE public.channels;
675
  ALTER PUBLICATION supabase_realtime ADD TABLE public.messages;
676
 
677
- -- Создаем базовый канал
678
- INSERT INTO public.channels (name) VALUES ('general');</code></pre>
679
  </div>
680
 
681
- <div id="doc-rls" class="hidden">
682
- <h1>3. Строгая настройка Row Level Security (RLS)</h1>
683
- <p>Безопасность данных гарантируется на уровне СУБД PostgreSQL. Ни один пользователь не сможет читать личные сообщения чужих приватных каналов.</p>
684
 
685
- <pre class="code-block"><code>-- Включение RLS для всех таблиц
686
- ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
 
687
  ALTER TABLE public.channels ENABLE ROW LEVEL SECURITY;
688
- ALTER TABLE public.channel_members ENABLE ROW LEVEL SECURITY;
689
  ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
690
 
691
- -- Политики чтения профилей
692
- CREATE POLICY "Profiles viewable by authenticated"
693
- ON public.profiles FOR SELECT USING (auth.role() = 'authenticated');
694
-
695
- -- Политики доступа к сообщениям
696
- CREATE POLICY "Messages readable by channel members"
697
- ON public.messages FOR SELECT
698
- USING (EXISTS (
699
- SELECT 1 FROM public.channels c
700
- LEFT JOIN public.channel_members cm ON c.id = cm.channel_id
701
- WHERE c.id = messages.channel_id
702
- AND (c.type = 'public' OR cm.user_id = auth.uid())
703
- ));
704
-
705
- CREATE POLICY "Insert messages allowed for channel members"
706
- ON public.messages FOR INSERT
707
- WITH CHECK (
708
- auth.uid() = author_id AND EXISTS (
709
- SELECT 1 FROM public.channels c
710
- LEFT JOIN public.channel_members cm ON c.id = cm.channel_id
711
- WHERE c.id = messages.channel_id
712
- AND (c.type = 'public' OR cm.user_id = auth.uid())
713
- )
714
- );
715
-
716
- CREATE POLICY "Users can edit own messages"
717
- ON public.messages FOR UPDATE USING (auth.uid() = author_id);
718
-
719
- CREATE POLICY "Users can delete own messages"
720
- ON public.messages FOR DELETE USING (auth.uid() = author_id);</code></pre>
721
  </div>
722
 
723
- <div id="doc-wss" class="hidden">
724
- <h1>4. Реальный WebSocket протокол</h1>
725
- <p>Обмен сообщениями происходит через протокол Realtime Broadcast over WebSockets. Клиент подписывается на топик вида <code class="inline">realtime:public:messages:channel_id=eq.{ID}</code>.</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
726
  </div>
727
 
728
  </div>
@@ -817,9 +914,27 @@ CREATE POLICY "Users can delete own messages"
817
  <button onclick="cancelActionState()" style="background:none; border:none; font-size: 18px; color: var(--text-secondary); cursor:pointer;">&times;</button>
818
  </div>
819
 
 
 
 
 
 
 
 
 
 
 
820
  <div class="chat-input-area">
821
  <div class="chat-input-wrapper">
822
- <input type="text" id="message-input" class="form-input selectable-text" placeholder="Написать сообщение..." onkeypress="handleKeyPress(event)">
 
 
 
 
 
 
 
 
823
  <button onclick="sendMessage()" class="btn-md">
824
  <i class="fa-solid fa-paper-plane"></i>
825
  </button>
@@ -877,6 +992,7 @@ CREATE POLICY "Users can delete own messages"
877
  let usersData = [];
878
 
879
  let realtimeSubscription = null;
 
880
 
881
  // Состояние приложения
882
  let appState = {
@@ -890,300 +1006,356 @@ CREATE POLICY "Users can delete own messages"
890
  let replyTargetMsg = null;
891
  let editingMsgId = null;
892
 
893
- // Переключение тем
894
- function toggleTheme() {
895
- appState.theme = appState.theme === 'light' ? 'dark' : 'light';
896
- document.documentElement.setAttribute('data-theme', appState.theme);
897
-
898
- const iconNav = document.getElementById('theme-icon-nav');
899
- const iconClient = document.getElementById('theme-icon-client');
900
 
901
- if (appState.theme === 'dark') {
902
- if(iconNav) iconNav.className = 'fa-solid fa-sun';
903
- if(iconClient) iconClient.className = 'fa-solid fa-sun';
904
  } else {
905
- if(iconNav) iconNav.className = 'fa-solid fa-moon';
906
- if(iconClient) iconClient.className = 'fa-solid fa-moon';
907
  }
908
- saveSession();
909
  }
910
 
911
- // Запоминание сессии
912
- function saveSession() {
913
- if (appState.username && appState.projectUrl) {
914
- const session = JSON.stringify(appState);
915
- window.name = session;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
916
  }
917
  }
918
 
919
  async function restoreSession() {
920
- try {
921
- if (window.name) {
922
- const saved = JSON.parse(window.name);
923
- if (saved && saved.username && saved.projectUrl) {
924
- appState = saved;
925
- document.getElementById('wcl-username').innerText = appState.username;
926
- document.documentElement.setAttribute('data-theme', appState.theme || 'light');
927
-
928
- // Авто-подключение к БД
929
- supabaseClient = supabase.createClient(appState.projectUrl, appState.anonKey);
930
-
931
- // Получаем пользователя
932
- const { data: user } = await supabaseClient
933
- .from('users')
934
- .select('*')
935
- .eq('username', appState.username)
936
- .single();
937
-
938
- if (user) {
939
- currentUser = user;
940
- await initApp();
941
- navigate('client');
942
- return true;
943
- }
944
  }
945
  }
946
- } catch(e) {
947
- console.error("Session restore error:", e);
948
  }
949
  return false;
950
  }
951
 
952
- function navigate(screenId) {
953
- document.querySelectorAll('.screen').forEach(el => el.classList.remove('active'));
954
- document.getElementById('screen-' + screenId).classList.add('active');
955
-
956
- const marketingNav = document.getElementById('marketing-nav');
957
- if (screenId === 'client') {
958
- marketingNav.style.display = 'none';
959
- } else {
960
- marketingNav.style.display = 'flex';
961
- }
962
- }
963
-
964
- function switchDocSection(sectionId, el) {
965
- document.querySelectorAll('.docs-menu-item').forEach(m => m.classList.remove('active'));
966
- if(el) el.classList.add('active');
967
-
968
- ['overview', 'schema', 'rls', 'wss'].forEach(id => {
969
- const docEl = document.getElementById('doc-' + id);
970
- if (docEl) {
971
- if (id === sectionId) docEl.classList.remove('hidden');
972
- else docEl.classList.add('hidden');
973
- }
974
- });
975
- }
976
-
977
  async function handleServerSubmit(e) {
978
  e.preventDefault();
979
- const errDiv = document.getElementById('server-error');
980
- errDiv.style.display = 'none';
981
  const url = document.getElementById('project-url').value.trim();
982
  const key = document.getElementById('anon-key').value.trim();
983
-
 
 
984
  try {
985
- supabaseClient = supabase.createClient(url, key);
986
- // Проверка соединения - пробуем получить 1 канал
987
- const { error } = await supabaseClient.from('channels').select('id').limit(1);
 
988
  if (error) throw error;
989
-
 
990
  appState.projectUrl = url;
991
  appState.anonKey = key;
992
- document.getElementById('display-node').innerText = url;
 
 
 
993
  navigate('auth');
994
- } catch(err) {
995
- errDiv.innerText = 'Ошибка подключения. Проверьте URL и Key базы данных. ' + (err.message || '');
996
- errDiv.style.display = 'block';
997
  }
998
  }
999
 
1000
  async function handleAuthSubmit(e) {
1001
  e.preventDefault();
1002
- const errDiv = document.getElementById('auth-error');
1003
- errDiv.style.display = 'none';
1004
- const username = document.getElementById('username').value.trim();
1005
- if (!username) return;
 
1006
 
1007
  try {
1008
- // Ищем юзера или создаем нового
1009
- let { data: user, error: searchError } = await supabaseClient
1010
  .from('users')
1011
  .select('*')
1012
- .eq('username', username)
1013
- .single();
1014
-
1015
- if (searchError && searchError.code === 'PGRST116') {
1016
- // Пользователь не найден, создаем
1017
- const { data: newUser, error: insertError } = await supabaseClient
 
 
1018
  .from('users')
1019
- .insert([{ username }])
1020
- .select()
1021
- .single();
1022
- if (insertError) throw insertError;
1023
- user = newUser;
1024
- } else if (searchError) {
1025
- throw searchError;
1026
  }
1027
 
1028
- currentUser = user;
1029
- appState.username = user.username;
1030
- document.getElementById('wcl-username').innerText = user.username;
1031
- saveSession();
1032
- await initApp();
1033
- navigate('client');
1034
  } catch (err) {
1035
- errDiv.innerText = 'Ошибка авторизации: ' + (err.message || err.details || 'Неизвестная ошибка');
1036
- errDiv.style.display = 'block';
1037
  }
1038
  }
1039
 
1040
- function logout() {
1041
- if(realtimeSubscription) realtimeSubscription.unsubscribe();
1042
- appState.username = '';
1043
- appState.projectUrl = '';
1044
- appState.anonKey = '';
1045
- window.name = '';
1046
- currentUser = null;
1047
- supabaseClient = null;
1048
- navigate('landing');
 
 
 
 
 
1049
  }
1050
 
1051
- async function initApp() {
1052
- // Загружаем всех пользователей
1053
- const { data: uData } = await supabaseClient.from('users').select('*');
1054
- if (uData) usersData = uData;
1055
- renderUsersList();
1056
 
1057
- // Загружаем каналы
1058
- const { data: cData } = await supabaseClient.from('channels').select('*').order('created_at', { ascending: true });
1059
- if (cData) channelsData = cData;
 
 
 
 
1060
 
1061
- if (channelsData.length > 0) {
1062
- await switchChannel(channelsData[0].id);
 
 
 
 
 
1063
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1064
 
1065
- // Подписка на Realtime изменения в Supabase
1066
- if (realtimeSubscription) realtimeSubscription.unsubscribe();
1067
- realtimeSubscription = supabaseClient.channel('public-db-changes')
1068
  .on('postgres_changes', { event: '*', schema: 'public', table: 'messages' }, payload => {
1069
  if (payload.eventType === 'INSERT') {
1070
  if (payload.new.channel_id === currentChannelId) {
1071
  messagesData.push(payload.new);
1072
  renderMessages();
1073
  }
1074
- } else if (payload.eventType === 'DELETE') {
1075
- messagesData = messagesData.filter(m => m.id !== payload.old.id);
1076
- renderMessages();
1077
  } else if (payload.eventType === 'UPDATE') {
1078
  const idx = messagesData.findIndex(m => m.id === payload.new.id);
1079
- if(idx !== -1) {
1080
  messagesData[idx] = payload.new;
1081
  renderMessages();
1082
  }
 
 
 
1083
  }
1084
  })
1085
  .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'users' }, payload => {
1086
  usersData.push(payload.new);
1087
- renderUsersList();
1088
- })
1089
- .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'channels' }, payload => {
1090
- channelsData.push(payload.new);
1091
- renderChannelsList();
1092
  })
1093
  .subscribe();
1094
  }
1095
 
1096
- function toggleSidebar(side) {
1097
- const right = document.getElementById('wcl-right-sidebar');
1098
- const overlay = document.getElementById('wcl-overlay');
1099
-
1100
- if (side === 'right') {
1101
- const isOpen = right.classList.contains('open');
1102
- closeSidebars();
1103
- if (!isOpen) { right.classList.add('open'); overlay.classList.add('active'); }
1104
- }
1105
  }
1106
 
1107
- function closeSidebars() {
1108
- document.getElementById('wcl-right-sidebar').classList.remove('open');
1109
- document.getElementById('wcl-overlay').classList.remove('active');
 
1110
  }
1111
 
1112
- async function switchChannel(channelId) {
1113
- currentChannelId = channelId;
1114
- const ch = channelsData.find(c => c.id === channelId);
1115
- if (ch) {
1116
- document.getElementById('current-channel-title').innerText = '#' + ch.name;
1117
- }
1118
-
1119
- cancelActionState();
1120
- closeSidebars();
1121
- renderChannelsList();
1122
-
1123
- // Загрузка сообщений канала
1124
- const { data: mData } = await supabaseClient
1125
- .from('messages')
1126
- .select('*')
1127
- .eq('channel_id', channelId)
1128
- .order('created_at', { ascending: true });
1129
-
1130
- messagesData = mData || [];
1131
- renderMessages();
1132
  }
1133
 
1134
- function renderChannelsList() {
1135
- const container = document.getElementById('channels-list');
1136
- container.innerHTML = '';
 
 
 
 
1137
 
1138
- channelsData.forEach(ch => {
1139
- const item = document.createElement('div');
1140
- item.className = `list-item ${ch.id === currentChannelId ? 'active' : ''}`;
1141
- item.onclick = () => switchChannel(ch.id);
1142
-
1143
- item.innerHTML = `
1144
- <i class="fa-solid fa-hashtag" style="margin-right: 10px;"></i>
1145
- <span style="font-weight: 500;">${escapeHTML(ch.name)}</span>
1146
- `;
1147
- container.appendChild(item);
1148
  });
 
 
 
 
 
1149
  }
1150
 
1151
- function renderUsersList() {
1152
- const container = document.getElementById('users-list');
1153
- container.innerHTML = '';
1154
- document.getElementById('user-count').innerText = usersData.length;
1155
 
1156
- usersData.forEach(u => {
1157
- const item = document.createElement('div');
1158
- item.className = 'list-item';
1159
- item.onclick = () => insertMention(u.username);
1160
-
1161
- const isMe = currentUser && u.id === currentUser.id;
1162
- const displayName = isMe ? `${u.username} (Вы)` : u.username;
 
 
 
1163
 
1164
- item.innerHTML = `
1165
- <span class="status-dot status-online"></span>
1166
- <span style="font-weight: 500;">${escapeHTML(displayName)}</span>
1167
- `;
1168
- container.appendChild(item);
1169
- });
1170
  }
1171
 
1172
- function insertMention(username) {
1173
- const input = document.getElementById('message-input');
1174
- input.value = input.value ? `${input.value} @${username} ` : `@${username} `;
1175
- input.focus();
 
 
 
 
1176
  }
1177
 
1178
- function getUserName(id) {
1179
- const u = usersData.find(x => x.id === id);
1180
- return u ? u.username : 'Unknown';
 
1181
  }
1182
 
1183
- function formatTime(isoStr) {
1184
- if (!isoStr) return '';
1185
- const d = new Date(isoStr);
1186
- return d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1187
  }
1188
 
1189
  function renderMessages() {
@@ -1195,7 +1367,7 @@ CREATE POLICY "Users can delete own messages"
1195
  const isSelf = currentUser && msg.user_id === currentUser.id;
1196
  const authorName = getUserName(msg.user_id);
1197
 
1198
- const isMentioned = currentUser && msg.content.toLowerCase().includes(`@${currentUser.username.toLowerCase()}`);
1199
 
1200
  msgDiv.className = `message ${isSelf ? 'self' : ''} ${isMentioned ? 'mentioned-me' : ''}`;
1201
  msgDiv.id = `msg-${msg.id}`;
@@ -1209,7 +1381,7 @@ CREATE POLICY "Users can delete own messages"
1209
  if (msg.reply_to_id) {
1210
  const replyOriginalMsg = messagesData.find(m => m.id === msg.reply_to_id);
1211
  const replyAuthor = replyOriginalMsg ? getUserName(replyOriginalMsg.user_id) : 'Unknown';
1212
- const replyText = replyOriginalMsg ? replyOriginalMsg.content : 'Удаленное сообщение';
1213
 
1214
  quoteHtml = `
1215
  <div class="message-quote" onclick="scrollToMessage('${msg.reply_to_id}'); event.stopPropagation();">
@@ -1219,9 +1391,15 @@ CREATE POLICY "Users can delete own messages"
1219
  `;
1220
  }
1221
 
 
 
 
 
 
1222
  msgDiv.innerHTML = `
1223
  <div class="message-author">${escapeHTML(authorName)}</div>
1224
  ${quoteHtml}
 
1225
  <div class="selectable-text">${formatMessageText(msg.content)}</div>
1226
  <div class="message-time">${formatTime(msg.created_at)}</div>
1227
  `;
@@ -1232,130 +1410,178 @@ CREATE POLICY "Users can delete own messages"
1232
  chatBox.scrollTop = chatBox.scrollHeight;
1233
  }
1234
 
1235
- function scrollToMessage(targetId) {
1236
- const targetEl = document.getElementById(`msg-${targetId}`);
1237
- if (targetEl) {
1238
- targetEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
1239
- targetEl.classList.remove('flash-blue');
1240
- void targetEl.offsetWidth;
1241
- targetEl.classList.add('flash-blue');
1242
- setTimeout(() => targetEl.classList.remove('flash-blue'), 3000);
1243
- }
1244
- }
1245
-
1246
  async function sendMessage() {
1247
  const input = document.getElementById('message-input');
1248
  const text = input.value.trim();
1249
- if (!text || !currentChannelId || !currentUser) return;
1250
 
1251
- if (editingMsgId !== null) {
1252
- await supabaseClient.from('messages').update({ content: text }).eq('id', editingMsgId);
1253
- } else {
1254
- await supabaseClient.from('messages').insert([{
1255
- channel_id: currentChannelId,
1256
- user_id: currentUser.id,
1257
- content: text,
1258
- reply_to_id: replyTargetMsg ? replyTargetMsg.id : null
1259
- }]);
1260
- }
1261
 
1262
- input.value = '';
1263
- cancelActionState();
1264
- }
 
1265
 
1266
- function handleKeyPress(e) {
1267
- if (e.key === 'Enter') sendMessage();
1268
- }
 
 
 
 
 
 
 
 
1269
 
1270
- function formatMessageText(text) {
1271
- const escaped = escapeHTML(text);
1272
- return escaped.replace(/@([a-zA-Z0-9_\-А-Яа-я]+)/g, '<span class="mention-tag" onclick="insertMention(\'$1\'); event.stopPropagation();">@$1</span>');
 
 
 
1273
  }
1274
 
1275
  function handleMessageContextMenu(e, msgId, isSelf) {
1276
  e.preventDefault();
1277
- e.stopPropagation();
1278
  selectedMessageId = msgId;
 
 
1279
 
1280
- const isMobile = window.innerWidth < 768;
1281
-
1282
- if (isMobile) {
1283
- document.getElementById('mobile-edit-btn').style.display = isSelf ? 'flex' : 'none';
1284
- document.getElementById('mobile-delete-btn').style.display = isSelf ? 'flex' : 'none';
1285
- document.getElementById('mobile-action-modal').classList.remove('hidden');
 
1286
  } else {
1287
- const menu = document.getElementById('context-menu');
1288
- document.getElementById('context-edit-btn').style.display = isSelf ? 'flex' : 'none';
1289
- document.getElementById('context-delete-btn').style.display = isSelf ? 'flex' : 'none';
 
 
1290
 
1291
- menu.style.left = e.clientX + 'px';
1292
- menu.style.top = e.clientY + 'px';
1293
- menu.classList.remove('hidden');
1294
  }
1295
  }
1296
 
 
 
 
 
 
1297
  function onReplyClick() {
1298
- hideContextMenus();
1299
  const msg = messagesData.find(m => m.id === selectedMessageId);
1300
  if (!msg) return;
1301
-
1302
  replyTargetMsg = msg;
1303
  editingMsgId = null;
1304
 
1305
- document.getElementById('reply-title').innerText = 'Ответ пользователю ' + getUserName(msg.user_id);
1306
- document.getElementById('reply-text').innerText = msg.content;
1307
- document.getElementById('reply-banner').classList.remove('hidden');
 
1308
  document.getElementById('message-input').focus();
1309
  }
1310
 
1311
  function onEditClick() {
1312
- hideContextMenus();
1313
  const msg = messagesData.find(m => m.id === selectedMessageId);
1314
  if (!msg) return;
1315
-
1316
  editingMsgId = msg.id;
1317
  replyTargetMsg = null;
1318
 
 
1319
  document.getElementById('reply-title').innerText = 'Редактирование сообщения';
1320
  document.getElementById('reply-text').innerText = msg.content;
1321
- document.getElementById('reply-banner').classList.remove('hidden');
1322
-
1323
- const input = document.getElementById('message-input');
1324
- input.value = msg.content;
1325
- input.focus();
1326
  }
1327
 
1328
  async function onDeleteClick() {
1329
- hideContextMenus();
1330
- if (selectedMessageId === null) return;
1331
-
1332
- await supabaseClient.from('messages').delete().eq('id', selectedMessageId);
1333
-
1334
- cancelActionState();
1335
  }
1336
 
1337
  function cancelActionState() {
1338
- selectedMessageId = null;
1339
  replyTargetMsg = null;
1340
  editingMsgId = null;
1341
  document.getElementById('reply-banner').classList.add('hidden');
1342
  document.getElementById('message-input').value = '';
1343
  }
1344
 
1345
- function hideContextMenus() {
1346
- document.getElementById('context-menu').classList.add('hidden');
1347
- document.getElementById('mobile-action-modal').classList.add('hidden');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1348
  }
1349
 
1350
- function closeMobileModal() {
1351
- document.getElementById('mobile-action-modal').classList.add('hidden');
 
 
 
 
 
 
1352
  }
1353
 
1354
- document.addEventListener('click', () => {
1355
- document.getElementById('context-menu').classList.add('hidden');
1356
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1357
 
1358
  function escapeHTML(str) {
 
1359
  return String(str).replace(/[&<>'"]/g,
1360
  tag => ({
1361
  '&': '&amp;',
 
194
  flex-direction: column;
195
  align-items: center;
196
  justify-content: center;
 
197
  padding: 40px 20px;
198
  flex: 1;
199
+ max-width: 1200px;
200
+ margin: 0 auto;
201
  }
202
  .landing-hero {
203
+ width: 100%;
204
  background: var(--bg-card);
205
+ padding: 48px;
206
+ border-radius: 6px;
207
  box-shadow: var(--shadow-card);
208
+ text-align: center;
209
+ margin-bottom: 30px;
210
+ border: 1px solid var(--border-color);
211
  }
212
  .landing-title {
213
+ font-size: 38px;
214
  font-weight: 700;
215
+ margin: 20px 0 15px 0;
216
  color: var(--text-primary);
217
+ line-height: 1.2;
218
  }
219
  .landing-desc {
220
+ font-size: 16px;
221
  color: var(--text-secondary);
222
  line-height: 1.6;
223
+ margin-bottom: 32px;
224
+ max-width: 780px;
225
+ margin-left: auto;
226
+ margin-right: auto;
227
+ }
228
+ .landing-grid {
229
+ display: grid;
230
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
231
+ gap: 20px;
232
+ width: 100%;
233
+ }
234
+ .landing-card {
235
+ background: var(--bg-card);
236
+ padding: 24px;
237
+ border-radius: 6px;
238
+ box-shadow: var(--shadow-card);
239
+ border: 1px solid var(--border-color);
240
+ transition: transform 0.2s, box-shadow 0.2s;
241
+ }
242
+ .landing-card:hover {
243
+ transform: translateY(-3px);
244
+ box-shadow: 0 6px 16px rgba(0,0,0,0.15);
245
+ }
246
+ .landing-card-icon {
247
+ font-size: 28px;
248
+ color: var(--brand-color);
249
+ margin-bottom: 12px;
250
+ }
251
+ .landing-card-title {
252
+ font-size: 18px;
253
+ font-weight: 700;
254
+ margin-bottom: 8px;
255
+ color: var(--text-primary);
256
+ }
257
+ .landing-card-text {
258
+ font-size: 14px;
259
+ color: var(--text-secondary);
260
+ line-height: 1.5;
261
  }
262
 
263
  /* Документация */
 
273
  overflow: hidden;
274
  }
275
  .docs-sidebar {
276
+ width: 300px;
277
  border-right: 1px solid var(--border-color);
278
  background: var(--bg-card);
279
  padding: 20px 0;
280
+ flex-shrink: 0;
281
  }
282
  .docs-menu-item {
283
+ padding: 10px 20px;
284
+ font-size: 13px;
285
  font-weight: 500;
286
  color: var(--text-primary);
287
  cursor: pointer;
288
  border-left: 3px solid transparent;
289
  display: block;
290
+ transition: background-color 0.15s;
291
+ }
292
+ .docs-menu-item.sub-item {
293
+ padding-left: 36px;
294
+ font-size: 12px;
295
+ color: var(--text-secondary);
296
  }
297
  .docs-menu-item:hover, .docs-menu-item.active {
298
  background: var(--quote-bg);
 
305
  overflow-y: auto;
306
  max-height: calc(100vh - 120px);
307
  }
308
+ .docs-content h1 { font-size: 26px; margin-bottom: 15px; border-bottom: 2px solid var(--border-color); padding-bottom: 10px; }
309
+ .docs-content h2 { font-size: 18px; color: var(--brand-color); margin: 25px 0 10px 0; }
310
+ .docs-content h3 { font-size: 15px; font-weight: 700; margin: 18px 0 8px 0; color: var(--text-primary); }
311
+ .docs-content p { font-size: 14px; color: var(--text-secondary); line-height: 1.6; margin-bottom: 15px; }
312
+ .docs-content ul { margin: 0 0 15px 20px; color: var(--text-secondary); font-size: 14px; line-height: 1.6; }
313
+
314
+ /* Изображения в сообщениях */
315
+ .chat-msg-img {
316
+ max-width: 100%;
317
+ max-height: 320px;
318
+ border-radius: 6px;
319
+ margin-top: 6px;
320
+ display: block;
321
+ cursor: pointer;
322
+ border: 1px solid var(--border-color);
323
+ transition: opacity 0.2s;
324
+ }
325
+ .chat-msg-img:hover {
326
+ opacity: 0.95;
327
+ }
328
 
329
+ /* Превью загружаемого фото */
330
+ .photo-preview-bar {
331
+ background: var(--bg-card);
332
+ border-top: 1px solid var(--border-color);
333
+ padding: 8px 16px;
334
+ display: flex;
335
+ align-items: center;
336
+ gap: 12px;
337
  }
338
+ .photo-preview-thumb {
339
+ width: 44px;
340
+ height: 44px;
 
341
  border-radius: 4px;
342
+ object-fit: cover;
 
 
 
 
343
  border: 1px solid var(--border-color);
344
  }
345
 
 
668
  <div id="screen-landing" class="screen active">
669
  <div class="landing-container">
670
  <div class="landing-hero">
671
+ <i class="fa-solid fa-shield-halved text-brand" style="font-size: 64px; color: var(--brand-color);"></i>
672
+ <h1 class="landing-title">ClientLess Communication Protocol</h1>
673
  <p class="landing-desc">
674
+ Легковесный клиент для работы с собственными независимыми серверами общением. Полная изоляция персональных данных, поддержка медиа-файлов, мгновенная доставка через WebSockets и строгая защита на уровне вашей СУБД.
 
675
  </p>
676
+ <div style="display: flex; gap: 15px; justify-content: center; flex-wrap: wrap;">
677
+ <button onclick="navigate('server')" class="btn-md" style="padding: 12px 28px; font-size: 14px;">Запустить Web Client</button>
678
+ <button onclick="navigate('docs')" class="btn-md btn-secondary" style="padding: 12px 28px; font-size: 14px;">Документация и Настройка БД</button>
679
+ </div>
680
+ </div>
681
+
682
+ <div class="landing-grid">
683
+ <div class="landing-card">
684
+ <i class="fa-solid fa-server landing-card-icon"></i>
685
+ <div class="landing-card-title">Собственный Узел</div>
686
+ <div class="landing-card-text">Подключайтесь к собственному проекту Supabase. Все сообщения и медиа принадлежат исключительно вам.</div>
687
+ </div>
688
+ <div class="landing-card">
689
+ <i class="fa-solid fa-lock landing-card-icon"></i>
690
+ <div class="landing-card-title">Строгий RLS</div>
691
+ <div class="landing-card-text">Авторизация и разграничение прав выполняются прямо в PostgreSQL с применением Row Level Security.</div>
692
+ </div>
693
+ <div class="landing-card">
694
+ <i class="fa-solid fa-image landing-card-icon"></i>
695
+ <div class="landing-card-title">Медиа в Хранилище</div>
696
+ <div class="landing-card-text">Отправляйте снимки экрана из буфера обмена (Ctrl + V) с автоматической загрузкой в Supabase Storage.</div>
697
  </div>
698
  </div>
699
  </div>
 
703
  <div id="screen-docs" class="screen">
704
  <div class="docs-wrapper">
705
  <div class="docs-sidebar">
706
+ <span class="docs-menu-item active" onclick="switchDocSection('sec-1', this)">1. Обзор и Требования</span>
707
+ <span class="docs-menu-item sub-item" onclick="switchDocSection('sec-1-1', this)">1.1 Требования Supabase</span>
708
+ <span class="docs-menu-item sub-item" onclick="switchDocSection('sec-1-2', this)">1.2 Принцип работы WCL</span>
709
+
710
+ <span class="docs-menu-item" onclick="switchDocSection('sec-2', this)">2. Структура БД (SQL)</span>
711
+ <span class="docs-menu-item sub-item" onclick="switchDocSection('sec-2-1', this)">2.1 Создание Таблиц</span>
712
+ <span class="docs-menu-item sub-item" onclick="switchDocSection('sec-2-2', this)">2.2 Включение Realtime</span>
713
+
714
+ <span class="docs-menu-item" onclick="switchDocSection('sec-3', this)">3. Настройка RLS и Безопасности</span>
715
+ <span class="docs-menu-item sub-item" onclick="switchDocSection('sec-3-1', this)">3.1 Политики Доступа БД</span>
716
+
717
+ <span class="docs-menu-item" onclick="switchDocSection('sec-4', this)">4. Настройка Storage (Файлы)</span>
718
+ <span class="docs-menu-item sub-item" onclick="switchDocSection('sec-4-1', this)">4.1 Создание Bucket 'chat-media'</span>
719
+ <span class="docs-menu-item sub-item" onclick="switchDocSection('sec-4-2', this)">4.2 Политики Загрузки Фото</span>
720
  </div>
721
  <div class="docs-content" id="docs-content-container">
722
 
723
+ <div id="doc-sec-1">
724
  <h1>1. Обзор архитектуры ClientLess</h1>
725
+ <p>ClientLess — это веб-клиент с архитектурой Zero-Trust Frontend. Приложение работает напрямую с вашим экзекутивом Supabase без промежуточных серверов.</p>
726
+
727
+ <h2 id="doc-sec-1-1">1.1 Требования к Supabase (Free Tier)</h2>
728
+ <p>Для работы сервера подходят бесплатные тарифы Supabase:</p>
729
+ <ul>
730
+ <li>База данных PostgreSQL (до 500 MB).</li>
731
+ <li>File Storage на 1 GB бесплатно (используется для изображений).</li>
732
+ <li>Поддержка Realtime подписок.</li>
733
+ </ul>
734
+
735
+ <h2 id="doc-sec-1-2">1.2 Принцип работы WCL</h2>
736
+ <p>Веб-клиент выполняет подключение с помощью <code>Project URL</code> и публичного ключа <code>Anon Key</code>. Все операции чтение/запись защищены правилами PostgreSQL RLS.</p>
737
  </div>
738
 
739
+ <div id="doc-sec-2" class="hidden">
740
+ <h1>2. Полная структура Базы Данных (SQL)</h1>
741
+ <p>Выполните этот скрипт в левом меню <strong>SQL Editor</strong> вашего Supabase проекта.</p>
742
 
743
+ <h2 id="doc-sec-2-1">2.1 Создание Таблиц</h2>
744
  <pre class="code-block"><code>-- =====================================================
745
+ -- ClientLess Core Schema (users, channels, messages)
746
  -- =====================================================
747
 
748
  -- 1. Таблица Пользователей
 
765
  channel_id UUID REFERENCES public.channels(id) ON DELETE CASCADE NOT NULL,
766
  user_id UUID REFERENCES public.users(id) ON DELETE CASCADE NOT NULL,
767
  content TEXT NOT NULL,
768
+ image_url TEXT,
769
  reply_to_id UUID REFERENCES public.messages(id) ON DELETE SET NULL,
770
  created_at TIMESTAMPTZ DEFAULT NOW()
771
+ );</code></pre>
772
 
773
+ <h2 id="doc-sec-2-2">2.2 Включение Realtime</h2>
774
+ <pre class="code-block"><code>-- Включаем публикации в реальном времени для чата
775
  ALTER PUBLICATION supabase_realtime ADD TABLE public.users;
776
  ALTER PUBLICATION supabase_realtime ADD TABLE public.channels;
777
  ALTER PUBLICATION supabase_realtime ADD TABLE public.messages;
778
 
779
+ -- Создаем базовые каналы по умолчанию
780
+ INSERT INTO public.channels (name) VALUES ('general'), ('development');</code></pre>
781
  </div>
782
 
783
+ <div id="doc-sec-3" class="hidden">
784
+ <h1>3. Настройка RLS и Безопасности</h1>
785
+ <p>Включите защиту данных Row Level Security на стороне базы данных.</p>
786
 
787
+ <h2 id="doc-sec-3-1">3.1 Политики Доступа БД</h2>
788
+ <pre class="code-block"><code>-- Включение RLS
789
+ ALTER TABLE public.users ENABLE ROW LEVEL SECURITY;
790
  ALTER TABLE public.channels ENABLE ROW LEVEL SECURITY;
 
791
  ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
792
 
793
+ -- Разрешаем публичный доступ с Anon Key
794
+ CREATE POLICY "Public Read Users" ON public.users FOR SELECT USING (true);
795
+ CREATE POLICY "Public Insert Users" ON public.users FOR INSERT WITH CHECK (true);
796
+
797
+ CREATE POLICY "Public Read Channels" ON public.channels FOR SELECT USING (true);
798
+
799
+ CREATE POLICY "Public Read Messages" ON public.messages FOR SELECT USING (true);
800
+ CREATE POLICY "Public Insert Messages" ON public.messages FOR INSERT WITH CHECK (true);
801
+ CREATE POLICY "Public Update Messages" ON public.messages FOR UPDATE USING (true);
802
+ CREATE POLICY "Public Delete Messages" ON public.messages FOR DELETE USING (true);</code></pre>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
803
  </div>
804
 
805
+ <div id="doc-sec-4" class="hidden">
806
+ <h1>4. Настройка Хранилища Изображений (Storage)</h1>
807
+ <p>Для загрузки фото из буфера обмена (Ctrl + V) или выбора файлов необходимо создать и настроить Storage Bucket.</p>
808
+
809
+ <h2 id="doc-sec-4-1">4.1 Создание Bucket 'chat-media'</h2>
810
+ <p>Перейдите в разедл <strong>Storage</strong> -> <strong>New Bucket</strong>:</p>
811
+ <ul>
812
+ <li>Имя бакета: <code class="inline">chat-media</code></li>
813
+ <li>Отметьте галочку: <strong>Public Bucket</strong> (Публичный доступ)</li>
814
+ </ul>
815
+
816
+ <h2 id="doc-sec-4-2">4.2 Политики Загрузки Фото (SQL)</h2>
817
+ <pre class="code-block"><code>-- Разрешаем чтение и загрузку файлов в чат
818
+ CREATE POLICY "Public Allow Select Storage" ON storage.objects
819
+ FOR SELECT USING (bucket_id = 'chat-media');
820
+
821
+ CREATE POLICY "Public Allow Upload Storage" ON storage.objects
822
+ FOR INSERT WITH CHECK (bucket_id = 'chat-media');</code></pre>
823
  </div>
824
 
825
  </div>
 
914
  <button onclick="cancelActionState()" style="background:none; border:none; font-size: 18px; color: var(--text-secondary); cursor:pointer;">&times;</button>
915
  </div>
916
 
917
+ <!-- Превью прикрепленного фото перед отправкой -->
918
+ <div id="photo-preview-bar" class="photo-preview-bar hidden">
919
+ <img id="photo-preview-img" src="" class="photo-preview-thumb" alt="Preview">
920
+ <div style="flex: 1; font-size: 12px; color: var(--text-secondary);">
921
+ <div style="font-weight: 700; color: var(--text-primary);">Изображение готово к отправке</div>
922
+ <span>Нажмите кнопку отправки или клавишу Enter</span>
923
+ </div>
924
+ <button onclick="clearPendingPhoto()" style="background:none; border:none; font-size: 18px; color: var(--text-secondary); cursor:pointer;">&times;</button>
925
+ </div>
926
+
927
  <div class="chat-input-area">
928
  <div class="chat-input-wrapper">
929
+ <!-- Скрытый инпут файла -->
930
+ <input type="file" id="photo-file-input" class="hidden" accept="image/*" onchange="handleFileSelect(event)">
931
+
932
+ <button onclick="document.getElementById('photo-file-input').click()" class="btn-md btn-secondary" style="padding: 10px 14px;" title="Прикрепить фото">
933
+ <i class="fa-solid fa-image"></i>
934
+ </button>
935
+
936
+ <input type="text" id="message-input" class="form-input selectable-text" placeholder="Написать сообщение... (Ctrl+V для вставки фото)" onkeypress="handleKeyPress(event)">
937
+
938
  <button onclick="sendMessage()" class="btn-md">
939
  <i class="fa-solid fa-paper-plane"></i>
940
  </button>
 
992
  let usersData = [];
993
 
994
  let realtimeSubscription = null;
995
+ let pendingPhotoFile = null;
996
 
997
  // Состояние приложения
998
  let appState = {
 
1006
  let replyTargetMsg = null;
1007
  let editingMsgId = null;
1008
 
1009
+ function navigate(screenId) {
1010
+ document.querySelectorAll('.screen').forEach(s => s.classList.remove('active'));
1011
+ const target = document.getElementById('screen-' + screenId);
1012
+ if (target) target.classList.add('active');
 
 
 
1013
 
1014
+ const nav = document.getElementById('marketing-nav');
1015
+ if (screenId === 'client') {
1016
+ if (nav) nav.style.display = 'none';
1017
  } else {
1018
+ if (nav) nav.style.display = 'flex';
 
1019
  }
 
1020
  }
1021
 
1022
+ function toggleTheme() {
1023
+ const html = document.documentElement;
1024
+ const currentTheme = html.getAttribute('data-theme') || 'light';
1025
+ const newTheme = currentTheme === 'light' ? 'dark' : 'light';
1026
+ html.setAttribute('data-theme', newTheme);
1027
+ appState.theme = newTheme;
1028
+ localStorage.setItem('wcl_theme', newTheme);
1029
+
1030
+ const navIcon = document.getElementById('theme-icon-nav');
1031
+ const clientIcon = document.getElementById('theme-icon-client');
1032
+ const iconClass = newTheme === 'light' ? 'fa-solid fa-moon' : 'fa-solid fa-sun';
1033
+ if (navIcon) navIcon.className = iconClass;
1034
+ if (clientIcon) clientIcon.className = iconClass;
1035
+ }
1036
+
1037
+ function restoreTheme() {
1038
+ const saved = localStorage.getItem('wcl_theme') || 'light';
1039
+ document.documentElement.setAttribute('data-theme', saved);
1040
+ appState.theme = saved;
1041
+ const navIcon = document.getElementById('theme-icon-nav');
1042
+ const clientIcon = document.getElementById('theme-icon-client');
1043
+ const iconClass = saved === 'light' ? 'fa-solid fa-moon' : 'fa-solid fa-sun';
1044
+ if (navIcon) navIcon.className = iconClass;
1045
+ if (clientIcon) clientIcon.className = iconClass;
1046
+ }
1047
+
1048
+ function initSupabase(url, key) {
1049
+ if (!url || !key || typeof supabase === 'undefined') return null;
1050
+ try {
1051
+ return supabase.createClient(url, key);
1052
+ } catch (err) {
1053
+ console.error("Supabase init error:", err);
1054
+ return null;
1055
  }
1056
  }
1057
 
1058
  async function restoreSession() {
1059
+ restoreTheme();
1060
+ const savedUrl = localStorage.getItem('wcl_project_url');
1061
+ const savedKey = localStorage.getItem('wcl_anon_key');
1062
+ const savedUserStr = localStorage.getItem('wcl_user');
1063
+
1064
+ if (savedUrl && savedKey) {
1065
+ appState.projectUrl = savedUrl;
1066
+ appState.anonKey = savedKey;
1067
+ document.getElementById('project-url').value = savedUrl;
1068
+ document.getElementById('anon-key').value = savedKey;
1069
+
1070
+ supabaseClient = initSupabase(savedUrl, savedKey);
1071
+
1072
+ if (savedUserStr && supabaseClient) {
1073
+ try {
1074
+ currentUser = JSON.parse(savedUserStr);
1075
+ document.getElementById('wcl-username').innerText = currentUser.username;
1076
+ document.getElementById('display-node').innerText = savedUrl.replace('https://', '');
1077
+ await startClientSession();
1078
+ return true;
1079
+ } catch (e) {
1080
+ console.error("Error restoring user session:", e);
 
 
1081
  }
1082
  }
 
 
1083
  }
1084
  return false;
1085
  }
1086
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1087
  async function handleServerSubmit(e) {
1088
  e.preventDefault();
 
 
1089
  const url = document.getElementById('project-url').value.trim();
1090
  const key = document.getElementById('anon-key').value.trim();
1091
+ const errorEl = document.getElementById('server-error');
1092
+ errorEl.style.display = 'none';
1093
+
1094
  try {
1095
+ const client = initSupabase(url, key);
1096
+ if (!client) throw new Error("Не удалось инициализировать Supabase клиент");
1097
+
1098
+ const { error } = await client.from('channels').select('id').limit(1);
1099
  if (error) throw error;
1100
+
1101
+ supabaseClient = client;
1102
  appState.projectUrl = url;
1103
  appState.anonKey = key;
1104
+ localStorage.setItem('wcl_project_url', url);
1105
+ localStorage.setItem('wcl_anon_key', key);
1106
+
1107
+ document.getElementById('display-node').innerText = url.replace('https://', '');
1108
  navigate('auth');
1109
+ } catch (err) {
1110
+ errorEl.innerText = err.message || "Ошибка подключения к узлу";
1111
+ errorEl.style.display = 'block';
1112
  }
1113
  }
1114
 
1115
  async function handleAuthSubmit(e) {
1116
  e.preventDefault();
1117
+ const usernameInput = document.getElementById('username').value.trim();
1118
+ const errorEl = document.getElementById('auth-error');
1119
+ errorEl.style.display = 'none';
1120
+
1121
+ if (!usernameInput) return;
1122
 
1123
  try {
1124
+ let { data: users, error: fetchErr } = await supabaseClient
 
1125
  .from('users')
1126
  .select('*')
1127
+ .eq('username', usernameInput);
1128
+
1129
+ if (fetchErr) throw fetchErr;
1130
+
1131
+ let userRecord = users && users.length > 0 ? users[0] : null;
1132
+
1133
+ if (!userRecord) {
1134
+ const { data: newUser, error: createErr } = await supabaseClient
1135
  .from('users')
1136
+ .insert([{ username: usernameInput }])
1137
+ .select();
1138
+
1139
+ if (createErr) throw createErr;
1140
+ userRecord = newUser[0];
 
 
1141
  }
1142
 
1143
+ currentUser = userRecord;
1144
+ localStorage.setItem('wcl_user', JSON.stringify(currentUser));
1145
+ document.getElementById('wcl-username').innerText = currentUser.username;
1146
+
1147
+ await startClientSession();
 
1148
  } catch (err) {
1149
+ errorEl.innerText = err.message || "Ошибка авторизации";
1150
+ errorEl.style.display = 'block';
1151
  }
1152
  }
1153
 
1154
+ async function startClientSession() {
1155
+ navigate('client');
1156
+ await loadUsers();
1157
+ await loadChannels();
1158
+ setupRealtime();
1159
+ }
1160
+
1161
+ async function loadUsers() {
1162
+ if (!supabaseClient) return;
1163
+ const { data, error } = await supabaseClient.from('users').select('*');
1164
+ if (!error && data) {
1165
+ usersData = data;
1166
+ renderUsers();
1167
+ }
1168
  }
1169
 
1170
+ function renderUsers() {
1171
+ const usersList = document.getElementById('users-list');
1172
+ const userCount = document.getElementById('user-count');
1173
+ if (userCount) userCount.innerText = usersData.length;
1174
+ if (!usersList) return;
1175
 
1176
+ usersList.innerHTML = usersData.map(u => `
1177
+ <div class="list-item">
1178
+ <span class="status-dot status-online"></span>
1179
+ <span style="font-size: 14px;">${escapeHTML(u.username)}</span>
1180
+ </div>
1181
+ `).join('');
1182
+ }
1183
 
1184
+ async function loadChannels() {
1185
+ if (!supabaseClient) return;
1186
+ const { data, error } = await supabaseClient.from('channels').select('*').order('created_at', { ascending: true });
1187
+ if (!error && data && data.length > 0) {
1188
+ channelsData = data;
1189
+ renderChannels();
1190
+ selectChannel(channelsData[0].id);
1191
  }
1192
+ }
1193
+
1194
+ function renderChannels() {
1195
+ const list = document.getElementById('channels-list');
1196
+ if (!list) return;
1197
+ list.innerHTML = channelsData.map(c => `
1198
+ <div class="list-item ${c.id === currentChannelId ? 'active' : ''}" onclick="selectChannel('${c.id}')">
1199
+ <i class="fa-solid fa-hashtag" style="margin-right: 10px; color: var(--text-secondary);"></i>
1200
+ <span>${escapeHTML(c.name)}</span>
1201
+ </div>
1202
+ `).join('');
1203
+ }
1204
+
1205
+ async function selectChannel(channelId) {
1206
+ currentChannelId = channelId;
1207
+ const ch = channelsData.find(c => c.id === channelId);
1208
+ if (ch) {
1209
+ document.getElementById('current-channel-title').innerText = `#${ch.name}`;
1210
+ }
1211
+ renderChannels();
1212
+ await loadMessages();
1213
+ }
1214
+
1215
+ async function loadMessages() {
1216
+ if (!supabaseClient || !currentChannelId) return;
1217
+ const { data, error } = await supabaseClient
1218
+ .from('messages')
1219
+ .select('*')
1220
+ .eq('channel_id', currentChannelId)
1221
+ .order('created_at', { ascending: true });
1222
+
1223
+ if (!error && data) {
1224
+ messagesData = data;
1225
+ renderMessages();
1226
+ }
1227
+ }
1228
+
1229
+ function setupRealtime() {
1230
+ if (!supabaseClient) return;
1231
+ if (realtimeSubscription) supabaseClient.removeChannel(realtimeSubscription);
1232
 
1233
+ realtimeSubscription = supabaseClient
1234
+ .channel('public-chat')
 
1235
  .on('postgres_changes', { event: '*', schema: 'public', table: 'messages' }, payload => {
1236
  if (payload.eventType === 'INSERT') {
1237
  if (payload.new.channel_id === currentChannelId) {
1238
  messagesData.push(payload.new);
1239
  renderMessages();
1240
  }
 
 
 
1241
  } else if (payload.eventType === 'UPDATE') {
1242
  const idx = messagesData.findIndex(m => m.id === payload.new.id);
1243
+ if (idx !== -1) {
1244
  messagesData[idx] = payload.new;
1245
  renderMessages();
1246
  }
1247
+ } else if (payload.eventType === 'DELETE') {
1248
+ messagesData = messagesData.filter(m => m.id === payload.old.id);
1249
+ renderMessages();
1250
  }
1251
  })
1252
  .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'users' }, payload => {
1253
  usersData.push(payload.new);
1254
+ renderUsers();
 
 
 
 
1255
  })
1256
  .subscribe();
1257
  }
1258
 
1259
+ function getUserName(userId) {
1260
+ const u = usersData.find(user => user.id === userId);
1261
+ return u ? u.username : 'Пользователь';
 
 
 
 
 
 
1262
  }
1263
 
1264
+ function formatTime(dateStr) {
1265
+ if (!dateStr) return '';
1266
+ const date = new Date(dateStr);
1267
+ return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
1268
  }
1269
 
1270
+ function formatMessageText(text) {
1271
+ if (!text) return '';
1272
+ let escaped = escapeHTML(text);
1273
+ escaped = escaped.replace(/@([a-zA-Z0-9_А-Яа-я]+)/g, '<span class="mention-tag">@$1</span>');
1274
+ return escaped;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1275
  }
1276
 
1277
+ function switchDocSection(sectionId, el) {
1278
+ document.querySelectorAll('.docs-menu-item').forEach(m => m.classList.remove('active'));
1279
+ if(el) el.classList.add('active');
1280
+
1281
+ const mainGroup = sectionId.startsWith('sec-1') ? 'sec-1' :
1282
+ sectionId.startsWith('sec-2') ? 'sec-2' :
1283
+ sectionId.startsWith('sec-3') ? 'sec-3' : 'sec-4';
1284
 
1285
+ ['sec-1', 'sec-2', 'sec-3', 'sec-4'].forEach(id => {
1286
+ const docEl = document.getElementById('doc-' + id);
1287
+ if (docEl) {
1288
+ if (id === mainGroup) docEl.classList.remove('hidden');
1289
+ else docEl.classList.add('hidden');
1290
+ }
 
 
 
 
1291
  });
1292
+
1293
+ const targetEl = document.getElementById('doc-' + sectionId);
1294
+ if (targetEl) {
1295
+ targetEl.scrollIntoView({ behavior: 'smooth' });
1296
+ }
1297
  }
1298
 
1299
+ // Обработка вставки фото из буфера обмена (Ctrl + V)
1300
+ document.addEventListener('paste', function(e) {
1301
+ const screenClient = document.getElementById('screen-client');
1302
+ if (!screenClient || !screenClient.classList.contains('active')) return;
1303
 
1304
+ const items = (e.clipboardData || e.originalEvent.clipboardData).items;
1305
+ for (let item of items) {
1306
+ if (item.type.indexOf('image') === 0) {
1307
+ const blob = item.getAsFile();
1308
+ setPendingPhoto(blob);
1309
+ e.preventDefault();
1310
+ break;
1311
+ }
1312
+ }
1313
+ });
1314
 
1315
+ function handleFileSelect(e) {
1316
+ const file = e.target.files[0];
1317
+ if (file && file.type.startsWith('image/')) {
1318
+ setPendingPhoto(file);
1319
+ }
1320
+ e.target.value = '';
1321
  }
1322
 
1323
+ function setPendingPhoto(file) {
1324
+ pendingPhotoFile = file;
1325
+ const reader = new FileReader();
1326
+ reader.onload = function(e) {
1327
+ document.getElementById('photo-preview-img').src = e.target.result;
1328
+ document.getElementById('photo-preview-bar').classList.remove('hidden');
1329
+ };
1330
+ reader.readAsDataURL(file);
1331
  }
1332
 
1333
+ function clearPendingPhoto() {
1334
+ pendingPhotoFile = null;
1335
+ document.getElementById('photo-preview-img').src = '';
1336
+ document.getElementById('photo-preview-bar').classList.add('hidden');
1337
  }
1338
 
1339
+ async function uploadPhotoToStorage(file) {
1340
+ if (!supabaseClient) return null;
1341
+ const ext = file.name ? file.name.split('.').pop() : 'png';
1342
+ const fileName = `${Date.now()}_${Math.random().toString(36).substring(2, 8)}.${ext}`;
1343
+ const filePath = `${currentUser ? currentUser.id : 'public'}/${fileName}`;
1344
+
1345
+ const { data, error } = await supabaseClient.storage
1346
+ .from('chat-media')
1347
+ .upload(filePath, file);
1348
+
1349
+ if (error) {
1350
+ console.error("Storage upload error:", error);
1351
+ throw new Error("Ошибка загрузки фото в Storage. Проверьте правильность настройки бакета 'chat-media'.");
1352
+ }
1353
+
1354
+ const { data: publicUrlData } = supabaseClient.storage
1355
+ .from('chat-media')
1356
+ .getPublicUrl(filePath);
1357
+
1358
+ return publicUrlData.publicUrl;
1359
  }
1360
 
1361
  function renderMessages() {
 
1367
  const isSelf = currentUser && msg.user_id === currentUser.id;
1368
  const authorName = getUserName(msg.user_id);
1369
 
1370
+ const isMentioned = currentUser && msg.content && msg.content.toLowerCase().includes(`@${currentUser.username.toLowerCase()}`);
1371
 
1372
  msgDiv.className = `message ${isSelf ? 'self' : ''} ${isMentioned ? 'mentioned-me' : ''}`;
1373
  msgDiv.id = `msg-${msg.id}`;
 
1381
  if (msg.reply_to_id) {
1382
  const replyOriginalMsg = messagesData.find(m => m.id === msg.reply_to_id);
1383
  const replyAuthor = replyOriginalMsg ? getUserName(replyOriginalMsg.user_id) : 'Unknown';
1384
+ const replyText = replyOriginalMsg ? (replyOriginalMsg.content || '[Фото]') : 'Удаленное сообщение';
1385
 
1386
  quoteHtml = `
1387
  <div class="message-quote" onclick="scrollToMessage('${msg.reply_to_id}'); event.stopPropagation();">
 
1391
  `;
1392
  }
1393
 
1394
+ let photoHtml = '';
1395
+ if (msg.image_url && isValidUrl(msg.image_url)) {
1396
+ photoHtml = `<img src="${escapeHTML(msg.image_url)}" class="chat-msg-img" loading="lazy" onclick="window.open('${escapeHTML(msg.image_url)}', '_blank')" alt="Attachment" />`;
1397
+ }
1398
+
1399
  msgDiv.innerHTML = `
1400
  <div class="message-author">${escapeHTML(authorName)}</div>
1401
  ${quoteHtml}
1402
+ ${photoHtml}
1403
  <div class="selectable-text">${formatMessageText(msg.content)}</div>
1404
  <div class="message-time">${formatTime(msg.created_at)}</div>
1405
  `;
 
1410
  chatBox.scrollTop = chatBox.scrollHeight;
1411
  }
1412
 
 
 
 
 
 
 
 
 
 
 
 
1413
  async function sendMessage() {
1414
  const input = document.getElementById('message-input');
1415
  const text = input.value.trim();
1416
+ if ((!text && !pendingPhotoFile) || !currentChannelId || !currentUser) return;
1417
 
1418
+ let uploadedImageUrl = null;
 
 
 
 
 
 
 
 
 
1419
 
1420
+ try {
1421
+ if (pendingPhotoFile) {
1422
+ uploadedImageUrl = await uploadPhotoToStorage(pendingPhotoFile);
1423
+ }
1424
 
1425
+ if (editingMsgId !== null) {
1426
+ await supabaseClient.from('messages').update({ content: text }).eq('id', editingMsgId);
1427
+ } else {
1428
+ await supabaseClient.from('messages').insert([{
1429
+ channel_id: currentChannelId,
1430
+ user_id: currentUser.id,
1431
+ content: text || '',
1432
+ image_url: uploadedImageUrl,
1433
+ reply_to_id: replyTargetMsg ? replyTargetMsg.id : null
1434
+ }]);
1435
+ }
1436
 
1437
+ input.value = '';
1438
+ clearPendingPhoto();
1439
+ cancelActionState();
1440
+ } catch(err) {
1441
+ alert(err.message || "Ошибка отправки сообщения");
1442
+ }
1443
  }
1444
 
1445
  function handleMessageContextMenu(e, msgId, isSelf) {
1446
  e.preventDefault();
 
1447
  selectedMessageId = msgId;
1448
+ const msg = messagesData.find(m => m.id === msgId);
1449
+ if (!msg) return;
1450
 
1451
+ if (window.innerWidth < 768) {
1452
+ const mobileModal = document.getElementById('mobile-action-modal');
1453
+ const editBtn = document.getElementById('mobile-edit-btn');
1454
+ const deleteBtn = document.getElementById('mobile-delete-btn');
1455
+ if (editBtn) editBtn.style.display = isSelf ? 'flex' : 'none';
1456
+ if (deleteBtn) deleteBtn.style.display = isSelf ? 'flex' : 'none';
1457
+ if (mobileModal) mobileModal.classList.remove('hidden');
1458
  } else {
1459
+ const ctxMenu = document.getElementById('context-menu');
1460
+ const editBtn = document.getElementById('context-edit-btn');
1461
+ const deleteBtn = document.getElementById('context-delete-btn');
1462
+ if (editBtn) editBtn.style.display = isSelf ? 'flex' : 'none';
1463
+ if (deleteBtn) deleteBtn.style.display = isSelf ? 'flex' : 'none';
1464
 
1465
+ ctxMenu.style.left = `${Math.min(e.clientX, window.innerWidth - 180)}px`;
1466
+ ctxMenu.style.top = `${Math.min(e.clientY, window.innerHeight - 120)}px`;
1467
+ ctxMenu.classList.remove('hidden');
1468
  }
1469
  }
1470
 
1471
+ document.addEventListener('click', () => {
1472
+ const ctxMenu = document.getElementById('context-menu');
1473
+ if (ctxMenu) ctxMenu.classList.add('hidden');
1474
+ });
1475
+
1476
  function onReplyClick() {
 
1477
  const msg = messagesData.find(m => m.id === selectedMessageId);
1478
  if (!msg) return;
 
1479
  replyTargetMsg = msg;
1480
  editingMsgId = null;
1481
 
1482
+ const banner = document.getElementById('reply-banner');
1483
+ document.getElementById('reply-title').innerText = `Ответ пользователю: ${getUserName(msg.user_id)}`;
1484
+ document.getElementById('reply-text').innerText = msg.content || '[Изображение]';
1485
+ banner.classList.remove('hidden');
1486
  document.getElementById('message-input').focus();
1487
  }
1488
 
1489
  function onEditClick() {
 
1490
  const msg = messagesData.find(m => m.id === selectedMessageId);
1491
  if (!msg) return;
 
1492
  editingMsgId = msg.id;
1493
  replyTargetMsg = null;
1494
 
1495
+ const banner = document.getElementById('reply-banner');
1496
  document.getElementById('reply-title').innerText = 'Редактирование сообщения';
1497
  document.getElementById('reply-text').innerText = msg.content;
1498
+ document.getElementById('message-input').value = msg.content;
1499
+ banner.classList.remove('hidden');
1500
+ document.getElementById('message-input').focus();
 
 
1501
  }
1502
 
1503
  async function onDeleteClick() {
1504
+ if (!selectedMessageId || !supabaseClient) return;
1505
+ try {
1506
+ await supabaseClient.from('messages').delete().eq('id', selectedMessageId);
1507
+ } catch (err) {
1508
+ alert("Ошибка удаления сообщения: " + err.message);
1509
+ }
1510
  }
1511
 
1512
  function cancelActionState() {
 
1513
  replyTargetMsg = null;
1514
  editingMsgId = null;
1515
  document.getElementById('reply-banner').classList.add('hidden');
1516
  document.getElementById('message-input').value = '';
1517
  }
1518
 
1519
+ function closeMobileModal(e) {
1520
+ const modal = document.getElementById('mobile-action-modal');
1521
+ if (modal) modal.classList.add('hidden');
1522
+ }
1523
+
1524
+ function toggleSidebar(side) {
1525
+ const leftSb = document.getElementById('wcl-left-sidebar');
1526
+ const rightSb = document.getElementById('wcl-right-sidebar');
1527
+ const overlay = document.getElementById('wcl-overlay');
1528
+
1529
+ if (side === 'left') {
1530
+ leftSb.classList.toggle('open');
1531
+ overlay.classList.toggle('active', leftSb.classList.contains('open'));
1532
+ } else {
1533
+ rightSb.classList.toggle('open');
1534
+ overlay.classList.toggle('active', rightSb.classList.contains('open'));
1535
+ }
1536
  }
1537
 
1538
+ function closeSidebars() {
1539
+ const leftSb = document.getElementById('wcl-left-sidebar');
1540
+ const rightSb = document.getElementById('wcl-right-sidebar');
1541
+ const overlay = document.getElementById('wcl-overlay');
1542
+
1543
+ if (leftSb) leftSb.classList.remove('open');
1544
+ if (rightSb) rightSb.classList.remove('open');
1545
+ if (overlay) overlay.classList.remove('active');
1546
  }
1547
 
1548
+ function scrollToMessage(msgId) {
1549
+ const el = document.getElementById(`msg-${msgId}`);
1550
+ if (el) {
1551
+ el.scrollIntoView({ behavior: 'smooth', block: 'center' });
1552
+ el.classList.remove('flash-blue');
1553
+ void el.offsetWidth;
1554
+ el.classList.add('flash-blue');
1555
+ }
1556
+ }
1557
+
1558
+ function handleKeyPress(e) {
1559
+ if (e.key === 'Enter' && !e.shiftKey) {
1560
+ e.preventDefault();
1561
+ sendMessage();
1562
+ }
1563
+ }
1564
+
1565
+ function logout() {
1566
+ localStorage.removeItem('wcl_user');
1567
+ currentUser = null;
1568
+ if (realtimeSubscription && supabaseClient) {
1569
+ supabaseClient.removeChannel(realtimeSubscription);
1570
+ }
1571
+ navigate('server');
1572
+ }
1573
+
1574
+ function isValidUrl(string) {
1575
+ try {
1576
+ const url = new URL(string);
1577
+ return url.protocol === "http:" || url.protocol === "https:";
1578
+ } catch (_) {
1579
+ return false;
1580
+ }
1581
+ }
1582
 
1583
  function escapeHTML(str) {
1584
+ if (!str) return '';
1585
  return String(str).replace(/[&<>'"]/g,
1586
  tag => ({
1587
  '&': '&amp;',