82 lines
2.9 KiB
JavaScript
82 lines
2.9 KiB
JavaScript
// Inbox: loads messages as JSON (GET /messages/list) and marks them read (POST /messages/{id}/read).
|
|
const inbox = document.querySelector('.inbox');
|
|
const list = inbox.querySelector('.inbox-list');
|
|
const status = inbox.querySelector('.inbox-status');
|
|
const unreadOnly = inbox.querySelector('.inbox-unread-only');
|
|
const t = inbox.dataset;
|
|
const dateFormat = new Intl.DateTimeFormat(document.documentElement.lang, { dateStyle: 'medium', timeStyle: 'short' });
|
|
|
|
async function load() {
|
|
try {
|
|
const res = await fetch(`${t.list}?unreadOnly=${unreadOnly.checked}`, { headers: { Accept: 'application/json' } });
|
|
if (!res.ok || res.redirected) throw new Error(res.status);
|
|
render(await res.json());
|
|
} catch {
|
|
list.replaceChildren();
|
|
status.textContent = t.failed;
|
|
}
|
|
}
|
|
|
|
// built with textContent only: message bodies are user input
|
|
function render(messages) {
|
|
status.textContent = messages.length ? '' : t.empty;
|
|
list.replaceChildren(...messages.map(m => {
|
|
const li = document.createElement('li');
|
|
li.className = 'inbox-item' + (m.isRead ? ' is-read' : '');
|
|
|
|
const meta = document.createElement('div');
|
|
meta.className = 'inbox-meta';
|
|
const from = document.createElement('strong');
|
|
from.textContent = m.anonymous ? t.anonymous : m.senderUsername;
|
|
const time = document.createElement('time');
|
|
time.dateTime = m.createdAt;
|
|
time.textContent = dateFormat.format(new Date(m.createdAt));
|
|
meta.append(from, time);
|
|
|
|
const body = document.createElement('p');
|
|
body.className = 'inbox-body';
|
|
body.textContent = m.body;
|
|
|
|
li.append(meta, body);
|
|
|
|
if (m.anonymous) {
|
|
const agent = document.createElement('p');
|
|
agent.className = 'inbox-agent';
|
|
agent.textContent = m.senderUsername;
|
|
li.append(agent);
|
|
}
|
|
|
|
li.append(m.isRead ? readLabel() : markReadButton(m.id, li));
|
|
return li;
|
|
}));
|
|
}
|
|
|
|
function readLabel() {
|
|
const span = document.createElement('span');
|
|
span.className = 'inbox-read';
|
|
span.textContent = t.read;
|
|
return span;
|
|
}
|
|
|
|
function markReadButton(id, li) {
|
|
const button = document.createElement('button');
|
|
button.type = 'button';
|
|
button.className = 'inbox-mark-read';
|
|
button.textContent = t.markRead;
|
|
button.addEventListener('click', async () => {
|
|
button.disabled = true;
|
|
const res = await fetch(`${t.base}/${id}/read`, {
|
|
method: 'POST',
|
|
headers: { RequestVerificationToken: t.token }
|
|
});
|
|
if (!res.ok) { button.disabled = false; return; }
|
|
if (unreadOnly.checked) { li.remove(); if (!list.children.length) status.textContent = t.empty; return; }
|
|
li.classList.add('is-read');
|
|
button.replaceWith(readLabel());
|
|
});
|
|
return button;
|
|
}
|
|
|
|
unreadOnly.addEventListener('change', load);
|
|
load();
|