Files
matrix-iframe/matrix_iframe/static/matrix_iframe/matrix-chat.js
T

301 lines
12 KiB
JavaScript

'use strict';
(function () {
const cfg = window._matrixChat || {};
const SERVER = (cfg.server || '').replace(/\/$/, '');
const ROOM_ALIAS = cfg.room || '';
if (!SERVER || !ROOM_ALIAS) return;
const CREDS_KEY = 'matrix_chat_creds_' + SERVER;
let accessToken = null;
let userId = null;
let roomId = null;
let syncToken = null;
let syncActive = false;
let txnCounter = 0;
let initialized = false;
// ── DOM bootstrap ─────────────────────────────────────────────────────────
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) {
return String(str)
.replace(/&/g, '&amp;').replace(/</g, '&lt;')
.replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function setStatus(msg, isError) {
const el = document.getElementById('sk-chat-status');
el.textContent = msg;
el.className = 'sk-chat-status' + (isError ? ' sk-chat-status-error' : '');
}
function clearStatus() {
const el = document.getElementById('sk-chat-status');
el.textContent = '';
el.className = 'sk-chat-status';
}
function senderLocalpart(mxid) {
const m = String(mxid).match(/^@([^:]+):/);
return m ? m[1] : mxid;
}
function formatTime(ts) {
if (!ts) return '';
return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// ── Credentials ───────────────────────────────────────────────────────────
function loadCreds() {
try {
const stored = JSON.parse(localStorage.getItem(CREDS_KEY) || 'null');
if (stored && stored.access_token) {
accessToken = stored.access_token;
userId = stored.user_id;
return true;
}
} catch (_) {}
return false;
}
function saveCreds() {
localStorage.setItem(CREDS_KEY, JSON.stringify({ access_token: accessToken, user_id: userId }));
}
function clearCreds() {
localStorage.removeItem(CREDS_KEY);
accessToken = null;
userId = null;
}
// ── Matrix API ────────────────────────────────────────────────────────────
async function matrixFetch(method, path, body, params) {
const url = new URL(SERVER + path);
if (params) for (const [k, v] of Object.entries(params)) url.searchParams.set(k, String(v));
const opts = { method, headers: { 'Content-Type': 'application/json' } };
if (accessToken) opts.headers['Authorization'] = 'Bearer ' + accessToken;
if (body !== null && body !== undefined) opts.body = JSON.stringify(body);
const resp = await fetch(url.toString(), opts);
if (resp.status === 401) { clearCreds(); beginSSO(); throw new Error('Session expired'); }
const data = await resp.json();
if (!resp.ok) throw new Error(data.error || 'HTTP ' + resp.status);
return data;
}
// ── Auth ──────────────────────────────────────────────────────────────────
function beginSSO() {
const redirectUrl = window.location.origin + window.location.pathname;
window.location.href = SERVER + '/_matrix/client/v3/login/sso/redirect?redirectUrl=' +
encodeURIComponent(redirectUrl);
}
async function exchangeLoginToken(token) {
setStatus('Authenticating…');
const data = await matrixFetch('POST', '/_matrix/client/v3/login', {
type: 'm.login.token',
token,
initial_device_display_name: 'Sticknife Library Chat',
});
accessToken = data.access_token;
userId = data.user_id;
saveCreds();
window.history.replaceState({}, '', window.location.pathname);
}
// ── Room ──────────────────────────────────────────────────────────────────
async function resolveRoom() {
const data = await matrixFetch('GET', '/_matrix/client/v3/directory/room/' + encodeURIComponent(ROOM_ALIAS));
roomId = data.room_id;
}
async function joinRoom() {
try { await matrixFetch('POST', '/_matrix/client/v3/join/' + encodeURIComponent(roomId), {}); }
catch (_) {}
}
// ── Rendering ─────────────────────────────────────────────────────────────
function renderEvent(event) {
if (event.type !== 'm.room.message') return;
if (!event.content || event.content.msgtype !== 'm.text') return;
const messagesEl = document.getElementById('sk-chat-messages');
const el = document.createElement('div');
el.className = 'sk-chat-message';
el.innerHTML =
'<span class="sk-chat-sender">' + escapeHtml(senderLocalpart(event.sender)) + '</span>' +
'<span class="sk-chat-body">' + escapeHtml(event.content.body) + '</span>' +
'<span class="sk-chat-time">' + escapeHtml(formatTime(event.origin_server_ts)) + '</span>';
messagesEl.appendChild(el);
}
function scrollToBottom() {
const el = document.getElementById('sk-chat-messages');
el.scrollTop = el.scrollHeight;
}
function isScrolledToBottom() {
const el = document.getElementById('sk-chat-messages');
return el.scrollHeight - el.scrollTop <= el.clientHeight + 60;
}
async function loadHistory() {
const data = await matrixFetch('GET',
'/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/messages',
null, { dir: 'b', limit: '50' });
for (const ev of (data.chunk || []).reverse()) renderEvent(ev);
scrollToBottom();
}
// ── Send ──────────────────────────────────────────────────────────────────
async function sendMessage() {
const inputEl = document.getElementById('sk-chat-input');
const text = inputEl.value.trim();
if (!text || !roomId) return;
inputEl.value = '';
const txnId = Date.now() + '_' + (txnCounter++);
try {
await matrixFetch('PUT',
'/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/send/m.room.message/' + txnId,
{ msgtype: 'm.text', body: text });
} catch (e) {
setStatus('Send failed: ' + e.message, true);
}
}
// ── Sync ──────────────────────────────────────────────────────────────────
async function syncLoop() {
syncActive = true;
const filter = JSON.stringify({
room: { rooms: [roomId], timeline: { limit: 20 }, state: { not_types: ['*'] }, ephemeral: { not_types: ['*'] } },
presence: { not_types: ['*'] },
account_data: { not_types: ['*'] },
});
while (syncActive) {
try {
const params = { filter, timeout: '30000' };
if (syncToken) params.since = syncToken;
const data = await matrixFetch('GET', '/_matrix/client/v3/sync', null, params);
if (!syncActive) break;
syncToken = data.next_batch;
const timeline = data.rooms?.join?.[roomId]?.timeline;
if (timeline?.events?.length) {
const atBottom = isScrolledToBottom();
for (const ev of timeline.events) renderEvent(ev);
if (atBottom) scrollToBottom();
}
} catch (e) {
if (!syncActive) break;
await new Promise(r => setTimeout(r, 5000));
}
}
}
// ── Entry point ───────────────────────────────────────────────────────────
async function init() {
const urlParams = new URLSearchParams(window.location.search);
const loginToken = urlParams.get('loginToken');
if (loginToken) {
try { await exchangeLoginToken(loginToken); }
catch (e) { setStatus('Login failed: ' + e.message, true); return; }
} else if (!loadCreds()) {
beginSSO();
return;
}
try {
setStatus('Connecting…');
await resolveRoom();
await joinRoom();
await loadHistory();
clearStatus();
} catch (e) {
setStatus('Connection error: ' + e.message, true);
return;
}
syncLoop();
}
window.addEventListener('beforeunload', function () { syncActive = false; });
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', mount);
} else {
mount();
}
// Auto-open if returning from SSO redirect (loginToken in URL)
if (new URLSearchParams(window.location.search).has('loginToken')) {
document.addEventListener('DOMContentLoaded', function () {
openPanel();
});
}
})();