Files

387 lines
14 KiB
JavaScript

/*
* Herald client for jellyfin-web.
* Shows pending notices one at a time. No dependencies; ES5 on purpose, some TV web views are old.
*/
(function () {
'use strict';
if (window.__heraldClient) {
return;
}
window.__heraldClient = true;
var CHECK_INTERVAL_MS = 10 * 60 * 1000;
var SESSION_POLL_MS = 3000;
var SAFE_LINK = /^(https?:\/\/|mailto:)/i;
var userId = null;
var lastCheck = 0;
var checking = false;
var queue = [];
var open = null;
// ---------------------------------------------------------------- session
function currentUserId() {
try {
var client = window.ApiClient;
if (!client || typeof client.getCurrentUserId !== 'function') {
return null;
}
var token = typeof client.accessToken === 'function' ? client.accessToken() : null;
return token ? (client.getCurrentUserId() || null) : null;
} catch (e) {
return null;
}
}
function send(method, path, body) {
var client = window.ApiClient;
var options = { type: method, url: client.getUrl(path) };
if (body) {
options.data = JSON.stringify(body);
options.contentType = 'application/json';
}
if (method === 'GET') {
options.dataType = 'json';
}
return client.ajax(options);
}
// Runs on a short local timer. It only talks to the server after a login or
// user switch, and otherwise once per CHECK_INTERVAL_MS.
function tick() {
var id = currentUserId();
if (id !== userId) {
userId = id;
queue = [];
closeOpen();
if (id) {
check();
}
return;
}
if (id && !document.hidden && Date.now() - lastCheck >= CHECK_INTERVAL_MS) {
check();
}
}
function check() {
if (checking || !userId) {
return;
}
checking = true;
lastCheck = Date.now();
var askedFor = userId;
send('GET', 'Herald/Notices/Pending').then(function (notices) {
checking = false;
if (askedFor !== userId || !notices || !notices.length) {
return;
}
queue = notices.filter(function (n) {
return !open || open.notice.Id !== n.Id || open.notice.Revision !== n.Revision;
});
showNext();
}, function () {
checking = false;
});
}
// ---------------------------------------------------------------- content
function appendText(parent, text) {
if (text) {
parent.appendChild(document.createTextNode(text));
}
}
// Bold, italic and links. Everything ends up as text nodes or elements
// created here; the notice body is never parsed as HTML.
function appendInline(parent, text) {
var pattern = /\*\*([^*]+?)\*\*|\*([^*\s][^*]*?)\*|(^|[^\w])_([^_\s][^_]*?)_(?!\w)|\[([^\]]+)\]\(([^)\s]+)\)/g;
var last = 0;
var match;
while ((match = pattern.exec(text)) !== null) {
appendText(parent, text.slice(last, match.index));
last = pattern.lastIndex;
if (match[1] !== undefined) {
appendInline(parent.appendChild(document.createElement('strong')), match[1]);
} else if (match[2] !== undefined) {
appendInline(parent.appendChild(document.createElement('em')), match[2]);
} else if (match[4] !== undefined) {
appendText(parent, match[3]);
appendInline(parent.appendChild(document.createElement('em')), match[4]);
} else if (SAFE_LINK.test(match[6])) {
var link = document.createElement('a');
link.href = match[6];
link.target = '_blank';
link.rel = 'noopener noreferrer';
link.className = 'heraldLink';
appendInline(link, match[5]);
parent.appendChild(link);
} else {
appendText(parent, match[0]);
}
}
appendText(parent, text.slice(last));
}
function appendBody(parent, body) {
var lines = String(body || '').replace(/\r\n?/g, '\n').split('\n');
var block = null;
var blockType = null;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var bullet = /^\s*[-*]\s+(.*)$/.exec(line);
var numbered = /^\s*\d+[.)]\s+(.*)$/.exec(line);
if (!line.trim()) {
block = null;
blockType = null;
} else if (bullet || numbered) {
var type = bullet ? 'ul' : 'ol';
if (blockType !== type) {
block = parent.appendChild(document.createElement(type));
blockType = type;
}
appendInline(block.appendChild(document.createElement('li')), (bullet || numbered)[1]);
} else {
if (blockType !== 'p') {
block = parent.appendChild(document.createElement('p'));
blockType = 'p';
} else {
block.appendChild(document.createElement('br'));
}
appendInline(block, line);
}
}
}
// ---------------------------------------------------------------- modal
var CSS = [
'.heraldBackdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:999990;display:flex;align-items:center;justify-content:center;',
'padding:1.2em;box-sizing:border-box;background:rgba(0,0,0,.66);opacity:0;transition:opacity .14s ease-out}',
'.heraldBackdrop.heraldIn{opacity:1}',
// Fallback surface for themes without a ".dialog" rule; zero specificity so the theme wins when it has one.
':where(.heraldSheet){background-color:var(--jf-palette-background-paper,#202020)}',
'.heraldSheet.heraldSheet{position:relative;display:flex;flex-direction:column;width:100%;max-width:34em;max-height:86vh;margin:0;padding:0;',
'box-sizing:border-box;border:1px solid rgba(128,128,128,.28);border-radius:.3em;overflow:hidden;',
'box-shadow:0 1.2em 3em rgba(0,0,0,.55);transform:translateY(.6em);transition:transform .16s ease-out}',
'.heraldIn .heraldSheet{transform:none}',
'.heraldMast{flex:none;padding:1.5em 1.7em 0}',
'.heraldKicker{display:flex;justify-content:space-between;margin:0;font-size:.74em;font-weight:600;letter-spacing:.16em;text-transform:uppercase;opacity:.7}',
'.heraldRule{height:.3em;margin:.6em 0 1em;border-top:.12em solid currentColor;border-bottom:1px solid currentColor;opacity:.42}',
'.heraldTitle{margin:0;font-size:1.5em;font-weight:600;line-height:1.22;overflow-wrap:anywhere}',
'.heraldBody{flex:1 1 auto;min-height:0;overflow-y:auto;padding:.9em 1.7em .3em;line-height:1.55;overflow-wrap:anywhere}',
'.heraldBody p{margin:0 0 .85em}',
'.heraldBody ul,.heraldBody ol{margin:0 0 .85em;padding-left:1.35em}',
'.heraldBody li{margin:.2em 0}',
'.heraldLink{color:var(--jf-palette-primary-main,#00a4dc);text-decoration:underline}',
'.heraldFoot{flex:none;display:flex;flex-wrap:wrap;align-items:center;justify-content:flex-end;gap:.4em 1em;padding:.7em 1.7em 1.3em}',
'.heraldError{flex:1 1 12em;margin:0;font-size:.9em;color:var(--jf-palette-error-main,#e2574c)}',
'.heraldButton.heraldButton{flex:none;margin:0;min-width:8.5em;justify-content:center;text-align:center}',
'@media (max-width:30em){.heraldBackdrop{padding:.6em;align-items:flex-end}.heraldMast{padding:1.2em 1.2em 0}',
'.heraldBody{padding:.8em 1.2em .2em}.heraldFoot{padding:.6em 1.2em 1.1em}.heraldButton.heraldButton{flex:1 1 100%}}',
'@media (prefers-reduced-motion:reduce){.heraldBackdrop,.heraldSheet.heraldSheet{transition:none}}'
].join('');
function ensureStyle() {
if (!document.getElementById('heraldStyle')) {
var style = document.createElement('style');
style.id = 'heraldStyle';
style.textContent = CSS;
document.head.appendChild(style);
}
}
function element(tag, className, text) {
var node = document.createElement(tag);
if (className) {
node.className = className;
}
if (text) {
node.textContent = text;
}
return node;
}
function showNext() {
if (open || !queue.length || !userId) {
return;
}
show(queue.shift());
}
function show(notice) {
ensureStyle();
var mustAccept = !!notice.RequireAccept;
var titleId = 'heraldTitle-' + notice.Id;
var backdrop = element('div', 'heraldBackdrop');
// "dialog" and the button classes are jellyfin-web's own, so the active theme colors them.
var sheet = element('div', 'heraldSheet dialog');
sheet.setAttribute('role', mustAccept ? 'alertdialog' : 'dialog');
sheet.setAttribute('aria-modal', 'true');
sheet.setAttribute('aria-labelledby', titleId);
var mast = element('div', 'heraldMast');
var kicker = element('p', 'heraldKicker');
kicker.appendChild(element('span', null, mustAccept ? 'Please confirm' : 'Notice'));
if (queue.length) {
kicker.appendChild(element('span', null, (queue.length) + ' more'));
}
mast.appendChild(kicker);
mast.appendChild(element('div', 'heraldRule'));
var title = element('h2', 'heraldTitle', notice.Title);
title.id = titleId;
mast.appendChild(title);
var body = element('div', 'heraldBody');
appendBody(body, notice.Body);
var foot = element('div', 'heraldFoot');
var error = element('p', 'heraldError');
error.setAttribute('role', 'alert');
var button = element('button', 'heraldButton raised button-submit emby-button', mustAccept ? 'Accept' : 'Close');
button.type = 'button';
foot.appendChild(error);
foot.appendChild(button);
sheet.appendChild(mast);
sheet.appendChild(body);
sheet.appendChild(foot);
backdrop.appendChild(sheet);
var state = {
notice: notice,
backdrop: backdrop,
button: button,
error: error,
sending: false,
previousFocus: document.activeElement,
onKey: null
};
button.addEventListener('click', function () {
respond(state, mustAccept ? 'Accepted' : 'Dismissed');
});
backdrop.addEventListener('click', function (e) {
if (e.target === backdrop && !mustAccept) {
respond(state, 'Dismissed');
}
});
state.onKey = function (e) {
if (e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27) {
// Keep jellyfin-web from treating it as "back".
e.preventDefault();
e.stopPropagation();
if (!mustAccept) {
respond(state, 'Dismissed');
}
} else if (e.key === 'Tab' || e.keyCode === 9) {
keepFocusInside(e, sheet);
}
};
document.addEventListener('keydown', state.onKey, true);
open = state;
document.body.appendChild(backdrop);
// Two frames so the transition has a starting state to move from.
requestAnimationFrame(function () {
requestAnimationFrame(function () {
backdrop.classList.add('heraldIn');
});
});
button.focus();
}
function keepFocusInside(e, sheet) {
var items = sheet.querySelectorAll('a[href],button');
if (!items.length) {
return;
}
var first = items[0];
var last = items[items.length - 1];
if (!sheet.contains(document.activeElement)) {
e.preventDefault();
first.focus();
} else if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
function respond(state, action) {
if (state.sending || open !== state) {
return;
}
state.sending = true;
state.button.disabled = true;
state.error.textContent = '';
var path = 'Herald/Notices/' + encodeURIComponent(state.notice.Id) + '/Ack';
send('POST', path, { revision: state.notice.Revision, action: action }).then(function () {
closeOpen();
showNext();
}, function (response) {
var status = response && response.status;
if (status === 404 || status === 409) {
// Changed or withdrawn while it was on screen: ask the server what is current.
closeOpen();
queue = [];
check();
} else if (action === 'Dismissed') {
// Not stored, so it comes back with the next check. Do not hold the user up.
closeOpen();
showNext();
} else {
state.sending = false;
state.button.disabled = false;
state.error.textContent = 'Could not save your answer. Please try again.';
}
});
}
function closeOpen() {
var state = open;
if (!state) {
return;
}
open = null;
document.removeEventListener('keydown', state.onKey, true);
if (state.backdrop.parentNode) {
state.backdrop.parentNode.removeChild(state.backdrop);
}
try {
if (state.previousFocus && document.contains(state.previousFocus)) {
state.previousFocus.focus();
}
} catch (e) {
// focus is a courtesy
}
}
// ---------------------------------------------------------------- start
setInterval(tick, SESSION_POLL_MS);
document.addEventListener('visibilitychange', function () {
if (!document.hidden) {
tick();
}
});
tick();
})();