-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
170 lines (150 loc) · 6.16 KB
/
renderer.js
File metadata and controls
170 lines (150 loc) · 6.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
const state = require('./src/state');
const { mxcToUrl, scrollToBottom } = require('./src/utils');
const { login, getSavedSession, normalizeHomeserver, showStatus } = require('./src/auth');
const { startClient } = require('./src/client');
const { buildMessageEl } = require('./src/messages');
const { buildBody, clearMentions } = require('./src/mentions');
window.addEventListener('DOMContentLoaded', () => {
const session = getSavedSession();
if (session) {
document.getElementById('login-screen').classList.remove('active');
document.getElementById('loading-screen').classList.add('active');
startClient(session).catch(() => {
require('./src/auth').clearSession();
document.getElementById('loading-screen').classList.remove('active');
document.getElementById('login-screen').classList.add('active');
});
} else {
document.getElementById('login-screen').classList.add('active');
}
});
document.getElementById('login-form').addEventListener('submit', async e => {
e.preventDefault();
const homeserver = normalizeHomeserver(document.getElementById('homeserver').value);
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value;
const btn = e.target.querySelector('button[type="submit"]');
showStatus('Connecting...', 'success');
btn.disabled = true;
try {
const creds = await login(homeserver, username, password);
document.getElementById('login-screen').classList.remove('active');
document.getElementById('loading-screen').classList.add('active');
await startClient(creds);
} catch (err) {
showStatus(`Login failed: ${err.message}`, 'error');
btn.disabled = false;
}
});
const messageForm = document.getElementById('message-form');
const messageInput = document.getElementById('message-input');
const messagesContainer = document.getElementById('messages-container');
messageInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
messageForm.dispatchEvent(new Event('submit'));
}
});
messageInput.addEventListener('input', () => {
messageInput.style.height = 'auto';
messageInput.style.height = messageInput.scrollHeight + 'px';
});
messageForm.addEventListener('submit', async e => {
e.preventDefault();
const text = messageInput.value.trim();
if (!text || !state.roomId) return;
const msg = buildBody(text);
messageInput.value = '';
messageInput.style.height = 'auto';
const tempId = `temp-${Date.now()}`;
const fakeEvent = {
getSender: () => state.client.getUserId(),
getContent: () => ({ msgtype: 'm.text', body: text }),
getDate: () => new Date(),
getType: () => 'm.room.message',
getId: () => tempId,
};
const tempEl = buildMessageEl(fakeEvent);
tempEl.dataset.tempId = tempId;
tempEl.style.opacity = '0.6';
messagesContainer.appendChild(tempEl);
scrollToBottom();
try {
const hs = state.client.getHomeserverUrl();
const token = state.client.getAccessToken();
const txnId = `m${Date.now()}${Math.random().toString(36).slice(2)}`;
const res = await fetch(`${hs}/_matrix/client/v3/rooms/${encodeURIComponent(state.roomId)}/send/m.room.message/${txnId}`, {
method: 'PUT',
headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify(msg),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
messagesContainer.querySelector(`[data-temp-id="${tempId}"]`)?.remove();
clearMentions();
} catch (err) {
console.error('Send failed:', err);
clearMentions();
const el = messagesContainer.querySelector(`[data-temp-id="${tempId}"]`);
if (!el) return;
el.style.opacity = '1';
el.style.background = 'rgba(237,66,69,0.1)';
const retry = document.createElement('button');
retry.textContent = 'Retry';
retry.className = 'retry-btn';
retry.onclick = async () => {
retry.disabled = true;
retry.textContent = 'Retrying...';
try {
const hs2 = state.client.getHomeserverUrl();
const token2 = state.client.getAccessToken();
const txnId2 = `m${Date.now()}${Math.random().toString(36).slice(2)}`;
const res2 = await fetch(`${hs2}/_matrix/client/v3/rooms/${encodeURIComponent(state.roomId)}/send/m.room.message/${txnId2}`, {
method: 'PUT',
headers: { 'Authorization': `Bearer ${token2}`, 'Content-Type': 'application/json' },
body: JSON.stringify(msg),
});
if (!res2.ok) throw new Error(`HTTP ${res2.status}`);
el.remove();
} catch (err2) {
console.error('Retry failed:', err2);
retry.disabled = false;
retry.textContent = 'Retry';
}
};
el.appendChild(retry);
}
});
const attachBtn = document.getElementById('attach-btn');
const fileInput = document.getElementById('file-input');
attachBtn.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', async e => {
const file = e.target.files[0];
if (!file || !state.roomId) return;
if (!file.type.startsWith('image/')) { alert('Images only please'); return; }
if (file.size > 10 * 1024 * 1024) { alert('Max image size is 10MB'); return; }
const status = document.createElement('div');
status.className = 'upload-status';
status.textContent = `Uploading ${file.name}...`;
messagesContainer.appendChild(status);
scrollToBottom();
try {
const res = await state.client.uploadContent(file, {
name: file.name,
type: file.type,
onlyContentUri: false,
});
const hs = state.client.getHomeserverUrl();
const token = state.client.getAccessToken();
const txnId = `img${Date.now()}${Math.random().toString(36).slice(2)}`;
await fetch(`${hs}/_matrix/client/v3/rooms/${encodeURIComponent(state.roomId)}/send/m.room.message/${txnId}`, {
method: 'PUT',
headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ msgtype: 'm.image', body: file.name, url: res.content_uri, info: { mimetype: file.type, size: file.size } }),
});
} catch (err) {
alert('Upload failed: ' + err.message);
} finally {
status.remove();
fileInput.value = '';
}
});