MediaWiki:Gadget-sessionStorageNotify.js
Hoppa till navigering
Hoppa till sök
OBS: Efter du har publicerat sidan kan du behöva tömma din webbläsares cache för att se ändringarna.
- Firefox / Safari: Håll ned Skift och klicka på Uppdatera sidan eller tryck Ctrl-F5 eller Ctrl-R (⌘-R på Mac)
- Google Chrome: Tryck Ctrl-Skift-R (⌘-Skift-R på Mac)
- Internet Explorer / Edge: Håll ned Ctrl och klicka på Uppdatera eller tryck Ctrl-F5
- Opera: Tryck Ctrl-F5.
// @ts-check
/** @type {*} */
var w = window;
w.sessionStorageNotify =
/**
* A wrapper around `mw.notification.notify()`, where if the notification
* wasn't shown for a sufficiently long time on the current page, will be
* displayed on the next page load.
*
* @param {{
* message: string | HTMLElement | JQuery;
* seconds?: number;
* tag?: string;
* }} opts
*/
function (opts) {
show({
id: Math.random(),
message:
typeof opts.message === "string"
? opts.message
: { html: $("<div>").append(opts.message).html() },
seconds: opts.seconds || 5,
tag: opts.tag,
});
};
/**
* @typedef {{
* id: number;
* message: string | { html: string };
* seconds: number;
* tag?: string;
* }} Notif
*
* @typedef {*} JQuery
*/
var $ = w.$;
var mw = w.mw;
/** @param {Notif} notif */
function show(notif) {
mw.loader.using(
[
"mediawiki.notification",
// OOUI isn't required by this gadget, but by loading it, we load the CSS
// required for an `OO.ui.MessageWidget`.
"oojs-ui-core",
],
function () {
// Create a MediaWiki notification and show it.
var n = mw.notification.notify(
typeof notif.message === "string"
? notif.message
: $($.parseHTML(notif.message.html)),
{
autoHide: false,
tag: notif.tag,
}
);
// Add it to `sessionStorage`.
update(function (notifs) {
notifs[notif.id] = notif;
});
// Close the notification and remove it from `sessionStorage`.
setTimeout(function () {
n.close();
update(function (notifs) {
delete notifs[notif.id];
});
}, 1000 * notif.seconds);
}
);
}
/** @param {(notifs: Record<number, Notif>) => void} action */
function update(action) {
try {
var key = "gadget:ssNotify";
var notifs = JSON.parse("" + sessionStorage.getItem(key)) || {};
action(notifs);
sessionStorage.setItem(key, JSON.stringify(notifs));
} catch (e) {
// Can't use `sessionStorage`. Do nothing.
}
}
$(function () {
// Don't actually update them here - just used for access.
update(function (notifs) {
Object.values(notifs).forEach(show);
});
});