Refactor Matrix chat widget implementation and enhance CSS styles for improved UI

This commit is contained in:
ryan
2026-06-19 17:45:21 +02:00
parent e04aeccee4
commit aaa738d3cd
3 changed files with 362 additions and 259 deletions
+13 -16
View File
@@ -1,4 +1,4 @@
from flask import Blueprint, render_template, current_app, redirect, url_for, request from flask import Blueprint, current_app, redirect, url_for, request
blueprint = Blueprint( blueprint = Blueprint(
'matrix_iframe', 'matrix_iframe',
@@ -8,29 +8,35 @@ blueprint = Blueprint(
static_url_path='/static/matrix_iframe', static_url_path='/static/matrix_iframe',
) )
def init_app(app, server_url='', room_alias='', login_endpoint=None):
def init_app(app, server_url='', room_alias='', base_template='layout.html', login_endpoint=None):
""" """
Register the Matrix chat blueprint with a Flask app. Register the Matrix chat blueprint with a Flask app.
The blueprint serves static assets (JS + CSS) and injects
matrix_chat_available, matrix_server_url, and matrix_room_alias
into every template context so the host app's layout can mount
the chat overlay widget.
Args: Args:
server_url: Matrix homeserver base URL, e.g. "https://matrix.sticknife.com" server_url: Matrix homeserver base URL, e.g. "https://matrix.sticknife.com"
room_alias: Matrix room alias, e.g. "#sticknife-library:matrix.sticknife.com" room_alias: Matrix room alias, e.g. "#sticknife-library:matrix.sticknife.com"
base_template: Jinja2 base template to extend, default "layout.html"
login_endpoint: Flask endpoint to redirect unauthenticated users to, login_endpoint: Flask endpoint to redirect unauthenticated users to,
e.g. "web.login". If None, no auth guard is applied. e.g. "web.login". If None, no auth guard is applied.
""" """
app.config.setdefault('MATRIX_SERVER_URL', server_url) app.config.setdefault('MATRIX_SERVER_URL', server_url)
app.config.setdefault('MATRIX_ROOM_ALIAS', room_alias) app.config.setdefault('MATRIX_ROOM_ALIAS', room_alias)
app.config.setdefault('MATRIX_CHAT_BASE', base_template)
app.config.setdefault('MATRIX_CHAT_LOGIN_ENDPOINT', login_endpoint) app.config.setdefault('MATRIX_CHAT_LOGIN_ENDPOINT', login_endpoint)
app.register_blueprint(blueprint) app.register_blueprint(blueprint)
@blueprint.app_context_processor @blueprint.app_context_processor
def _inject_matrix_chat(): def _inject_matrix_chat():
"""Makes matrix_chat_available=True visible to all templates when the blueprint is registered.""" """Injects matrix chat config into every template when the blueprint is registered."""
return {'matrix_chat_available': True} return {
'matrix_chat_available': True,
'matrix_server_url': current_app.config.get('MATRIX_SERVER_URL', ''),
'matrix_room_alias': current_app.config.get('MATRIX_ROOM_ALIAS', ''),
}
@blueprint.before_request @blueprint.before_request
@@ -46,12 +52,3 @@ def _auth_guard():
pass pass
@blueprint.route('/chat')
def chat():
return render_template(
'matrix_iframe/chat.html',
matrix_server=current_app.config.get('MATRIX_SERVER_URL', ''),
matrix_room_alias=current_app.config.get('MATRIX_ROOM_ALIAS', ''),
base_template=current_app.config.get('MATRIX_CHAT_BASE', 'layout.html'),
page='chat',
)
+225 -108
View File
@@ -1,144 +1,261 @@
#matrix-chat-root { /* ── Launch button ──────────────────────────────────────────────────────── */
display: flex;
flex-direction: column; .sk-chat-launch {
height: calc(100vh - 120px); position: fixed;
padding: 1rem; left: 18px;
gap: 0.75rem; bottom: 18px;
z-index: 1020;
min-height: 46px;
display: inline-flex;
align-items: center;
gap: 10px;
border: 1px solid rgba(126, 207, 255, 0.40);
border-radius: 999px;
color: #0e1f2b;
background: #7ecfff;
box-shadow: 0 16px 38px rgba(0, 0, 0, 0.32), inset 0 1px 0 rgba(255, 255, 255, 0.38);
padding: 0 16px 0 12px;
font-weight: 800;
cursor: pointer;
font-size: 0.9rem;
font-family: inherit;
transition: background 140ms ease, box-shadow 140ms ease;
} }
.matrix-status { .sk-chat-launch:hover {
font-size: 0.875rem; background: #a8dcff;
color: #aaa; box-shadow: 0 20px 44px rgba(0, 0, 0, 0.38), inset 0 1px 0 rgba(255, 255, 255, 0.42);
min-height: 1.25rem;
} }
.matrix-status-error { .sk-chat-launch-icon {
color: #e74c3c; width: 28px;
height: 28px;
border-radius: 50%;
background: rgba(14, 31, 43, 0.14);
display: inline-grid;
place-items: center;
flex-shrink: 0;
}
.sk-chat-launch svg {
width: 16px;
height: 16px;
fill: none;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
/* ── Backdrop ───────────────────────────────────────────────────────────── */
.sk-chat-backdrop {
position: fixed;
inset: 0;
z-index: 2000;
display: grid;
place-items: center;
padding: 28px;
background: rgba(5, 10, 12, 0.58);
backdrop-filter: blur(10px);
}
.sk-chat-backdrop[hidden] {
display: none;
}
/* ── Shell (modal) ──────────────────────────────────────────────────────── */
.sk-chat-shell {
position: relative;
width: min(680px, 100%);
height: min(700px, calc(100vh - 56px));
display: flex;
flex-direction: column;
gap: 10px;
overflow: hidden;
border: 1px solid rgba(126, 207, 255, 0.18);
border-radius: 18px;
color: #e8f4ff;
background: rgba(10, 20, 30, 0.94);
box-shadow: 0 28px 88px rgba(0, 0, 0, 0.52), inset 0 1px 0 rgba(255, 255, 255, 0.06);
padding: 14px;
}
/* ── Top bar ────────────────────────────────────────────────────────────── */
.sk-chat-topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 40px;
flex-shrink: 0;
}
.sk-chat-title {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 700;
font-size: 1rem;
color: #7ecfff;
}
.sk-chat-title svg {
width: 18px;
height: 18px;
fill: none;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
flex-shrink: 0;
}
.sk-chat-close {
background: none;
border: none;
color: #7ecfff;
font-size: 1.4rem;
line-height: 1;
cursor: pointer;
padding: 4px 8px;
border-radius: 6px;
transition: background 120ms ease;
font-family: inherit;
}
.sk-chat-close:hover {
background: rgba(126, 207, 255, 0.12);
}
/* ── Status bar ─────────────────────────────────────────────────────────── */
.sk-chat-status {
font-size: 0.8rem;
color: #7aa8c4;
min-height: 1rem;
flex-shrink: 0;
}
.sk-chat-status-error {
color: #e74c3c;
} }
/* ── Message list ───────────────────────────────────────────────────────── */ /* ── Message list ───────────────────────────────────────────────────────── */
.matrix-messages { .sk-chat-messages {
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;
background: rgba(0, 0, 0, 0.2); background: rgba(0, 0, 0, 0.25);
border: 1px solid rgba(255, 255, 255, 0.08); border: 1px solid rgba(126, 207, 255, 0.08);
border-radius: 8px; border-radius: 10px;
padding: 1rem; padding: 12px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.4rem; gap: 6px;
min-height: 0;
} }
.matrix-message { .sk-chat-message {
display: flex; display: flex;
align-items: baseline; align-items: baseline;
gap: 0.5rem; gap: 6px;
flex-wrap: nowrap; font-size: 0.875rem;
font-size: 0.9rem; line-height: 1.5;
line-height: 1.5; min-width: 0;
min-width: 0;
} }
.matrix-sender { .sk-chat-sender {
font-weight: 600; font-weight: 600;
color: #7ecfff; color: #7ecfff;
white-space: nowrap; white-space: nowrap;
flex-shrink: 0; flex-shrink: 0;
} }
.matrix-sender::after { .sk-chat-sender::after {
content: ':'; content: ':';
} }
.matrix-body { .sk-chat-body {
color: #ddd; color: #cce4f5;
word-break: break-word; word-break: break-word;
flex: 1; flex: 1;
min-width: 0; min-width: 0;
} }
.matrix-time { .sk-chat-time {
font-size: 0.72rem; font-size: 0.7rem;
color: #555; color: #3a5568;
white-space: nowrap; white-space: nowrap;
flex-shrink: 0; flex-shrink: 0;
align-self: flex-end; align-self: flex-end;
padding-bottom: 1px; padding-bottom: 1px;
} }
/* ── Input bar ──────────────────────────────────────────────────────────── */ /* ── Input bar ──────────────────────────────────────────────────────────── */
.matrix-input-bar { .sk-chat-inputbar {
display: flex; display: flex;
gap: 0.5rem; gap: 8px;
flex-shrink: 0; flex-shrink: 0;
} }
.matrix-input { .sk-chat-input {
flex: 1; flex: 1;
background: rgba(0, 0, 0, 0.3); background: rgba(0, 0, 0, 0.35);
border: 1px solid rgba(255, 255, 255, 0.15); border: 1px solid rgba(126, 207, 255, 0.18);
border-radius: 6px; border-radius: 8px;
color: #ddd; color: #cce4f5;
padding: 0.5rem 0.75rem; padding: 8px 12px;
font-size: 0.9rem; font-size: 0.875rem;
outline: none; outline: none;
transition: border-color 0.15s; transition: border-color 0.15s;
font-family: inherit;
} }
.matrix-input:focus { .sk-chat-input:focus {
border-color: rgba(126, 207, 255, 0.4); border-color: rgba(126, 207, 255, 0.45);
} }
.matrix-input::placeholder { .sk-chat-input::placeholder {
color: #555; color: #2e4a5e;
} }
.matrix-send-btn { .sk-chat-send {
background: rgba(126, 207, 255, 0.12); background: rgba(126, 207, 255, 0.14);
border: 1px solid rgba(126, 207, 255, 0.3); border: 1px solid rgba(126, 207, 255, 0.32);
border-radius: 6px; border-radius: 8px;
color: #7ecfff; color: #7ecfff;
padding: 0.5rem 1.25rem; padding: 8px 18px;
font-size: 0.9rem; font-size: 0.875rem;
cursor: pointer; cursor: pointer;
transition: background 0.15s, border-color 0.15s; font-weight: 600;
white-space: nowrap; transition: background 0.14s, border-color 0.14s;
font-family: inherit;
white-space: nowrap;
} }
.matrix-send-btn:hover { .sk-chat-send:hover {
background: rgba(126, 207, 255, 0.22); background: rgba(126, 207, 255, 0.24);
border-color: rgba(126, 207, 255, 0.5); border-color: rgba(126, 207, 255, 0.5);
} }
.matrix-send-btn:active { /* ── Responsive ─────────────────────────────────────────────────────────── */
background: rgba(126, 207, 255, 0.3);
}
/* ── Light theme fallback (when host app uses a light base) ─────────────── */ @media (max-width: 600px) {
.sk-chat-backdrop {
@media (prefers-color-scheme: light) { padding: 0;
.matrix-messages { align-items: flex-end;
background: rgba(0, 0, 0, 0.04); }
border-color: rgba(0, 0, 0, 0.1); .sk-chat-shell {
} width: 100%;
.matrix-sender { color: #1a6fa8; } height: 85vh;
.matrix-body { color: #222; } border-radius: 18px 18px 0 0;
.matrix-time { color: #aaa; } }
.matrix-input { .sk-chat-launch {
background: #fff; left: 12px;
border-color: #ccc; bottom: 12px;
color: #222; }
}
.matrix-input:focus { border-color: #1a6fa8; }
.matrix-input::placeholder { color: #aaa; }
.matrix-send-btn {
background: rgba(26, 111, 168, 0.1);
border-color: rgba(26, 111, 168, 0.4);
color: #1a6fa8;
}
.matrix-send-btn:hover {
background: rgba(26, 111, 168, 0.18);
}
} }
+124 -135
View File
@@ -1,9 +1,11 @@
'use strict'; 'use strict';
(function () { (function () {
const root = document.getElementById('matrix-chat-root'); const cfg = window._matrixChat || {};
const SERVER = (root.dataset.matrixServer || '').replace(/\/$/, ''); const SERVER = (cfg.server || '').replace(/\/$/, '');
const ROOM_ALIAS = root.dataset.matrixRoom || ''; const ROOM_ALIAS = cfg.room || '';
if (!SERVER || !ROOM_ALIAS) return;
const CREDS_KEY = 'matrix_chat_creds_' + SERVER; const CREDS_KEY = 'matrix_chat_creds_' + SERVER;
let accessToken = null; let accessToken = null;
@@ -12,30 +14,84 @@
let syncToken = null; let syncToken = null;
let syncActive = false; let syncActive = false;
let txnCounter = 0; let txnCounter = 0;
let initialized = false;
const messagesEl = document.getElementById('matrix-messages'); // ── DOM bootstrap ─────────────────────────────────────────────────────────
const statusEl = document.getElementById('matrix-chat-status');
const inputEl = document.getElementById('matrix-input');
const sendBtn = document.getElementById('matrix-send');
// ── Utilities ──────────────────────────────────────────────────────────── function mount() {
const css = document.createElement('link');
css.rel = 'stylesheet';
css.href = cfg.cssUrl || '';
if (cfg.cssUrl) document.head.appendChild(css);
document.body.insertAdjacentHTML('beforeend', `
<button class="sk-chat-launch" id="sk-chat-launch" aria-label="Open community chat">
<span class="sk-chat-launch-icon">
<svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
</span>
<span class="sk-chat-launch-label">Chat</span>
</button>
<div class="sk-chat-backdrop" id="sk-chat-backdrop" hidden>
<div class="sk-chat-shell" id="sk-chat-shell" role="dialog" aria-modal="true" aria-label="Library Chat">
<div class="sk-chat-topbar">
<span class="sk-chat-title">
<svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
Library Chat
</span>
<button class="sk-chat-close" id="sk-chat-close" aria-label="Close chat">&times;</button>
</div>
<div class="sk-chat-status" id="sk-chat-status"></div>
<div class="sk-chat-messages" id="sk-chat-messages"></div>
<div class="sk-chat-inputbar">
<input type="text" class="sk-chat-input" id="sk-chat-input" placeholder="Send a message…" autocomplete="off">
<button class="sk-chat-send" id="sk-chat-send">Send</button>
</div>
</div>
</div>`);
document.getElementById('sk-chat-launch').addEventListener('click', openPanel);
document.getElementById('sk-chat-close').addEventListener('click', closePanel);
document.getElementById('sk-chat-backdrop').addEventListener('click', function (e) {
if (e.target === this) closePanel();
});
document.getElementById('sk-chat-send').addEventListener('click', sendMessage);
document.getElementById('sk-chat-input').addEventListener('keydown', function (e) {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') closePanel();
});
}
function openPanel() {
document.getElementById('sk-chat-backdrop').hidden = false;
document.getElementById('sk-chat-input').focus();
if (!initialized) { initialized = true; init(); }
}
function closePanel() {
document.getElementById('sk-chat-backdrop').hidden = true;
}
// ── Utilities ─────────────────────────────────────────────────────────────
function escapeHtml(str) { function escapeHtml(str) {
return String(str) return String(str)
.replace(/&/g, '&amp;') .replace(/&/g, '&amp;').replace(/</g, '&lt;')
.replace(/</g, '&lt;') .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
} }
function setStatus(msg, isError) { function setStatus(msg, isError) {
statusEl.textContent = msg; const el = document.getElementById('sk-chat-status');
statusEl.className = 'matrix-status' + (isError ? ' matrix-status-error' : ''); el.textContent = msg;
el.className = 'sk-chat-status' + (isError ? ' sk-chat-status-error' : '');
} }
function clearStatus() { function clearStatus() {
statusEl.textContent = ''; const el = document.getElementById('sk-chat-status');
statusEl.className = 'matrix-status'; el.textContent = '';
el.className = 'sk-chat-status';
} }
function senderLocalpart(mxid) { function senderLocalpart(mxid) {
@@ -48,7 +104,7 @@
return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
} }
// ── Credentials ────────────────────────────────────────────────────────── // ── Credentials ──────────────────────────────────────────────────────────
function loadCreds() { function loadCreds() {
try { try {
@@ -63,10 +119,7 @@
} }
function saveCreds() { function saveCreds() {
localStorage.setItem(CREDS_KEY, JSON.stringify({ localStorage.setItem(CREDS_KEY, JSON.stringify({ access_token: accessToken, user_id: userId }));
access_token: accessToken,
user_id: userId,
}));
} }
function clearCreds() { function clearCreds() {
@@ -75,40 +128,26 @@
userId = null; userId = null;
} }
// ── Matrix API ─────────────────────────────────────────────────────────── // ── Matrix API ───────────────────────────────────────────────────────────
async function matrixFetch(method, path, body, params) { async function matrixFetch(method, path, body, params) {
const url = new URL(SERVER + path); const url = new URL(SERVER + path);
if (params) { if (params) for (const [k, v] of Object.entries(params)) url.searchParams.set(k, String(v));
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, String(v)); const opts = { method, headers: { 'Content-Type': 'application/json' } };
}
const opts = {
method,
headers: { 'Content-Type': 'application/json' },
};
if (accessToken) opts.headers['Authorization'] = 'Bearer ' + accessToken; if (accessToken) opts.headers['Authorization'] = 'Bearer ' + accessToken;
if (body !== null && body !== undefined) opts.body = JSON.stringify(body); if (body !== null && body !== undefined) opts.body = JSON.stringify(body);
const resp = await fetch(url.toString(), opts); const resp = await fetch(url.toString(), opts);
if (resp.status === 401) { clearCreds(); beginSSO(); throw new Error('Session expired'); }
if (resp.status === 401) {
clearCreds();
beginSSO();
throw new Error('Session expired — redirecting to login');
}
const data = await resp.json(); const data = await resp.json();
if (!resp.ok) throw new Error(data.error || 'HTTP ' + resp.status); if (!resp.ok) throw new Error(data.error || 'HTTP ' + resp.status);
return data; return data;
} }
// ── Auth ───────────────────────────────────────────────────────────────── // ── Auth ─────────────────────────────────────────────────────────────────
function beginSSO() { function beginSSO() {
// Strip any existing query string so we get a clean callback URL
const redirectUrl = window.location.origin + window.location.pathname; const redirectUrl = window.location.origin + window.location.pathname;
window.location.href = window.location.href = SERVER + '/_matrix/client/v3/login/sso/redirect?redirectUrl=' +
SERVER + '/_matrix/client/v3/login/sso/redirect?redirectUrl=' +
encodeURIComponent(redirectUrl); encodeURIComponent(redirectUrl);
} }
@@ -122,159 +161,109 @@
accessToken = data.access_token; accessToken = data.access_token;
userId = data.user_id; userId = data.user_id;
saveCreds(); saveCreds();
// Remove loginToken from the URL without triggering a reload
window.history.replaceState({}, '', window.location.pathname); window.history.replaceState({}, '', window.location.pathname);
} }
// ── Room ───────────────────────────────────────────────────────────────── // ── Room ─────────────────────────────────────────────────────────────────
async function resolveRoom() { async function resolveRoom() {
const data = await matrixFetch( const data = await matrixFetch('GET', '/_matrix/client/v3/directory/room/' + encodeURIComponent(ROOM_ALIAS));
'GET',
'/_matrix/client/v3/directory/room/' + encodeURIComponent(ROOM_ALIAS),
);
roomId = data.room_id; roomId = data.room_id;
} }
async function joinRoom() { async function joinRoom() {
try { try { await matrixFetch('POST', '/_matrix/client/v3/join/' + encodeURIComponent(roomId), {}); }
await matrixFetch('POST', '/_matrix/client/v3/join/' + encodeURIComponent(roomId), {}); catch (_) {}
} catch (_) {
// Already joined is fine; any real error surfaces during sync
}
} }
// ── Rendering ──────────────────────────────────────────────────────────── // ── Rendering ────────────────────────────────────────────────────────────
function renderEvent(event) { function renderEvent(event) {
if (event.type !== 'm.room.message') return; if (event.type !== 'm.room.message') return;
if (!event.content || event.content.msgtype !== 'm.text') return; if (!event.content || event.content.msgtype !== 'm.text') return;
const messagesEl = document.getElementById('sk-chat-messages');
const el = document.createElement('div'); const el = document.createElement('div');
el.className = 'matrix-message'; el.className = 'sk-chat-message';
el.innerHTML = el.innerHTML =
'<span class="matrix-sender">' + escapeHtml(senderLocalpart(event.sender)) + '</span>' + '<span class="sk-chat-sender">' + escapeHtml(senderLocalpart(event.sender)) + '</span>' +
'<span class="matrix-body">' + escapeHtml(event.content.body) + '</span>' + '<span class="sk-chat-body">' + escapeHtml(event.content.body) + '</span>' +
'<span class="matrix-time">' + escapeHtml(formatTime(event.origin_server_ts)) + '</span>'; '<span class="sk-chat-time">' + escapeHtml(formatTime(event.origin_server_ts)) + '</span>';
messagesEl.appendChild(el); messagesEl.appendChild(el);
} }
function isScrolledToBottom() { function scrollToBottom() {
return messagesEl.scrollHeight - messagesEl.scrollTop <= messagesEl.clientHeight + 60; const el = document.getElementById('sk-chat-messages');
el.scrollTop = el.scrollHeight;
} }
function scrollToBottom() { function isScrolledToBottom() {
messagesEl.scrollTop = messagesEl.scrollHeight; const el = document.getElementById('sk-chat-messages');
return el.scrollHeight - el.scrollTop <= el.clientHeight + 60;
} }
async function loadHistory() { async function loadHistory() {
const data = await matrixFetch( const data = await matrixFetch('GET',
'GET',
'/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/messages', '/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/messages',
null, null, { dir: 'b', limit: '50' });
{ dir: 'b', limit: '50' }, for (const ev of (data.chunk || []).reverse()) renderEvent(ev);
);
// /messages?dir=b returns newest-first; reverse for chronological display
const events = (data.chunk || []).reverse();
for (const ev of events) renderEvent(ev);
scrollToBottom(); scrollToBottom();
} }
// ── Send ───────────────────────────────────────────────────────────────── // ── Send ─────────────────────────────────────────────────────────────────
async function sendMessage() { async function sendMessage() {
const inputEl = document.getElementById('sk-chat-input');
const text = inputEl.value.trim(); const text = inputEl.value.trim();
if (!text || !roomId) return; if (!text || !roomId) return;
inputEl.value = ''; inputEl.value = '';
const txnId = Date.now() + '_' + (txnCounter++); const txnId = Date.now() + '_' + (txnCounter++);
try { try {
await matrixFetch( await matrixFetch('PUT',
'PUT', '/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/send/m.room.message/' + txnId,
'/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + { msgtype: 'm.text', body: text });
'/send/m.room.message/' + txnId,
{ msgtype: 'm.text', body: text },
);
} catch (e) { } catch (e) {
setStatus('Send failed: ' + e.message, true); setStatus('Send failed: ' + e.message, true);
} }
} }
// ── Sync loop ──────────────────────────────────────────────────────────── // ── Sync ──────────────────────────────────────────────────────────────────
// Minimal filter: only timeline events from our room, no state/presence/account noise
const SYNC_FILTER = JSON.stringify({
room: {
rooms: [], // filled in after room resolution
timeline: { limit: 20 },
state: { not_types: ['*'] },
ephemeral: { not_types: ['*'] },
},
presence: { not_types: ['*'] },
account_data: { not_types: ['*'] },
});
async function syncLoop() { async function syncLoop() {
syncActive = true; syncActive = true;
// Build a filter scoped to our single room
const filter = JSON.stringify({ const filter = JSON.stringify({
room: { room: { rooms: [roomId], timeline: { limit: 20 }, state: { not_types: ['*'] }, ephemeral: { not_types: ['*'] } },
rooms: [roomId],
timeline: { limit: 20 },
state: { not_types: ['*'] },
ephemeral: { not_types: ['*'] },
},
presence: { not_types: ['*'] }, presence: { not_types: ['*'] },
account_data: { not_types: ['*'] }, account_data: { not_types: ['*'] },
}); });
while (syncActive) { while (syncActive) {
try { try {
const params = { filter, timeout: '30000' }; const params = { filter, timeout: '30000' };
if (syncToken) params.since = syncToken; if (syncToken) params.since = syncToken;
const data = await matrixFetch('GET', '/_matrix/client/v3/sync', null, params); const data = await matrixFetch('GET', '/_matrix/client/v3/sync', null, params);
if (!syncActive) break; if (!syncActive) break;
syncToken = data.next_batch; syncToken = data.next_batch;
const timeline = data.rooms?.join?.[roomId]?.timeline;
const roomTimeline = if (timeline?.events?.length) {
data.rooms &&
data.rooms.join &&
data.rooms.join[roomId] &&
data.rooms.join[roomId].timeline;
if (roomTimeline && roomTimeline.events && roomTimeline.events.length) {
const atBottom = isScrolledToBottom(); const atBottom = isScrolledToBottom();
for (const ev of roomTimeline.events) renderEvent(ev); for (const ev of timeline.events) renderEvent(ev);
if (atBottom) scrollToBottom(); if (atBottom) scrollToBottom();
} }
} catch (e) { } catch (e) {
if (!syncActive) break; if (!syncActive) break;
// Back off before retrying to avoid hammering on persistent errors
await new Promise(r => setTimeout(r, 5000)); await new Promise(r => setTimeout(r, 5000));
} }
} }
} }
// ── Entry point ────────────────────────────────────────────────────────── // ── Entry point ──────────────────────────────────────────────────────────
async function init() { async function init() {
if (!SERVER) { setStatus('MATRIX_SERVER_URL is not configured.', true); return; }
if (!ROOM_ALIAS) { setStatus('MATRIX_ROOM_ALIAS is not configured.', true); return; }
// Handle SSO callback: Matrix redirects back here with ?loginToken=<token>
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const loginToken = urlParams.get('loginToken'); const loginToken = urlParams.get('loginToken');
if (loginToken) { if (loginToken) {
try { try { await exchangeLoginToken(loginToken); }
await exchangeLoginToken(loginToken); catch (e) { setStatus('Login failed: ' + e.message, true); return; }
} catch (e) {
setStatus('Login failed: ' + e.message, true);
return;
}
} else if (!loadCreds()) { } else if (!loadCreds()) {
beginSSO(); beginSSO();
return; return;
@@ -294,18 +283,18 @@
syncLoop(); syncLoop();
} }
// ── Event listeners ────────────────────────────────────────────────────── window.addEventListener('beforeunload', function () { syncActive = false; });
sendBtn.addEventListener('click', sendMessage); if (document.readyState === 'loading') {
inputEl.addEventListener('keydown', function (e) { document.addEventListener('DOMContentLoaded', mount);
if (e.key === 'Enter' && !e.shiftKey) { } else {
e.preventDefault(); mount();
sendMessage(); }
}
});
window.addEventListener('beforeunload', function () {
syncActive = false;
});
init(); // Auto-open if returning from SSO redirect (loginToken in URL)
if (new URLSearchParams(window.location.search).has('loginToken')) {
document.addEventListener('DOMContentLoaded', function () {
openPanel();
});
}
})(); })();