sldshr commited on
Commit
938b79d
·
verified ·
1 Parent(s): 519160a

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +607 -870
index.html CHANGED
@@ -2,1037 +2,774 @@
2
  <html lang="ru">
3
  <head>
4
  <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
6
- <title>Messenger 2015</title>
7
  <style>
 
8
  :root {
9
- /* 2015 Glossy Theme Colors */
10
- --bg-main: #eef2f5;
11
- --bg-panel: #ffffff;
12
- --text-main: #333333;
13
- --text-muted: #777777;
14
- --border-color: #c0cdd6;
15
-
16
- --btn-grad-top: #65a9e5;
17
- --btn-grad-bottom: #3b7cbf;
18
- --btn-hover-top: #78b8f2;
19
- --btn-hover-bottom: #4a8cd0;
20
- --btn-border: #286098;
21
- --btn-text: #ffffff;
22
- --btn-shadow: inset 0 1px 0 rgba(255,255,255,0.4), 0 1px 2px rgba(0,0,0,0.2);
23
-
24
- --header-grad-top: #4a5c6d;
25
- --header-grad-bottom: #2b3947;
26
- --header-border: #1a222b;
27
-
28
- --msg-mine-grad-top: #e8f4ff;
29
- --msg-mine-grad-bottom: #d4e8fa;
30
- --msg-mine-border: #a9cceb;
31
-
32
- --msg-other-grad-top: #ffffff;
33
- --msg-other-grad-bottom: #f5f5f5;
34
- --msg-other-border: #dcdcdc;
35
-
36
- --danger: #d9534f;
37
- --success: #5cb85c;
38
- }
39
-
40
- ::-webkit-scrollbar {
41
- width: 10px;
42
- }
43
- ::-webkit-scrollbar-track {
44
- background: #e1e8ed;
45
- border-left: 1px solid var(--border-color);
46
- }
47
- ::-webkit-scrollbar-thumb {
48
- background: linear-gradient(to bottom, #aab8c2, #8c9ea8);
49
- border: 1px solid #738794;
50
- border-radius: 5px;
51
- }
52
- ::-webkit-scrollbar-thumb:hover {
53
- background: linear-gradient(to bottom, #8c9ea8, #6d818d);
54
  }
55
 
56
  * {
57
  box-sizing: border-box;
58
- margin: 0;
59
- padding: 0;
60
- user-select: none; /* Disable text selection mostly */
61
  }
62
-
63
  body {
64
- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
65
- background-color: var(--bg-main);
66
- color: var(--text-main);
 
 
 
67
  height: 100vh;
68
  display: flex;
69
  flex-direction: column;
70
  overflow: hidden;
71
- font-size: 14px;
72
  }
73
 
74
- input, textarea, button {
75
- font-family: inherit;
76
- font-size: inherit;
 
 
 
 
 
77
  }
78
 
79
- .btn-glossy {
80
- background: linear-gradient(to bottom, var(--btn-grad-top), var(--btn-grad-bottom));
81
- border: 1px solid var(--btn-border);
82
- color: var(--btn-text);
83
- padding: 8px 16px;
84
- border-radius: 4px;
 
 
85
  cursor: pointer;
86
- text-shadow: 0 -1px 0 rgba(0,0,0,0.3);
87
- box-shadow: var(--btn-shadow);
88
- font-weight: bold;
89
- transition: all 0.1s ease;
90
- }
91
- .btn-glossy:hover {
92
- background: linear-gradient(to bottom, var(--btn-hover-top), var(--btn-hover-bottom));
93
- }
94
- .btn-glossy:active {
95
- box-shadow: inset 0 2px 4px rgba(0,0,0,0.3);
96
- background: var(--btn-grad-bottom);
97
- }
98
-
99
- .btn-danger {
100
- --btn-grad-top: #f27b77;
101
- --btn-grad-bottom: #c9302c;
102
- --btn-hover-top: #f78d8a;
103
- --btn-hover-bottom: #d9534f;
104
- --btn-border: #ac2925;
105
  }
106
 
107
- input[type="text"], input[type="password"], textarea {
108
- width: 100%;
109
- padding: 8px 10px;
110
- border: 1px solid #a9b5bd;
111
- border-radius: 3px;
112
- box-shadow: inset 0 2px 3px rgba(0,0,0,0.05);
113
- background: #fff;
114
- color: #333;
115
- user-select: text; /* Allow selection inside inputs */
116
- }
117
- input[type="text"]:focus, input[type="password"]:focus, textarea:focus {
118
- outline: none;
119
- border-color: #66afe9;
120
- box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
121
  }
122
 
123
- .hidden { display: none !important; }
 
 
 
 
 
124
 
125
- .modal-wrapper {
126
- position: fixed; top: 0; left: 0; width: 100%; height: 100%;
127
- background: rgba(0,0,0,0.6);
128
- display: flex; align-items: center; justify-content: center;
 
 
 
 
129
  z-index: 1000;
 
 
130
  }
131
- .modal-content {
132
- background: var(--bg-main);
133
- border: 1px solid #777;
134
- border-radius: 6px;
135
- box-shadow: 0 5px 15px rgba(0,0,0,0.5);
136
- width: 90%;
137
- max-width: 500px;
138
- max-height: 90vh;
139
- overflow-y: auto;
140
- position: relative;
141
  }
142
- .modal-header {
143
- background: linear-gradient(to bottom, var(--header-grad-top), var(--header-grad-bottom));
144
- border-bottom: 1px solid var(--header-border);
145
- padding: 10px 15px;
146
- color: #fff;
147
  font-weight: bold;
148
- text-shadow: 0 -1px 0 rgba(0,0,0,0.8);
149
- border-top-left-radius: 5px;
150
- border-top-right-radius: 5px;
151
- display: flex; justify-content: space-between; align-items: center;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  }
153
- .modal-body {
 
 
 
 
 
154
  padding: 15px;
155
- background: #fff;
 
 
 
156
  }
157
- .close-modal-btn {
158
- background: none; border: none; color: #fff; cursor: pointer; opacity: 0.7;
159
- display: flex; align-items: center; justify-content: center;
 
 
160
  }
161
- .close-modal-btn:hover { opacity: 1; }
162
 
163
- #login-screen {
164
- display: flex; flex-direction: column; align-items: center; justify-content: center;
165
- height: 100%;
166
- background: radial-gradient(circle at center, #ffffff 0%, #d4e0e8 100%);
 
 
 
167
  }
168
- .login-box {
169
- background: #fff;
 
 
 
 
 
 
 
 
 
170
  border: 1px solid var(--border-color);
171
- border-radius: 6px;
172
- box-shadow: 0 4px 12px rgba(0,0,0,0.15);
173
- width: 340px;
174
- overflow: hidden;
175
  }
176
- .login-header {
177
- background: linear-gradient(to bottom, #f9f9f9, #e0e0e0);
 
178
  border-bottom: 1px solid var(--border-color);
179
- padding: 15px;
180
- text-align: center;
181
- font-size: 18px;
182
  font-weight: bold;
183
- color: #444;
184
- text-shadow: 0 1px 0 #fff;
185
- }
186
- .login-form-inner { padding: 20px; display: flex; flex-direction: column; gap: 15px; }
187
- .form-group label { display: block; margin-bottom: 5px; font-weight: bold; color: #555; }
188
- .divider { height: 1px; background: var(--border-color); margin: 5px 0; }
189
-
190
- .top-right-controls { position: fixed; top: 10px; right: 10px; display: flex; gap: 10px; z-index: 100; }
191
-
192
- #app-screen {
193
- display: flex; width: 100%; height: 100%;
194
  }
195
 
196
  .sidebar {
197
- width: 250px;
198
- background: #f4f7f9;
199
- border-right: 1px solid var(--border-color);
200
- display: flex; flex-direction: column;
201
  flex-shrink: 0;
202
- transition: transform 0.3s ease;
203
  }
204
- .right-sidebar {
205
- width: 220px;
206
- background: #f4f7f9;
207
- border-left: 1px solid var(--border-color);
208
- display: flex; flex-direction: column;
209
- flex-shrink: 0;
210
- transition: transform 0.3s ease;
211
- }
212
- .sidebar-header {
213
- background: linear-gradient(to bottom, var(--header-grad-top), var(--header-grad-bottom));
214
- border-bottom: 1px solid var(--header-border);
215
- color: #fff; padding: 12px 15px; font-weight: bold; text-shadow: 0 -1px 0 #000;
216
- display: flex; justify-content: space-between; align-items: center;
217
- }
218
- .list-container {
219
- flex: 1; overflow-y: auto; padding: 10px 0;
220
- }
221
-
222
- .channel-item, .member-item {
223
- padding: 8px 15px;
224
- cursor: pointer;
225
- display: flex; align-items: center;
226
- color: #333;
227
- border-bottom: 1px solid #e1e8ed;
228
- }
229
- .channel-item:hover, .member-item:hover { background: #e8f0f6; }
230
- .channel-item.active {
231
- background: #d4e5f4; font-weight: bold;
232
- box-shadow: inset 3px 0 0 var(--btn-grad-bottom);
233
- }
234
-
235
- .avatar-wrap { position: relative; display: inline-block; margin-right: 10px; }
236
- .avatar {
237
- width: 32px; height: 32px; border-radius: 4px;
238
- background: #ccc; color: #fff;
239
- display: flex; align-items: center; justify-content: center;
240
- font-weight: bold; text-shadow: 0 1px 1px rgba(0,0,0,0.4);
241
- box-shadow: inset 0 1px 0 rgba(255,255,255,0.3), 0 1px 2px rgba(0,0,0,0.3);
242
- border: 1px solid rgba(0,0,0,0.1);
243
- }
244
- .status-dot {
245
- position: absolute; bottom: -2px; right: -2px; width: 10px; height: 10px;
246
- border-radius: 50%; background: var(--success); border: 1px solid #fff;
247
- }
248
- .status-dot.offline { background: var(--text-muted); }
249
 
250
- .current-user-panel {
251
- background: #e8ecf0; border-top: 1px solid var(--border-color);
252
- padding: 10px 15px; display: flex; align-items: center; cursor: pointer;
253
- }
254
- .current-user-panel:hover { background: #dce2e8; }
255
-
256
- .main-chat {
257
- flex: 1; display: flex; flex-direction: column; min-width: 0; background: #fff;
258
- }
259
- .chat-header {
260
- background: linear-gradient(to bottom, #f9f9f9, #e0e0e0);
261
- border-bottom: 1px solid var(--border-color);
262
- padding: 12px 15px; display: flex; align-items: center; justify-content: space-between;
263
- font-weight: bold; color: #333; text-shadow: 0 1px 0 #fff;
264
- }
265
- .mobile-btn {
266
- background: none; border: none; cursor: pointer; padding: 5px; display: none; color: #555;
267
  }
 
268
  .chat-messages {
269
- flex: 1; overflow-y: auto; padding: 15px; display: flex; flex-direction: column; gap: 10px;
270
- background: #ffffff; user-select: text;
 
 
 
 
 
271
  }
272
 
273
- .message-row { display: flex; flex-direction: column; max-width: 85%; }
274
- .message-row.mine { align-self: flex-end; }
275
- .message-row.other { align-self: flex-start; }
276
-
277
- .message-bubble {
278
- padding: 8px 12px; border-radius: 6px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);
279
- position: relative; word-wrap: break-word;
280
  }
281
- .message-row.mine .message-bubble {
282
- background: linear-gradient(to bottom, var(--msg-mine-grad-top), var(--msg-mine-grad-bottom));
283
- border: 1px solid var(--msg-mine-border);
284
- border-bottom-right-radius: 0;
285
  }
286
- .message-row.other .message-bubble {
287
- background: linear-gradient(to bottom, var(--msg-other-grad-top), var(--msg-other-grad-bottom));
288
- border: 1px solid var(--msg-other-border);
289
- border-bottom-left-radius: 0;
 
 
 
290
  }
291
 
292
- .message-header {
293
- display: flex; justify-content: space-between; align-items: center;
294
- margin-bottom: 4px; font-size: 11px;
295
  }
296
- .message-row.mine .message-header { color: #517a9e; }
297
- .message-row.other .message-header { color: #888; }
298
-
299
- .message-author { font-weight: bold; margin-right: 5px; }
300
- .message-time { color: inherit; opacity: 0.8; }
301
- .message-edited { font-style: italic; opacity: 0.6; margin-left: 5px; }
302
 
303
- .message-actions { display: flex; gap: 5px; opacity: 0; transition: opacity 0.2s; margin-left: 10px; }
304
- .message-bubble:hover .message-actions { opacity: 1; }
305
-
306
- .icon-btn-small {
307
- background: rgba(255,255,255,0.5); border: 1px solid rgba(0,0,0,0.15);
308
- border-radius: 3px; cursor: pointer; padding: 2px 4px; color: #555;
309
- display: flex; align-items: center; justify-content: center;
310
  }
311
- .icon-btn-small:hover { background: rgba(255,255,255,0.9); }
312
 
313
- .message-content { line-height: 1.4; color: #222; }
314
- .message-content code { background: rgba(0,0,0,0.05); padding: 2px 4px; border-radius: 3px; font-family: monospace; border: 1px solid rgba(0,0,0,0.1); }
315
- .message-content pre { background: #f4f4f4; padding: 8px; border-radius: 3px; border: 1px solid #ccc; overflow-x: auto; font-family: monospace; margin-top: 5px; }
316
- .mention { background: #d4e5f4; border: 1px solid #a9cceb; padding: 1px 4px; border-radius: 3px; font-weight: bold; color: #286098; }
317
-
318
- .reply-quote {
319
- background: rgba(0,0,0,0.03); border-left: 3px solid #777;
320
- padding: 4px 8px; margin-bottom: 6px; font-size: 12px; color: #666;
321
- border-radius: 0 3px 3px 0; cursor: pointer;
322
- }
323
- .message-row.mine .reply-quote { border-left-color: #286098; }
324
 
325
- .chat-input-area {
326
- background: #f0f3f5; border-top: 1px solid var(--border-color); padding: 10px;
327
- display: flex; flex-direction: column;
328
- }
329
- .action-bar {
330
- background: #fff8c4; border: 1px solid #f2c779; padding: 6px 10px;
331
- border-radius: 4px; margin-bottom: 8px; font-size: 12px;
332
- display: flex; justify-content: space-between; align-items: center;
333
- color: #8a6d3b; box-shadow: inset 0 1px 0 rgba(255,255,255,0.5);
334
- }
335
- .input-row { display: flex; gap: 8px; }
336
- .input-row textarea {
337
- flex: 1; resize: none; min-height: 40px; max-height: 120px; overflow-y: auto;
338
- border-radius: 4px; box-shadow: inset 0 2px 3px rgba(0,0,0,0.1);
339
  }
340
 
341
- .icon { width: 16px; height: 16px; fill: currentColor; }
342
- .icon-lg { width: 24px; height: 24px; fill: currentColor; }
343
-
344
- .tabs-header { display: flex; border-bottom: 1px solid #ccc; margin-bottom: 15px; }
345
- .tab-btn { flex: 1; padding: 8px; text-align: center; cursor: pointer; background: #eee; border: 1px solid #ccc; border-bottom: none; }
346
- .tab-btn.active { background: #fff; font-weight: bold; margin-bottom: -1px; border-bottom: 1px solid #fff; }
347
 
348
  @media (max-width: 768px) {
349
- .mobile-btn { display: block; }
350
- .sidebar {
351
- position: absolute; top: 0; left: 0; height: 100%; z-index: 50;
352
- transform: translateX(-100%);
353
- box-shadow: 2px 0 10px rgba(0,0,0,0.2);
354
- }
355
- .sidebar.open { transform: translateX(0); }
356
 
357
- .right-sidebar {
358
- position: absolute; top: 0; right: 0; height: 100%; z-index: 50;
359
- transform: translateX(100%);
360
- box-shadow: -2px 0 10px rgba(0,0,0,0.2);
361
- }
362
- .right-sidebar.open { transform: translateX(0); }
363
-
364
- .message-row { max-width: 95%; }
365
  }
 
 
 
 
 
366
  </style>
367
  </head>
368
  <body>
369
 
370
- <svg style="display: none;">
371
- <symbol id="icon-close" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></symbol>
372
- <symbol id="icon-send" viewBox="0 0 24 24"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></symbol>
373
- <symbol id="icon-menu" viewBox="0 0 24 24"><path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/></symbol>
374
- <symbol id="icon-users" viewBox="0 0 24 24"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></symbol>
375
- <symbol id="icon-plus" viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></symbol>
376
- <symbol id="icon-trash" viewBox="0 0 24 24"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/></symbol>
377
- <symbol id="icon-edit" viewBox="0 0 24 24"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></symbol>
378
- <symbol id="icon-reply" viewBox="0 0 24 24"><path d="M10 9V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"/></symbol>
379
- <symbol id="icon-server" viewBox="0 0 24 24"><path d="M2 15h20v4H2v-4zm0-6h20v4H2V9zm0-6h20v4H2V3z"/></symbol>
380
- <symbol id="icon-earth" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></symbol>
381
- </svg>
382
-
383
- <div class="top-right-controls">
384
- <button id="lang-btn" class="btn-glossy" style="padding: 4px 8px; font-size: 12px; display: flex; align-items: center; gap: 4px;">
385
- <svg class="icon"><use href="#icon-earth"></use></svg> <span id="lang-text">EN</span>
386
- </button>
387
  </div>
388
 
389
- <div id="login-screen">
390
- <div class="login-box">
391
- <div class="login-header" data-i18n="loginTitle">Вход в систему</div>
392
- <form id="login-form" class="login-form-inner">
393
- <div class="form-group">
394
- <label data-i18n="lblProjectUrl">Supabase Project URL</label>
395
- <input type="text" id="supa-url" required placeholder="https://xyz.supabase.co">
396
- </div>
397
- <div class="form-group">
398
- <label data-i18n="lblAnonKey">API Key (Anon)</label>
399
- <input type="password" id="supa-key" required placeholder="eyJh...">
400
- </div>
401
- <div class="divider"></div>
402
- <div class="form-group">
403
- <label data-i18n="lblUsername">Имя пользователя</label>
404
- <input type="text" id="login-user" required placeholder="Логин">
405
- </div>
406
- <div class="form-group">
407
- <label data-i18n="lblPassword">Пароль</label>
408
- <input type="password" id="login-pass" required placeholder="Пароль">
409
- </div>
410
- <button type="submit" class="btn-glossy" data-i18n="btnLogin" style="margin-top: 5px;">Войти</button>
411
-
412
- <div style="text-align: center; margin-top: 10px;">
413
- <button type="button" id="btn-show-setup" class="btn-glossy" style="background: transparent; border: none; color: #286098; box-shadow: none; text-shadow: none; display: inline-flex; align-items: center; gap: 5px; font-weight: normal; font-size: 12px;" data-i18n="btnSetup">
414
- <svg class="icon"><use href="#icon-server"></use></svg> Создать/Обновить сервер
415
- </button>
416
- </div>
417
- </form>
418
  </div>
419
- </div>
420
 
421
- <div id="setup-modal" class="modal-wrapper hidden">
422
- <div class="modal-content" style="max-width: 600px;">
423
- <div class="modal-header">
424
- <span data-i18n="setupModalTitle">Настройка БД Supabase</span>
425
- <button class="close-modal-btn" onclick="document.getElementById('setup-modal').classList.add('hidden')"><svg class="icon"><use href="#icon-close"></use></svg></button>
426
  </div>
427
- <div class="modal-body">
428
- <div class="tabs-header">
429
- <div class="tab-btn active" onclick="switchTab('create')" data-i18n="tabCreate">Создать с нуля</div>
430
- <div class="tab-btn" onclick="switchTab('migrate')" data-i18n="tabMigrate">Миграция (V1 -> V2)</div>
431
- </div>
432
-
433
- <!-- Tab: Create -->
434
- <div id="tab-create">
435
- <p style="font-size: 12px; margin-bottom: 10px; color: #555;" data-i18n="setupCreateDesc">Генератор SQL для создания таблиц с включенным RLS и политиками безопасности.</p>
436
-
437
- <div style="display: flex; gap: 10px; margin-bottom: 10px;">
438
- <div style="flex: 1;">
439
- <label style="font-size: 12px; font-weight: bold;">Название сервера (Канал по умолч.)</label>
440
- <input type="text" id="gen-channel" value="general" style="padding: 4px;">
441
- </div>
442
- </div>
443
-
444
- <button class="btn-glossy" onclick="generateSQL()" style="width: 100%; margin-bottom: 10px;" data-i18n="btnGenSql">Сгенерировать SQL</button>
445
-
446
- <div style="position: relative;">
447
- <textarea id="sql-create-out" style="font-family: monospace; font-size: 11px; height: 180px; white-space: pre;" readonly></textarea>
448
- <button class="btn-glossy" onclick="copyText('sql-create-out')" style="position: absolute; top: 5px; right: 5px; padding: 2px 8px; font-size: 11px;">Copy</button>
449
- </div>
450
- </div>
451
-
452
- <!-- Tab: Migrate -->
453
- <div id="tab-migrate" class="hidden">
454
- <p style="font-size: 12px; margin-bottom: 10px; color: #555;" data-i18n="setupMigDesc">Запустите этот скрипт, если у вас уже есть база данных старой версии. Да��ные не удалятся.</p>
455
-
456
- <div style="position: relative;">
457
- <textarea id="sql-mig-out" style="font-family: monospace; font-size: 11px; height: 200px; white-space: pre;" readonly>
458
- -- 1. Добавление новых колонок для прав
459
- ALTER TABLE public.app_users ADD COLUMN IF NOT EXISTS can_manage_channels BOOLEAN DEFAULT true;
460
-
461
- -- 2. Добавление колонок для сообщений
462
- ALTER TABLE public.messages ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP WITH TIME ZONE;
463
- ALTER TABLE public.messages ADD COLUMN IF NOT EXISTS reply_to UUID REFERENCES public.messages(id) ON DELETE SET NULL;
464
-
465
- -- 3. Включаем RLS если был выключен (на всякий случай)
466
- ALTER TABLE public.app_users ENABLE ROW LEVEL SECURITY;
467
- ALTER TABLE public.channels ENABLE ROW LEVEL SECURITY;
468
- ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
469
-
470
- -- 4. Политики (Разрешаем anon доступ, так как мы доверяем клиенту)
471
- DROP POLICY IF EXISTS "Anon all access" ON public.app_users;
472
- CREATE POLICY "Anon all access" ON public.app_users FOR ALL TO anon USING (true) WITH CHECK (true);
473
-
474
- DROP POLICY IF EXISTS "Anon all access" ON public.channels;
475
- CREATE POLICY "Anon all access" ON public.channels FOR ALL TO anon USING (true) WITH CHECK (true);
476
-
477
- DROP POLICY IF EXISTS "Anon all access" ON public.messages;
478
- CREATE POLICY "Anon all access" ON public.messages FOR ALL TO anon USING (true) WITH CHECK (true);
479
-
480
- GRANT ALL ON ALL TABLES IN SCHEMA public TO anon;
481
- GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO anon;
482
- </textarea>
483
- <button class="btn-glossy" onclick="copyText('sql-mig-out')" style="position: absolute; top: 5px; right: 5px; padding: 2px 8px; font-size: 11px;">Copy</button>
484
- </div>
485
- </div>
486
-
487
  </div>
488
  </div>
489
- </div>
490
 
491
- <div id="profile-modal" class="modal-wrapper hidden">
492
- <div class="modal-content" style="max-width: 300px;">
493
- <div class="modal-header">
494
- <span data-i18n="profileTitle">Мой профиль</span>
495
- <button class="close-modal-btn" onclick="document.getElementById('profile-modal').classList.add('hidden')"><svg class="icon"><use href="#icon-close"></use></svg></button>
496
- </div>
497
- <div class="modal-body" style="text-align: center;">
498
- <div id="profile-avatar-display" style="transform: scale(1.5); margin: 20px auto;"></div>
499
- <h3 id="profile-username-display" style="margin-bottom: 20px;">User</h3>
500
- <button type="button" id="btn-logout" class="btn-glossy btn-danger" style="width: 100%;" data-i18n="btnLogout">Выйти из аккаунта</button>
501
  </div>
502
  </div>
503
  </div>
504
 
505
- <div id="app-screen" class="hidden">
 
 
 
 
 
 
 
 
 
 
506
 
507
- <!-- Левая панель (Каналы) -->
508
- <div class="sidebar" id="sidebar-left">
509
- <div class="sidebar-header">
510
- <span data-i18n="channelsTitle">Каналы</span>
511
- <button id="btn-add-channel" class="icon-btn-small hidden" title="Создать канал" style="background: none; border: none; color: white;"><svg class="icon"><use href="#icon-plus"></use></svg></button>
512
  </div>
513
- <div class="list-container" id="channels-list"></div>
514
- <div class="current-user-panel" id="btn-my-profile">
515
- <div id="my-avatar-container"></div>
516
- <div style="flex: 1; font-weight: bold;" id="my-username-display">Name</div>
517
- <svg class="icon" style="color: #888;"><use href="#icon-edit"></use></svg>
518
  </div>
 
 
519
  </div>
520
 
521
- <!-- Центральная часть (Чат) -->
522
- <div class="main-chat">
523
- <div class="chat-header">
524
- <div style="display: flex; align-items: center; gap: 10px;">
525
- <button class="mobile-btn" onclick="toggleSidebar('sidebar-left')"><svg class="icon-lg"><use href="#icon-menu"></use></svg></button>
526
- <span id="current-channel-name"># select-channel</span>
527
- </div>
528
- <button class="mobile-btn" onclick="toggleSidebar('sidebar-right')"><svg class="icon-lg"><use href="#icon-users"></use></svg></button>
529
  </div>
530
-
531
- <div class="chat-messages" id="messages-container"></div>
532
-
533
- <div class="chat-input-area">
534
- <div id="action-bar" class="action-bar hidden">
535
- <span id="action-text">Действие...</span>
536
- <button class="icon-btn-small" onclick="cancelAction()"><svg class="icon"><use href="#icon-close"></use></svg></button>
537
- </div>
538
- <form id="send-form" class="input-row">
539
- <textarea id="msg-input" required placeholder="Написать сообщение..."></textarea>
540
- <button type="submit" class="btn-glossy" style="padding: 0 15px; display: flex; align-items: center; justify-content: center;">
541
- <svg class="icon"><use href="#icon-send"></use></svg>
542
- </button>
543
- </form>
544
  </div>
 
545
  </div>
 
546
 
547
- <!-- Правая панель (Участники) -->
548
- <div class="right-sidebar" id="sidebar-right">
549
- <div class="sidebar-header" data-i18n="membersTitle">Участники</div>
550
- <div class="list-container" id="members-list"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
551
  </div>
552
-
553
  </div>
554
 
555
  <script>
556
- // Предотвращение ПКМ по всему приложению
557
- document.addEventListener('contextmenu', e => e.preventDefault());
558
-
559
- // Словари переводов
560
- const dict = {
561
- ru: {
562
- loginTitle: "Вход в систему", lblProjectUrl: "Supabase Project URL", lblAnonKey: "API Key (Anon)",
563
- lblUsername: "Имя пользователя", lblPassword: "Пароль", btnLogin: "Войти",
564
- btnSetup: "Создать/Обновить сервер", setupModalTitle: "Настройка БД Supabase",
565
- tabCreate: "Создать с нуля", tabMigrate: "Миграция (V1 -> V2)",
566
- setupCreateDesc: "Генератор SQL для создания таблиц с включенным RLS и политиками безопасности.",
567
- btnGenSql: "Сгенерировать SQL", setupMigDesc: "Запустите этот скрипт, если у вас уже есть база данных старой версии. Данные не удалятся.",
568
- profileTitle: "Мой профиль", btnLogout: "Выйти из аккаунта", channelsTitle: "Каналы",
569
- membersTitle: "Участники", phMessage: "Написать сообщение...",
570
- errUrlKey: "Введите URL и Anon Key!", errCreds: "Введите логин и пароль!",
571
- errLogin: "Ошибка входа. Проверьте данные.", errSrv: "Ошибка соединения",
572
- txtReplyTo: "Ответ на сообщение", txtEdit: "Редактирование", txtDelErr: "Ошибка удаления: "
573
- },
574
- en: {
575
- loginTitle: "System Login", lblProjectUrl: "Supabase Project URL", lblAnonKey: "API Key (Anon)",
576
- lblUsername: "Username", lblPassword: "Password", btnLogin: "Login",
577
- btnSetup: "Create/Update Server", setupModalTitle: "Supabase DB Setup",
578
- tabCreate: "Create from scratch", tabMigrate: "Migration (V1 -> V2)",
579
- setupCreateDesc: "SQL Generator for creating tables with RLS and security policies enabled.",
580
- btnGenSql: "Generate SQL", setupMigDesc: "Run this script if you have an older database version. Data will not be lost.",
581
- profileTitle: "My Profile", btnLogout: "Logout", channelsTitle: "Channels",
582
- membersTitle: "Members", phMessage: "Type a message...",
583
- errUrlKey: "Enter URL and Anon Key!", errCreds: "Enter username and password!",
584
- errLogin: "Login failed. Check credentials.", errSrv: "Connection error",
585
- txtReplyTo: "Replying to", txtEdit: "Editing message", txtDelErr: "Delete error: "
586
  }
587
- };
588
- let lang = 'ru';
589
 
590
- function t(key) { return dict[lang][key] || key; }
591
- function updateTranslations() {
592
- document.querySelectorAll('[data-i18n]').forEach(el => {
593
- el.innerText = t(el.getAttribute('data-i18n'));
594
- });
595
- document.getElementById('msg-input').placeholder = t('phMessage');
596
- }
597
 
598
- document.getElementById('lang-btn').onclick = () => {
599
- lang = lang === 'ru' ? 'en' : 'ru';
600
- document.getElementById('lang-text').innerText = lang === 'ru' ? 'EN' : 'RU';
601
- updateTranslations();
602
- };
603
 
604
- // Утилиты генерации цветов и аватарок
605
- function stringToColor(str) {
606
- let hash = 0; for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash);
607
- return `hsl(${hash % 360}, 65%, 45%)`;
608
- }
 
 
 
 
609
 
610
- function createAvatar(user) {
611
- const wrap = document.createElement('div'); wrap.className = 'avatar-wrap';
612
- const av = document.createElement('div'); av.className = 'avatar';
613
- const name = user && user.username ? user.username : '?';
614
- av.style.backgroundColor = stringToColor(name);
615
- av.innerText = name.substring(0, 2).toUpperCase();
616
- wrap.appendChild(av);
617
-
618
- if (user && 'is_online' in user) {
619
- const dot = document.createElement('div');
620
- dot.className = `status-dot ${user.is_online ? '' : 'offline'}`;
621
- wrap.appendChild(dot);
622
  }
623
- return wrap;
624
  }
625
 
626
- function escapeHTML(str) { return str.replace(/[&<>'"]/g, tag => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' }[tag])); }
 
627
 
628
- function parseMarkdown(text) {
629
- let html = escapeHTML(text);
630
- html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>'); // bold
631
- html = html.replace(/\*(.*?)\*/g, '<em>$1</em>'); // italic
632
- html = html.replace(/```([\s\S]*?)```/g, '<pre>$1</pre>'); // code block
633
- html = html.replace(/`([^`]+)`/g, '<code>$1</code>'); // inline code
634
- html = html.replace(/@(\w+)/g, '<span class="mention">@$1</span>'); // mentions
635
- return html.replace(/\n/g, '<br>');
 
636
  }
637
 
638
- function copyText(id) {
639
- const el = document.getElementById(id); el.select(); document.execCommand('copy');
640
  }
641
 
642
- class SupabaseREST {
643
- constructor(url, key) {
644
- this.url = url.replace(/\/$/, ''); this.key = key;
645
- }
646
- async fetchApi(endpoint, options = {}) {
647
- const headers = { 'apikey': this.key, 'Authorization': `Bearer ${this.key}`, 'Content-Type': 'application/json', 'Prefer': 'return=representation' };
648
- if (options.headers) Object.assign(headers, options.headers);
649
-
650
- try {
651
- const res = await fetch(`${this.url}/rest/v1${endpoint}`, { ...options, headers });
652
- if (!res.ok) {
653
- const errText = await res.text();
654
- throw new Error(`HTTP ${res.status}: ${errText}`);
655
- }
656
- if (res.status !== 204) return await res.json();
657
- return null;
658
- } catch(e) {
659
- console.error("API Error:", e);
660
- throw e;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661
  }
 
 
 
 
 
 
662
  }
 
663
 
664
- async getUsers() { return await this.fetchApi('/app_users?select=*'); }
665
- async createUser(username, password) { return await this.fetchApi('/app_users', { method: 'POST', body: JSON.stringify({ username, password, is_online: true }) }); }
666
- async updateUser(id, data) { return await this.fetchApi(`/app_users?id=eq.${id}`, { method: 'PATCH', body: JSON.stringify(data) }); }
667
- async setOnline(id, status) { return await this.updateUser(id, { is_online: status, last_seen: new Date().toISOString() }); }
668
-
669
- async getChannels() { return await this.fetchApi('/channels?select=*&order=created_at.asc'); }
670
- async createChannel(name) { return await this.fetchApi('/channels', { method: 'POST', body: JSON.stringify({ name }) }); }
671
- async deleteChannel(id) { return await this.fetchApi(`/channels?id=eq.${id}`, { method: 'DELETE' }); }
672
 
673
- async getMessages(channelId) { return await this.fetchApi(`/messages?channel_id=eq.${channelId}&select=*,app_users!inner(username)&order=created_at.asc`); }
674
- async getMessageById(id) {
675
- const data = await this.fetchApi(`/messages?id=eq.${id}&select=*,app_users!inner(username)`);
676
- return data && data.length > 0 ? data[0] : null;
677
  }
678
- async sendMessage(channelId, userId, content, replyToId) {
679
- const payload = { channel_id: channelId, user_id: userId, content: content };
680
- if (replyToId) payload.reply_to = replyToId;
681
- return await this.fetchApi('/messages', { method: 'POST', body: JSON.stringify(payload) });
 
 
 
 
 
 
 
 
 
 
 
 
 
682
  }
683
- async updateMessage(id, content) { return await this.fetchApi(`/messages?id=eq.${id}`, { method: 'PATCH', body: JSON.stringify({ content, updated_at: new Date().toISOString() }) }); }
684
- async deleteMessage(id) { return await this.fetchApi(`/messages?id=eq.${id}`, { method: 'DELETE' }); }
685
  }
686
 
687
- let db = null;
688
- let state = {
689
- user: null, currentChannel: null, users: new Map(), channels: [], messages: [],
690
- action: { type: null, msgId: null }, pollTimer: null
691
- };
692
 
693
- const els = {
694
- loginScrn: document.getElementById('login-screen'), appScrn: document.getElementById('app-screen'),
695
- url: document.getElementById('supa-url'), key: document.getElementById('supa-key'),
696
- user: document.getElementById('login-user'), pass: document.getElementById('login-pass'),
697
- chList: document.getElementById('channels-list'), memList: document.getElementById('members-list'),
698
- msgCont: document.getElementById('messages-container'), chName: document.getElementById('current-channel-name'),
699
- msgInput: document.getElementById('msg-input'), sendForm: document.getElementById('send-form'),
700
- actionBar: document.getElementById('action-bar'), actionText: document.getElementById('action-text'),
701
- btnAddCh: document.getElementById('btn-add-channel')
702
- };
703
 
704
- window.onload = () => {
705
- updateTranslations();
706
- const savedUrl = localStorage.getItem('s_url');
707
- const savedKey = localStorage.getItem('s_key');
708
- const savedUser = localStorage.getItem('s_user');
709
-
710
- if (savedUrl && savedKey) { els.url.value = savedUrl; els.key.value = savedKey; }
711
- if (savedUser) {
712
- try {
713
- const u = JSON.parse(savedUser);
714
- els.user.value = u.username;
715
- // Auto login if we have a session
716
- if(localStorage.getItem('s_session')) {
717
- initDBAndLogin(savedUrl, savedKey, u.username, u.password, true);
718
  }
719
- } catch(e){}
 
 
 
 
 
720
  }
721
- };
722
 
723
- document.getElementById('login-form').onsubmit = async (e) => {
724
- e.preventDefault();
725
- const url = els.url.value.trim(), key = els.key.value.trim();
726
- const user = els.user.value.trim(), pass = els.pass.value;
727
- if(!url || !key) return showError(t('errUrlKey'));
728
- if(!user || !pass) return showError(t('errCreds'));
729
-
730
- localStorage.setItem('s_url', url); localStorage.setItem('s_key', key);
731
- await initDBAndLogin(url, key, user, pass, false);
732
- };
733
 
734
- async function initDBAndLogin(url, key, username, password, isAuto) {
735
- db = new SupabaseREST(url, key);
736
  try {
737
- let users = await db.getUsers();
738
- let u = users.find(x => x.username === username);
739
- if (!u) {
740
- // Create user
741
- const res = await db.createUser(username, password);
742
- u = res[0];
743
- } else if (u.password !== password) {
744
- throw new Error("Wrong password");
745
  }
746
-
747
- await db.setOnline(u.id, true);
748
- completeLogin(u);
749
- } catch (err) {
750
- if(!isAuto) showError(t('errLogin') + " " + err.message);
751
- else { localStorage.removeItem('s_session'); els.loginScrn.classList.remove('hidden'); els.appScrn.classList.add('hidden'); }
752
  }
753
  }
754
 
755
- function completeLogin(u) {
756
- state.user = u;
757
- localStorage.setItem('s_user', JSON.stringify(u));
758
- localStorage.setItem('s_session', 'active');
759
 
760
- document.getElementById('my-username-display').innerText = u.username;
761
- const myAv = document.getElementById('my-avatar-container');
762
- myAv.innerHTML = ''; myAv.appendChild(createAvatar(u));
763
 
764
- if(u.can_manage_channels) els.btnAddCh.classList.remove('hidden');
765
-
766
- els.loginScrn.classList.add('hidden'); els.appScrn.classList.remove('hidden');
767
- loadData();
768
- state.pollTimer = setInterval(pollData, 3000);
769
  }
770
 
771
- document.getElementById('btn-logout').onclick = async () => {
772
- if(state.user && db) { try { await db.setOnline(state.user.id, false); }catch(e){} }
773
- clearInterval(state.pollTimer);
774
- localStorage.removeItem('s_session');
775
- window.location.reload();
776
- };
777
 
778
- async function loadData() {
779
  try {
780
- const users = await db.getUsers();
781
- state.users.clear(); users.forEach(u => state.users.set(u.id, u));
782
- renderMembers();
783
-
784
- state.channels = await db.getChannels();
785
- renderChannels();
786
-
787
- if (state.channels.length > 0 && !state.currentChannel) selectChannel(state.channels[0]);
788
- else if (state.currentChannel) refreshMessages();
789
- } catch(e) { console.error(e); }
790
- }
791
- async function pollData() {
792
- if(!document.hidden) await loadData();
793
- }
794
-
795
- function renderMembers() {
796
- els.memList.innerHTML = '';
797
- Array.from(state.users.values()).sort((a,b) => b.is_online - a.is_online).forEach(u => {
798
- const div = document.createElement('div'); div.className = 'member-item';
799
- div.appendChild(createAvatar(u));
800
- const span = document.createElement('span'); span.innerText = u.username;
801
- div.appendChild(span);
802
- els.memList.appendChild(div);
803
- });
804
  }
805
 
806
  function renderChannels() {
807
- els.chList.innerHTML = '';
808
- state.channels.forEach(ch => {
 
809
  const div = document.createElement('div');
810
- div.className = `channel-item ${state.currentChannel && state.currentChannel.id === ch.id ? 'active' : ''}`;
811
- div.innerHTML = `<span style="flex:1;"># ${ch.name}</span>`;
812
-
813
- if (state.user && state.user.can_manage_channels) {
814
- const del = document.createElement('button'); del.className = 'icon-btn-small';
815
- del.innerHTML = '<svg class="icon"><use href="#icon-trash"></use></svg>';
816
- del.onclick = async (e) => { e.stopPropagation(); try{ await db.deleteChannel(ch.id); loadData();}catch(err){} };
817
- div.appendChild(del);
818
  }
819
-
820
- div.onclick = () => { selectChannel(ch); toggleSidebar('sidebar-left'); };
821
- els.chList.appendChild(div);
822
  });
823
  }
824
 
825
- function selectChannel(ch) {
826
- state.currentChannel = ch;
827
- els.chName.innerText = `# ${ch.name}`;
828
- renderChannels();
829
- refreshMessages();
 
 
 
 
 
 
830
  }
831
 
832
- async function refreshMessages() {
833
- if(!state.currentChannel) return;
 
834
  try {
835
- state.messages = await db.getMessages(state.currentChannel.id);
836
- renderMessages();
 
837
  } catch(e) {}
838
  }
839
 
840
- function renderMessages() {
841
- els.msgCont.innerHTML = '';
842
- state.messages.forEach(msg => {
843
- const isMine = msg.user_id === state.user.id;
844
- const row = document.createElement('div'); row.className = `message-row ${isMine ? 'mine' : 'other'}`;
845
-
846
- const bub = document.createElement('div'); bub.className = 'message-bubble';
847
-
848
- // Заголовок с действиями
849
- const head = document.createElement('div'); head.className = 'message-header';
850
-
851
- const authorInfo = document.createElement('div');
852
- authorInfo.innerHTML = `<span class="message-author">${msg.app_users.username}</span><span class="message-time">${new Date(msg.created_at).toLocaleTimeString([],{hour:'2-digit', minute:'2-digit'})}</span>${msg.updated_at ? '<span class="message-edited">(изм)</span>' : ''}`;
853
- head.appendChild(authorInfo);
854
-
855
- const acts = document.createElement('div'); acts.className = 'message-actions';
856
-
857
- const btnReply = document.createElement('button'); btnReply.className = 'icon-btn-small'; btnReply.title = 'Reply';
858
- btnReply.innerHTML = '<svg class="icon"><use href="#icon-reply"></use></svg>';
859
- btnReply.onclick = () => setAction('reply', msg.id, msg.app_users.username, msg.content);
860
- acts.appendChild(btnReply);
861
-
862
- if (isMine) {
863
- const btnEdit = document.createElement('button'); btnEdit.className = 'icon-btn-small'; btnEdit.title = 'Edit';
864
- btnEdit.innerHTML = '<svg class="icon"><use href="#icon-edit"></use></svg>';
865
- btnEdit.onclick = () => setAction('edit', msg.id, null, msg.content);
866
- acts.appendChild(btnEdit);
867
-
868
- const btnDel = document.createElement('button'); btnDel.className = 'icon-btn-small'; btnDel.title = 'Delete';
869
- btnDel.innerHTML = '<svg class="icon"><use href="#icon-trash"></use></svg>';
870
- btnDel.onclick = async () => {
871
- try { await db.deleteMessage(msg.id); refreshMessages(); }
872
- catch(e) { showError(t('txtDelErr') + e.message); }
873
- };
874
- acts.appendChild(btnDel);
875
- }
876
-
877
- head.appendChild(acts);
878
- bub.appendChild(head);
879
-
880
- // Отрисовка цитаты
881
- if (msg.reply_to) {
882
- const repMsg = state.messages.find(m => m.id === msg.reply_to);
883
- const q = document.createElement('div'); q.className = 'reply-quote';
884
- if (repMsg) {
885
- q.innerHTML = `<strong>${repMsg.app_users.username}:</strong> ${escapeHTML(repMsg.content).substring(0, 40)}...`;
886
- } else {
887
- q.innerText = "Сообщение удалено";
888
- }
889
- bub.appendChild(q);
890
  }
 
 
 
891
 
892
- const content = document.createElement('div'); content.className = 'message-content';
893
- content.innerHTML = parseMarkdown(msg.content);
894
- bub.appendChild(content);
 
 
 
 
895
 
896
- row.appendChild(bub);
897
- els.msgCont.appendChild(row);
 
 
898
  });
899
- els.msgCont.scrollTop = els.msgCont.scrollHeight;
900
  }
901
 
902
- els.msgInput.addEventListener('keydown', (e) => {
903
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); els.sendForm.dispatchEvent(new Event('submit')); }
904
- });
 
 
 
 
 
 
905
 
906
- els.sendForm.onsubmit = async (e) => {
907
- e.preventDefault();
908
- const txt = els.msgInput.value.trim();
909
- if (!txt || !state.currentChannel) return;
910
-
911
  try {
912
- if (state.action.type === 'edit') {
913
- await db.updateMessage(state.action.msgId, txt);
914
- } else {
915
- const replyId = state.action.type === 'reply' ? state.action.msgId : null;
916
- await db.sendMessage(state.currentChannel.id, state.user.id, txt, replyId);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
917
  }
918
- els.msgInput.value = '';
919
- cancelAction();
920
- refreshMessages();
921
- } catch (e) {
922
- showError("Error: " + e.message);
923
- }
924
- };
925
-
926
- function setAction(type, id, username, text) {
927
- state.action = { type, msgId: id };
928
- els.actionBar.classList.remove('hidden');
929
- if (type === 'reply') {
930
- els.actionText.innerHTML = `<strong>${t('txtReplyTo')} ${username}:</strong> ${escapeHTML(text).substring(0,30)}...`;
931
- els.actionBar.style.background = '#e8f4ff'; els.actionBar.style.borderColor = '#a9cceb'; els.actionBar.style.color = '#286098';
932
- els.msgInput.focus();
933
- } else if (type === 'edit') {
934
- els.actionText.innerHTML = `<strong>${t('txtEdit')}</strong>`;
935
- els.actionBar.style.background = '#fff8c4'; els.actionBar.style.borderColor = '#f2c779'; els.actionBar.style.color = '#8a6d3b';
936
- els.msgInput.value = text;
937
- els.msgInput.focus();
938
- }
939
- }
940
- function cancelAction() {
941
- state.action = { type: null, msgId: null };
942
- els.actionBar.classList.add('hidden');
943
- if(state.action.type === 'edit') els.msgInput.value = '';
944
- }
945
- function showError(msg) {
946
- els.actionText.innerText = msg;
947
- els.actionBar.classList.remove('hidden');
948
- els.actionBar.style.background = '#f2dede'; els.actionBar.style.borderColor = '#ebccd1'; els.actionBar.style.color = '#a94442';
949
- setTimeout(cancelAction, 8000);
950
  }
951
 
952
- function toggleSidebar(id) {
953
- const el = document.getElementById(id);
954
- if(el.classList.contains('open')) el.classList.remove('open');
955
- else {
956
- document.getElementById('sidebar-left').classList.remove('open');
957
- document.getElementById('sidebar-right').classList.remove('open');
958
- el.classList.add('open');
959
- }
960
  }
961
 
962
- document.getElementById('btn-show-setup').onclick = () => document.getElementById('setup-modal').classList.remove('hidden');
963
- document.getElementById('btn-my-profile').onclick = () => document.getElementById('profile-modal').classList.remove('hidden');
964
-
965
- els.btnAddCh.onclick = async () => {
966
- const name = prompt("Название канала:");
967
- if(name && name.trim()) {
968
- try { await db.createChannel(name.trim().toLowerCase().replace(/\s+/g,'-')); loadData(); } catch(e){ showError(e.message); }
 
 
 
 
 
 
 
 
 
 
 
 
 
969
  }
970
- };
971
 
972
- function switchTab(tabId) {
973
- document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
974
- document.getElementById('tab-create').classList.add('hidden');
975
- document.getElementById('tab-migrate').classList.add('hidden');
976
 
977
- event.target.classList.add('active');
978
- document.getElementById(`tab-${tabId}`).classList.remove('hidden');
 
 
 
979
  }
980
 
981
- function generateSQL() {
982
- const defCh = document.getElementById('gen-channel').value.trim() || 'general';
983
- const sql = `-- Supabase Messenger Setup SQL
984
- -- Выполните этот скрипт в SQL Editor
985
-
986
- -- 1. Таблица Пользователей
987
- CREATE TABLE public.app_users (
988
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
989
- username TEXT UNIQUE NOT NULL,
990
- password TEXT NOT NULL,
991
- is_online BOOLEAN DEFAULT false,
992
- last_seen TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
993
- can_manage_channels BOOLEAN DEFAULT true,
994
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
995
- );
996
-
997
- -- 2. Таблица Каналов
998
- CREATE TABLE public.channels (
999
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
1000
- name TEXT UNIQUE NOT NULL,
1001
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
1002
- );
1003
-
1004
- -- 3. Таблица Сообщений
1005
- CREATE TABLE public.messages (
1006
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
1007
- channel_id UUID REFERENCES public.channels(id) ON DELETE CASCADE NOT NULL,
1008
- user_id UUID REFERENCES public.app_users(id) ON DELETE CASCADE NOT NULL,
1009
- content TEXT NOT NULL,
1010
- reply_to UUID REFERENCES public.messages(id) ON DELETE SET NULL,
1011
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
1012
- updated_at TIMESTAMP WITH TIME ZONE
1013
- );
1014
-
1015
- -- Включаем RLS
1016
- ALTER TABLE public.app_users ENABLE ROW LEVEL SECURITY;
1017
- ALTER TABLE public.channels ENABLE ROW LEVEL SECURITY;
1018
- ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
1019
-
1020
- -- Политики (разрешаем клиенту управлять, т.к. auth на клиенте)
1021
- CREATE POLICY "Anon all access" ON public.app_users FOR ALL TO anon USING (true) WITH CHECK (true);
1022
- CREATE POLICY "Anon all access" ON public.channels FOR ALL TO anon USING (true) WITH CHECK (true);
1023
- CREATE POLICY "Anon all access" ON public.messages FOR ALL TO anon USING (true) WITH CHECK (true);
1024
-
1025
- GRANT ALL ON ALL TABLES IN SCHEMA public TO anon;
1026
- GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO anon;
1027
 
1028
- -- Базовый канал
1029
- INSERT INTO public.channels (name) VALUES ('${defCh}');
1030
- `;
1031
- document.getElementById('sql-create-out').value = sql;
1032
- }
1033
-
1034
- // Генерация при открытии
1035
- generateSQL();
1036
  </script>
1037
  </body>
1038
  </html>
 
2
  <html lang="ru">
3
  <head>
4
  <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>WebIRC 2010 - SQL Edition</title>
7
  <style>
8
+ /* Стили в духе 2010-х годов (Windows 7 Aero / Старые мессенджеры) */
9
  :root {
10
+ --bg-color: #d8e6f3;
11
+ --grad-top: #e4eff8;
12
+ --grad-bot: #b8d4eb;
13
+ --border-color: #799aab;
14
+ --text-dark: #1e395b;
15
+ --win-bg: #f4f7f9;
16
+ --menubar-top: #6ba2d4;
17
+ --menubar-bot: #3371b6;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  }
19
 
20
  * {
21
  box-sizing: border-box;
22
+ user-select: none;
 
 
23
  }
24
+
25
  body {
26
+ margin: 0;
27
+ padding: 0;
28
+ font-family: Tahoma, Verdana, Arial, sans-serif;
29
+ font-size: 13px;
30
+ background-color: var(--bg-color);
31
+ color: var(--text-dark);
32
  height: 100vh;
33
  display: flex;
34
  flex-direction: column;
35
  overflow: hidden;
 
36
  }
37
 
38
+ .menubar {
39
+ background: linear-gradient(to bottom, var(--menubar-top) 0%, var(--menubar-bot) 100%);
40
+ border-bottom: 1px solid #14406f;
41
+ padding: 5px 10px;
42
+ display: flex;
43
+ gap: 10px;
44
+ box-shadow: 0 2px 5px rgba(0,0,0,0.2);
45
+ z-index: 100;
46
  }
47
 
48
+ .btn {
49
+ background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 50%, #b5c6d0 51%, #e0eff9 100%);
50
+ border: 1px solid var(--border-color);
51
+ border-radius: 3px;
52
+ padding: 4px 12px;
53
+ color: #0f2c4c;
54
+ font-family: Tahoma, sans-serif;
55
+ font-size: 12px;
56
  cursor: pointer;
57
+ box-shadow: inset 1px 1px 1px rgba(255,255,255,0.8), 1px 1px 2px rgba(0,0,0,0.1);
58
+ text-shadow: 1px 1px 0px rgba(255,255,255,0.5);
59
+ transition: all 0.1s;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  }
61
 
62
+ .btn:hover {
63
+ background: linear-gradient(to bottom, #fff 0%, #eef3f7 50%, #d4e3ef 51%, #f0f7fb 100%);
 
 
 
 
 
 
 
 
 
 
 
 
64
  }
65
 
66
+ .btn:active {
67
+ background: linear-gradient(to bottom, #b5c6d0 0%, #d8e1e7 100%);
68
+ box-shadow: inset 1px 1px 3px rgba(0,0,0,0.3);
69
+ padding-top: 5px;
70
+ padding-bottom: 3px;
71
+ }
72
 
73
+ .window {
74
+ position: absolute;
75
+ width: 350px;
76
+ background: var(--win-bg);
77
+ border: 1px solid var(--border-color);
78
+ border-radius: 4px;
79
+ box-shadow: 3px 3px 10px rgba(0,0,0,0.4);
80
+ display: none;
81
  z-index: 1000;
82
+ flex-direction: column;
83
+ overflow: hidden;
84
  }
85
+
86
+ .window.active {
87
+ display: flex;
 
 
 
 
 
 
 
88
  }
89
+
90
+ .window-header {
91
+ background: linear-gradient(to bottom, #d4e4ef 0%, #86aecc 100%);
92
+ padding: 5px 8px;
 
93
  font-weight: bold;
94
+ color: #0f2c4c;
95
+ border-bottom: 1px solid var(--border-color);
96
+ cursor: move;
97
+ display: flex;
98
+ justify-content: space-between;
99
+ align-items: center;
100
+ border-radius: 3px 3px 0 0;
101
+ text-shadow: 1px 1px 0px rgba(255,255,255,0.5);
102
+ }
103
+
104
+ .window-close {
105
+ background: linear-gradient(to bottom, #e8a2a2 0%, #cc3333 100%);
106
+ border: 1px solid #7a1c1c;
107
+ color: white;
108
+ font-weight: bold;
109
+ width: 18px;
110
+ height: 18px;
111
+ line-height: 14px;
112
+ text-align: center;
113
+ cursor: pointer;
114
+ border-radius: 2px;
115
+ font-size: 10px;
116
+ box-shadow: inset 1px 1px 1px rgba(255,255,255,0.4);
117
  }
118
+
119
+ .window-close:hover {
120
+ background: linear-gradient(to bottom, #ffb3b3 0%, #ff4d4d 100%);
121
+ }
122
+
123
+ .window-body {
124
  padding: 15px;
125
+ display: flex;
126
+ flex-direction: column;
127
+ gap: 10px;
128
+ min-height: 0;
129
  }
130
+
131
+ .input-group {
132
+ display: flex;
133
+ flex-direction: column;
134
+ gap: 3px;
135
  }
 
136
 
137
+ input[type="text"], input[type="password"] {
138
+ border: 1px solid #999;
139
+ box-shadow: inset 1px 1px 2px #ccc;
140
+ padding: 5px;
141
+ border-radius: 2px;
142
+ font-family: Tahoma, sans-serif;
143
+ user-select: text;
144
  }
145
+
146
+ .workspace {
147
+ flex: 1;
148
+ display: flex;
149
+ padding: 5px;
150
+ gap: 5px;
151
+ height: calc(100vh - 35px);
152
+ }
153
+
154
+ .panel {
155
+ background: white;
156
  border: 1px solid var(--border-color);
157
+ border-radius: 2px;
158
+ box-shadow: inset 1px 1px 3px rgba(0,0,0,0.1);
159
+ display: flex;
160
+ flex-direction: column;
161
  }
162
+
163
+ .panel-header {
164
+ background: linear-gradient(to bottom, #f2f6f8 0%, #d8e1e7 100%);
165
  border-bottom: 1px solid var(--border-color);
166
+ padding: 4px 8px;
 
 
167
  font-weight: bold;
168
+ font-size: 11px;
169
+ color: #555;
 
 
 
 
 
 
 
 
 
170
  }
171
 
172
  .sidebar {
173
+ width: 200px;
 
 
 
174
  flex-shrink: 0;
 
175
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
+ .chat-area {
178
+ flex: 1;
179
+ display: flex;
180
+ flex-direction: column;
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  }
182
+
183
  .chat-messages {
184
+ flex: 1;
185
+ padding: 10px;
186
+ overflow-y: auto;
187
+ user-select: text;
188
+ display: flex;
189
+ flex-direction: column;
190
+ gap: 5px;
191
  }
192
 
193
+ .chat-input-area {
194
+ border-top: 1px solid var(--border-color);
195
+ padding: 5px;
196
+ display: flex;
197
+ gap: 5px;
198
+ background: #f4f7f9;
 
199
  }
200
+
201
+ .chat-input-area input {
202
+ flex: 1;
 
203
  }
204
+
205
+ .list-item {
206
+ padding: 4px 8px;
207
+ cursor: pointer;
208
+ border-bottom: 1px solid #eee;
209
+ display: flex;
210
+ justify-content: space-between;
211
  }
212
 
213
+ .list-item:hover {
214
+ background-color: #e4eff8;
 
215
  }
 
 
 
 
 
 
216
 
217
+ .list-item.active {
218
+ background-color: #3371b6;
219
+ color: white;
 
 
 
 
220
  }
 
221
 
222
+ .msg { font-family: Verdana, sans-serif; font-size: 12px; }
223
+ .msg .time { color: #888; font-size: 10px; margin-right: 5px; }
224
+ .msg .author { font-weight: bold; color: #1e5799; margin-right: 5px; }
225
+ .msg.system .author { color: #cc3333; }
 
 
 
 
 
 
 
226
 
227
+ .mobile-tabs {
228
+ display: none;
229
+ background: linear-gradient(to bottom, var(--menubar-top) 0%, var(--menubar-bot) 100%);
230
+ padding: 5px;
231
+ gap: 5px;
 
 
 
 
 
 
 
 
 
232
  }
233
 
234
+ .mobile-tabs .btn { flex: 1; }
 
 
 
 
 
235
 
236
  @media (max-width: 768px) {
237
+ .workspace { flex-direction: column; gap: 0; padding: 0; height: calc(100vh - 70px); }
238
+ .sidebar { width: 100%; height: 100%; display: none; border: none; }
239
+ .chat-area { display: none; border: none; height: 100%; }
240
+ .mobile-tabs { display: flex; }
 
 
 
241
 
242
+ /* Logic for mobile tabs */
243
+ .workspace[data-tab="channels"] .sidebar-left { display: flex; }
244
+ .workspace[data-tab="chat"] .chat-area { display: flex; }
245
+ .workspace[data-tab="users"] .sidebar-right { display: flex; }
246
+
247
+ .window { width: 90%; left: 5% !important; top: 10% !important; }
 
 
248
  }
249
+
250
+ /* Утилиты */
251
+ .hidden { display: none !important; }
252
+ #docx-window { width: 600px; max-width: 95vw; height: 400px; max-height: 90vh; }
253
+ #docx-content { overflow-y: auto; flex: 1; user-select: text; font-family: monospace; white-space: pre-wrap; font-size: 12px; padding: 10px; background: white;}
254
  </style>
255
  </head>
256
  <body>
257
 
258
+ <div class="menubar">
259
+ <button class="btn" onclick="openWindow('connect-window')">🔌 Подключиться</button>
260
+ <button class="btn" onclick="openWindow('docx-window')">📄 DOCX / FAQ (Настройка БД)</button>
261
+ <div style="flex:1"></div>
262
+ <div id="user-status" style="color: white; line-height: 24px; text-shadow: 1px 1px 1px #000; font-weight: bold;">Не подключен</div>
 
 
 
 
 
 
 
 
 
 
 
 
263
  </div>
264
 
265
+ <div class="workspace" data-tab="chat">
266
+ <!-- Левая колонка: Каналы -->
267
+ <div class="panel sidebar sidebar-left">
268
+ <div class="panel-header">Каналы</div>
269
+ <div id="channels-list" style="overflow-y: auto; flex: 1;">
270
+ <div style="padding: 10px; color: #888;">Подключитесь для загрузки...</div>
271
+ </div>
272
+ <div style="padding: 5px; border-top: 1px solid var(--border-color); background: #f4f7f9; display: flex; gap:2px;">
273
+ <input type="text" id="new-channel-name" placeholder="Имя канала" style="width: 100px;">
274
+ <button class="btn" onclick="createChannel()" style="flex:1">+</button>
275
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  </div>
 
277
 
278
+ <!-- Центральная колонка: Чат -->
279
+ <div class="panel chat-area">
280
+ <div class="panel-header" id="chat-title">Чат</div>
281
+ <div class="chat-messages" id="messages-list">
282
+ <div style="color: #999; text-align: center; margin-top: 20px;">Ожидание подключения к серверу...</div>
283
  </div>
284
+ <div class="chat-input-area">
285
+ <input type="text" id="msg-input" placeholder="Введите сообщение..." onkeypress="handleEnter(event)">
286
+ <button class="btn" onclick="sendMessage()">Отправить</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  </div>
288
  </div>
 
289
 
290
+ <!-- Правая колонка: Пользователи -->
291
+ <div class="panel sidebar sidebar-right">
292
+ <div class="panel-header">Пользователи</div>
293
+ <div id="users-list" style="overflow-y: auto; flex: 1;">
294
+ <div style="padding: 10px; color: #888;">Пусто</div>
 
 
 
 
 
295
  </div>
296
  </div>
297
  </div>
298
 
299
+ <div class="mobile-tabs">
300
+ <button class="btn" onclick="setMobileTab('channels')">Каналы</button>
301
+ <button class="btn" onclick="setMobileTab('chat')">Чат</button>
302
+ <button class="btn" onclick="setMobileTab('users')">Люди</button>
303
+ </div>
304
+
305
+ <div id="connect-window" class="window" style="top: 100px; left: 100px;">
306
+ <div class="window-header">
307
+ <span>⚙️ Настройки подключения</span>
308
+ <div class="window-close" onclick="closeWindow('connect-window')">X</div>
309
+ </div>
310
 
311
+ <!-- Шаг 1: Проверка Supabase -->
312
+ <div class="window-body" id="connect-step-1">
313
+ <div class="input-group">
314
+ <label>Supabase Project URL:</label>
315
+ <input type="text" id="supa-url" placeholder="https://xxxx.supabase.co" value="">
316
  </div>
317
+ <div class="input-group">
318
+ <label>Anon Key:</label>
319
+ <input type="password" id="supa-key" placeholder="eyJhbGciOiJIUzI1NiIsInR5c...">
 
 
320
  </div>
321
+ <button class="btn" style="margin-top: 10px;" onclick="checkConnection()">Check (Проверить)</button>
322
+ <div id="connect-error" style="color: red; font-size: 11px; margin-top: 5px;"></div>
323
  </div>
324
 
325
+ <!-- Шаг 2: Авторизация -->
326
+ <div class="window-body hidden" id="connect-step-2">
327
+ <div style="color: green; font-size: 11px; margin-bottom: 10px;">✅ Сервер доступен!</div>
328
+ <div class="input-group">
329
+ <label>Имя пользователя (Ник):</label>
330
+ <input type="text" id="auth-user" placeholder="Например: admin">
 
 
331
  </div>
332
+ <div class="input-group">
333
+ <label>Пароль (Пинкод):</label>
334
+ <input type="password" id="auth-pass" placeholder="***">
335
+ </div>
336
+ <div style="display: flex; gap: 10px; margin-top: 10px;">
337
+ <button class="btn" style="flex:1" onclick="login()">Вход</button>
338
+ <button class="btn" style="flex:1" onclick="register()">Регистрация</button>
 
 
 
 
 
 
 
339
  </div>
340
+ <div id="auth-error" style="color: red; font-size: 11px; margin-top: 5px;"></div>
341
  </div>
342
+ </div>
343
 
344
+ <div id="docx-window" class="window" style="top: 50px; left: 50px;">
345
+ <div class="window-header">
346
+ <span>📄 DOCX - Руководство по настройке Supabase</span>
347
+ <div class="window-close" onclick="closeWindow('docx-window')">X</div>
348
+ </div>
349
+ <div class="window-body" style="padding: 0; flex: 1; display: flex; flex-direction: column; min-height: 0;">
350
+ <div id="docx-content">
351
+ = ПОДГОТОВКА БАЗЫ ДАННЫХ (SUPABASE SQL SETUP) =
352
+
353
+ Чтобы этот IRC клиент работал, вам нужно создать проект на Supabase.com, зайти в SQL Editor и выполнить следующий скрипт. Мы не используем библиотеки, только чистый REST API!
354
+
355
+ --- СКОПИРУЙТЕ И ВЫПОЛНИТЕ ЭТОТ SQL ---
356
+
357
+ -- 1. Таблица пользователей
358
+ CREATE TABLE users (
359
+ id SERIAL PRIMARY KEY,
360
+ username TEXT UNIQUE NOT NULL,
361
+ password TEXT NOT NULL,
362
+ role TEXT DEFAULT 'user' -- 'admin' или 'user', 'banned'
363
+ );
364
+
365
+ -- 2. Таблица каналов
366
+ CREATE TABLE channels (
367
+ id SERIAL PRIMARY KEY,
368
+ name TEXT UNIQUE NOT NULL
369
+ );
370
+
371
+ -- 3. Таблица сообщений
372
+ CREATE TABLE messages (
373
+ id SERIAL PRIMARY KEY,
374
+ channel_id INTEGER REFERENCES channels(id) ON DELETE CASCADE,
375
+ user_id INTEGER REFERENCES users(id),
376
+ content TEXT NOT NULL,
377
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
378
+ );
379
+
380
+ -- 4. Базовые данные (Создаем канал по умолчанию)
381
+ INSERT INTO channels (name) VALUES ('general');
382
+
383
+ -- 5. Политики безопасности (ОЧЕНЬ ВАЖНО ДЛЯ REST API)
384
+ -- Так как мы обращаемся к REST API с Anon Key, нам нужно разрешить доступ.
385
+ -- В рамках "old school" клиента мы просто разрешаем всё для всех (не для продакшена!).
386
+ ALTER TABLE users ENABLE ROW LEVEL SECURITY;
387
+ ALTER TABLE channels ENABLE ROW LEVEL SECURITY;
388
+ ALTER TABLE messages ENABLE ROW LEVEL SECURITY;
389
+
390
+ CREATE POLICY "Allow all users" ON users FOR ALL USING (true);
391
+ CREATE POLICY "Allow all channels" ON channels FOR ALL USING (true);
392
+ CREATE POLICY "Allow all messages" ON messages FOR ALL USING (true);
393
+
394
+ ---------------------------------------------------
395
+
396
+ = FAQ =
397
+ В: Почему "без CDN"?
398
+ О: Мы обращаемся напрямую к REST API Supabase (через встроенный fetch). Никаких сторонних .js скриптов не загружается. Полная автономность файла!
399
+
400
+ В: Как забанить пользователя?
401
+ О: Если вы зарегистрируетесь, и вручную в БД поменяете свой 'role' на 'admin', вы сможете банить (менять role другого на 'banned'). Интерфейс попытается это сделать через API.
402
+ </div>
403
  </div>
 
404
  </div>
405
 
406
  <script>
407
+ // --- 1. Логика перетаскивания окон ---
408
+ function makeDraggable(el) {
409
+ let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
410
+ const header = el.querySelector('.window-header');
411
+ if (header) {
412
+ header.onmousedown = dragMouseDown;
413
+ } else {
414
+ el.onmousedown = dragMouseDown;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
  }
 
 
416
 
417
+ function dragMouseDown(e) {
418
+ e.preventDefault();
419
+ // Выводим окно на передний план
420
+ document.querySelectorAll('.window').forEach(w => w.style.zIndex = 1000);
421
+ el.style.zIndex = 1001;
 
 
422
 
423
+ pos3 = e.clientX;
424
+ pos4 = e.clientY;
425
+ document.onmouseup = closeDragElement;
426
+ document.onmousemove = elementDrag;
427
+ }
428
 
429
+ function elementDrag(e) {
430
+ e.preventDefault();
431
+ pos1 = pos3 - e.clientX;
432
+ pos2 = pos4 - e.clientY;
433
+ pos3 = e.clientX;
434
+ pos4 = e.clientY;
435
+ el.style.top = (el.offsetTop - pos2) + "px";
436
+ el.style.left = (el.offsetLeft - pos1) + "px";
437
+ }
438
 
439
+ function closeDragElement() {
440
+ document.onmouseup = null;
441
+ document.onmousemove = null;
 
 
 
 
 
 
 
 
 
442
  }
 
443
  }
444
 
445
+ // Инициализация перетаскивания
446
+ document.querySelectorAll('.window').forEach(makeDraggable);
447
 
448
+ // Управление окнами
449
+ function openWindow(id) {
450
+ const win = document.getElementById(id);
451
+ win.classList.add('active');
452
+ // Центрирование при первом открытии
453
+ if(win.style.top === "100px") {
454
+ win.style.top = (window.innerHeight / 2 - win.offsetHeight / 2) + "px";
455
+ win.style.left = (window.innerWidth / 2 - win.offsetWidth / 2) + "px";
456
+ }
457
  }
458
 
459
+ function closeWindow(id) {
460
+ document.getElementById(id).classList.remove('active');
461
  }
462
 
463
+ function setMobileTab(tab) {
464
+ document.querySelector('.workspace').setAttribute('data-tab', tab);
465
+ }
466
+
467
+ // --- 2. Сост��яние приложения и REST API ---
468
+ const state = {
469
+ url: '',
470
+ key: '',
471
+ user: null,
472
+ channels: [],
473
+ activeChannel: null,
474
+ usersCache: {},
475
+ lastMsgId: 0,
476
+ polling: null
477
+ };
478
+
479
+ // Универсальная обертка для REST API Supabase
480
+ async function api(table, method = 'GET', body = null, query = '') {
481
+ if (!state.url || !state.key) return null;
482
+
483
+ const endpoint = `${state.url}/rest/v1/${table}${query ? '?' + query : ''}`;
484
+ const headers = {
485
+ 'apikey': state.key,
486
+ 'Authorization': `Bearer ${state.key}`,
487
+ 'Content-Type': 'application/json',
488
+ 'Prefer': 'return=representation'
489
+ };
490
+
491
+ const config = { method, headers };
492
+ if (body) config.body = JSON.stringify(body);
493
+
494
+ try {
495
+ const res = await fetch(endpoint, config);
496
+ if (!res.ok) {
497
+ const errText = await res.text();
498
+ throw new Error(errText || `HTTP ${res.status}`);
499
  }
500
+ // DELETE запросы могут не возвращать JSON
501
+ if (method === 'DELETE' || res.status === 204) return true;
502
+ return await res.json();
503
+ } catch (e) {
504
+ console.error("API Error:", e);
505
+ throw e;
506
  }
507
+ }
508
 
509
+ // --- 3. Логика Подключения и Авторизации ---
510
+ async function checkConnection() {
511
+ const urlInput = document.getElementById('supa-url').value.trim();
512
+ const keyInput = document.getElementById('supa-key').value.trim();
513
+ const errDiv = document.getElementById('connect-error');
 
 
 
514
 
515
+ if (!urlInput || !keyInput) {
516
+ errDiv.innerText = "Заполните URL и Key";
517
+ return;
 
518
  }
519
+
520
+ // Убираем слэш на конце если есть
521
+ state.url = urlInput.endsWith('/') ? urlInput.slice(0, -1) : urlInput;
522
+ state.key = keyInput;
523
+ errDiv.innerText = "Проверка...";
524
+
525
+ try {
526
+ // Делаем легкий запрос к таблице channels для проверки
527
+ await api('channels', 'GET', null, 'select=id&limit=1');
528
+
529
+ // Если нет ошибки, сервер доступен
530
+ document.getElementById('connect-step-1').classList.add('hidden');
531
+ document.getElementById('connect-step-2').classList.remove('hidden');
532
+ errDiv.innerText = "";
533
+ } catch (e) {
534
+ errDiv.innerText = "Ошибка: Проверьте данные или права (RLS). " + e.message;
535
+ state.url = ''; state.key = '';
536
  }
 
 
537
  }
538
 
539
+ async function login() {
540
+ const u = document.getElementById('auth-user').value.trim();
541
+ const p = document.getElementById('auth-pass').value.trim();
542
+ const err = document.getElementById('auth-error');
 
543
 
544
+ if (!u || !p) return err.innerText = "Введите логин и пароль";
 
 
 
 
 
 
 
 
 
545
 
546
+ try {
547
+ // Ищем пользователя
548
+ const users = await api('users', 'GET', null, `username=eq.${encodeURIComponent(u)}&password=eq.${encodeURIComponent(p)}`);
549
+ if (users && users.length > 0) {
550
+ state.user = users[0];
551
+ if (state.user.role === 'banned') {
552
+ throw new Error("Вы забанены на этом сервере!");
 
 
 
 
 
 
 
553
  }
554
+ finishAuth();
555
+ } else {
556
+ err.innerText = "Неверный логин или пароль";
557
+ }
558
+ } catch(e) {
559
+ err.innerText = e.message;
560
  }
561
+ }
562
 
563
+ async function register() {
564
+ const u = document.getElementById('auth-user').value.trim();
565
+ const p = document.getElementById('auth-pass').value.trim();
566
+ const err = document.getElementById('auth-error');
567
+
568
+ if (!u || !p) return err.innerText = "Введите логин и пароль";
 
 
 
 
569
 
 
 
570
  try {
571
+ // Проверяем занят ли ник
572
+ const exist = await api('users', 'GET', null, `username=eq.${encodeURIComponent(u)}`);
573
+ if (exist && exist.length > 0) throw new Error("Ник уже занят");
574
+
575
+ const res = await api('users', 'POST', { username: u, password: p, role: 'user' });
576
+ if (res && res.length > 0) {
577
+ state.user = res[0];
578
+ finishAuth();
579
  }
580
+ } catch(e) {
581
+ err.innerText = e.message;
 
 
 
 
582
  }
583
  }
584
 
585
+ function finishAuth() {
586
+ closeWindow('connect-window');
587
+ document.getElementById('user-status').innerText = `👤 ${state.user.username} [${state.user.role}]`;
588
+ document.getElementById('messages-list').innerHTML = `<div class="msg system"><span class="author">***</span> SYSTEM: Соединение установлено. Авторизация успешна.</div>`;
589
 
590
+ // Запускаем процессы IRC
591
+ loadChannels();
 
592
 
593
+ // Polling каждые 2 секунды (старый стиль)
594
+ if(state.polling) clearInterval(state.polling);
595
+ state.polling = setInterval(appTick, 2000);
 
 
596
  }
597
 
598
+ // --- 4. Логика Чата (Каналы, Сообщения) ---
 
 
 
 
 
599
 
600
+ async function loadChannels() {
601
  try {
602
+ const chans = await api('channels', 'GET', null, 'order=id.asc');
603
+ if (chans) {
604
+ state.channels = chans;
605
+ renderChannels();
606
+ // Заходим в первый канал по умолчанию
607
+ if (chans.length > 0 && !state.activeChannel) {
608
+ joinChannel(chans[0].id);
609
+ }
610
+ }
611
+ } catch(e) { console.error("Load channels err", e); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
612
  }
613
 
614
  function renderChannels() {
615
+ const cl = document.getElementById('channels-list');
616
+ cl.innerHTML = '';
617
+ state.channels.forEach(c => {
618
  const div = document.createElement('div');
619
+ div.className = `list-item ${state.activeChannel === c.id ? 'active' : ''}`;
620
+ div.innerHTML = `<span>#${c.name}</span>`;
621
+ if (state.user && state.user.role === 'admin') {
622
+ div.innerHTML += `<span style="color:#ffb3b3;" onclick="deleteChannel(${c.id}, event)">x</span>`;
 
 
 
 
623
  }
624
+ div.onclick = () => joinChannel(c.id);
625
+ cl.appendChild(div);
 
626
  });
627
  }
628
 
629
+ async function createChannel() {
630
+ if(!state.user) return;
631
+ const input = document.getElementById('new-channel-name');
632
+ const name = input.value.trim().toLowerCase().replace(/[^a-z0-9_-]/g, '');
633
+ if (!name) return;
634
+
635
+ try {
636
+ await api('channels', 'POST', { name });
637
+ input.value = '';
638
+ loadChannels();
639
+ } catch(e) { alert("Ошибка создания канала: " + e.message); }
640
  }
641
 
642
+ async function deleteChannel(id, event) {
643
+ event.stopPropagation();
644
+ if(!confirm("Удалить канал?")) return;
645
  try {
646
+ await api('channels', 'DELETE', null, `id=eq.${id}`);
647
+ if (state.activeChannel === id) state.activeChannel = null;
648
+ loadChannels();
649
  } catch(e) {}
650
  }
651
 
652
+ async function joinChannel(id) {
653
+ state.activeChannel = id;
654
+ state.lastMsgId = 0;
655
+ const c = state.channels.find(x => x.id === id);
656
+ document.getElementById('chat-title').innerText = `Чат :: #${c ? c.name : 'Unknown'}`;
657
+ document.getElementById('messages-list').innerHTML = `<div class="msg system"><span class="author">***</span> SYSTEM: Вы вошли в канал #${c ? c.name : 'Unknown'}</div>`;
658
+ renderChannels();
659
+ await fetchMessages();
660
+ }
661
+
662
+ // Кэширование пользователей для отображения ников
663
+ async function getUser(id) {
664
+ if (state.usersCache[id]) return state.usersCache[id];
665
+ try {
666
+ const u = await api('users', 'GET', null, `id=eq.${id}&select=id,username,role`);
667
+ if (u && u.length > 0) {
668
+ state.usersCache[id] = u[0];
669
+ renderUsersList(); // Обновляем панель людей
670
+ return u[0];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
671
  }
672
+ } catch(e) {}
673
+ return { username: 'Unknown' };
674
+ }
675
 
676
+ function renderUsersList() {
677
+ const ul = document.getElementById('users-list');
678
+ ul.innerHTML = '';
679
+ Object.values(state.usersCache).forEach(u => {
680
+ const div = document.createElement('div');
681
+ div.className = 'list-item';
682
+ div.innerHTML = `<span>${u.role === 'admin' ? '@' : ''}${u.username}</span>`;
683
 
684
+ if (state.user && state.user.role === 'admin' && u.id !== state.user.id) {
685
+ div.innerHTML += `<span style="color:red; font-size:10px;" onclick="banUser(${u.id}, event)">[BAN]</span>`;
686
+ }
687
+ ul.appendChild(div);
688
  });
 
689
  }
690
 
691
+ async function banUser(userId, event) {
692
+ event.stopPropagation();
693
+ if(!confirm("Забанить пользователя?")) return;
694
+ try {
695
+ await api('users', 'PATCH', { role: 'banned' }, `id=eq.${userId}`);
696
+ alert("Пользователь забанен!");
697
+ delete state.usersCache[userId]; // Убираем из кэша
698
+ } catch(e) { alert("Ошибка: " + e.message); }
699
+ }
700
 
701
+ async function fetchMessages() {
702
+ if (!state.activeChannel || !state.user) return;
 
 
 
703
  try {
704
+ // Берем новые сообщения
705
+ const msgs = await api('messages', 'GET', null, `channel_id=eq.${state.activeChannel}&id=gt.${state.lastMsgId}&order=id.asc`);
706
+ if (msgs && msgs.length > 0) {
707
+ const ml = document.getElementById('messages-list');
708
+
709
+ for (const m of msgs) {
710
+ const u = await getUser(m.user_id);
711
+ const time = new Date(m.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', second:'2-digit'});
712
+
713
+ const div = document.createElement('div');
714
+ div.className = 'msg';
715
+ div.innerHTML = `<span class="time">[${time}]</span> <span class="author">&lt;${u.role==='admin'?'@':''}${u.username}&gt;</span> <span class="content"></span>`;
716
+ div.querySelector('.content').innerText = m.content; // Защита от XSS
717
+
718
+ ml.appendChild(div);
719
+ state.lastMsgId = Math.max(state.lastMsgId, m.id);
720
+ }
721
+ // Скролл вниз
722
+ ml.scrollTop = ml.scrollHeight;
723
  }
724
+ } catch(e) { console.error("Msg fetch err", e); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
725
  }
726
 
727
+ function handleEnter(e) {
728
+ if (e.key === 'Enter') sendMessage();
 
 
 
 
 
 
729
  }
730
 
731
+ async function sendMessage() {
732
+ const input = document.getElementById('msg-input');
733
+ const text = input.value.trim();
734
+ if (!text || !state.user || !state.activeChannel) return;
735
+
736
+ // Блокируем ввод пока отправляем
737
+ input.disabled = true;
738
+ try {
739
+ await api('messages', 'POST', {
740
+ channel_id: state.activeChannel,
741
+ user_id: state.user.id,
742
+ content: text
743
+ });
744
+ input.value = '';
745
+ await fetchMessages(); // Сразу запрашиваем обнову
746
+ } catch(e) {
747
+ alert("Не удалось отправить: " + e.message);
748
+ } finally {
749
+ input.disabled = false;
750
+ input.focus();
751
  }
752
+ }
753
 
754
+ // Основной цикл программы (замена WebSocket)
755
+ let tickCounter = 0;
756
+ function appTick() {
757
+ fetchMessages();
758
 
759
+ tickCounter++;
760
+ // Обновляем каналы реже (раз в 10 секунд)
761
+ if (tickCounter % 5 === 0) {
762
+ loadChannels();
763
+ }
764
  }
765
 
766
+ // Открываем FAQ при первом запуске, чтобы пользователь знал что делать
767
+ window.onload = () => {
768
+ setTimeout(() => {
769
+ openWindow('docx-window');
770
+ }, 500);
771
+ };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
772
 
 
 
 
 
 
 
 
 
773
  </script>
774
  </body>
775
  </html>