MediaWiki:Gadget-TimelinePreview.js
From Angelina Jordan Wiki
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
// Gadget: Timeline hover previews
// Requires: mediawiki.api, mediawiki.util, jquery
mw.loader.using(['mediawiki.api', 'mediawiki.util']).then(function () {
var api = new mw.Api();
var timelineCache = {};
var timelineLoaded = false;
var popup;
function loadTimeline() {
if (timelineLoaded) return $.Deferred().resolve();
timelineLoaded = true;
return api.get({
action: 'parse',
page: 'Timeline',
prop: 'text',
formatversion: 2
}).then(function (data) {
var html = $('<div>').html(data.parse.text);
var dts = html.find('dt');
dts.each(function () {
var dt = $(this);
var id = dt.find('span[id]').attr('id');
if (!id) return;
var ddList = [];
var el = dt.next();
while (el.length && el.prop('tagName') === 'DD') {
ddList.push(el.html());
el = el.next();
}
timelineCache[id] = ddList.join('<br>');
});
});
}
function showPopup($link, html) {
if (!popup) {
popup = $('<div>')
.css({
position: 'absolute',
zIndex: 1000,
background: 'white',
border: '1px solid #ccc',
padding: '0.5em',
maxWidth: '320px',
boxShadow: '0 2px 4px rgba(0,0,0,0.2)'
})
.hide()
.appendTo(document.body);
}
popup.html(html).show();
var offset = $link.offset();
popup.css({
top: offset.top + $link.height() + 5,
left: offset.left
});
}
function hidePopup() {
if (popup) popup.hide();
}
function onHover() {
var $link = $(this);
var href = $link.attr('href') || '';
var match = href.match(/\/Timeline#(\d{4}-\d{2}-\d{2})$/) || href.match(/^#(\d{4}-\d{2}-\d{2})$/);
if (!match) return;
var id = match[1];
mw.hook('wikipage.content').fire(); // ensure MW hooks run if needed
mw.hook('pv.disable').fire($link); // disable standard page preview
loadTimeline().then(function () {
var content = timelineCache[id];
if (content) showPopup($link, content);
});
}
function attach() {
$('a[href*="Timeline#"], a[href^="#"]').hover(onHover, hidePopup);
}
mw.hook('wikipage.content').add(attach);
});