You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.9 KiB
JavaScript

var _InAppWebViewReady = false;
2 years ago
var enableScrollSpy = true;
var titleList = [];
var currentTitle = '_top';
2 years ago
var titleOffset = 10;
window.MugenApp = {
emit: function() {
window.flutter_inappwebview.callHandler.apply(this, arguments);
},
scrollToTitle: function (anchor) {
var el = document.getElementById(anchor);
if (el) {
var scrollTop = window.scrollY + el.getBoundingClientRect().top;
if (navigator.safeArea) {
scrollTop -= navigator.safeArea.top + titleOffset;
}
scrollTop = Math.max(0, scrollTop);
enableScrollSpy = false;
window.scrollTo({
top: scrollTop,
});
setTimeout(function() {
enableScrollSpy = true;
}, 50);
}
},
};
function onReadyStateChange() {
if (_InAppWebViewReady && document.readyState === "complete") {
titleList = document.querySelectorAll('.mw-parser-output h1, .mw-parser-output h2, .mw-parser-output h3, .mw-parser-output h4, .mw-parser-output h5, .mw-parser-output h6');
window.MugenApp.emit('pageLoaded', true);
}
}
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
_InAppWebViewReady = true;
window.MugenApp.emit('bridgeConnected', true);
onReadyStateChange();
});
document.addEventListener("readystatechange", onReadyStateChange);
var _debouceTimer = null;
function debouce(callback, ms) {
return function() {
var _args = arguments;
if (!_debouceTimer) {
_debouceTimer = setTimeout(function() {
callback.apply(this, _args);
_debouceTimer = null;
}, ms);
}
}
}
document.addEventListener('scroll', debouce(function() {
2 years ago
if (!enableScrollSpy || !titleList || titleList.length === 0) return true;
2 years ago
var offsetTop = (navigator.safeArea ? navigator.safeArea.top : 0) + titleOffset;
var currentTitleEl = null;
var isFirstSection = false;
for (var i = 0; i < titleList.length; i ++) {
var el = titleList[i];
var pos = el.getBoundingClientRect();
if (pos.top - offsetTop > 0) {
if (i === 0) {
isFirstSection = true;
} else {
currentTitleEl = titleList[i - 1];
}
break;
}
}
if (!currentTitleEl && !isFirstSection) {
currentTitleEl = titleList[titleList.length - 1];
}
var newCurrentTitle;
if (isFirstSection) {
newCurrentTitle = '_firstSection';
} else {
var currentTitleAnchorEl = currentTitleEl.querySelector('.mw-headline');
if (currentTitleAnchorEl) {
newCurrentTitle = currentTitleAnchorEl.id;
}
}
if (newCurrentTitle && newCurrentTitle !== currentTitle) {
currentTitle = newCurrentTitle;
window.MugenApp.emit('sectionChange', newCurrentTitle);
}
}, 200), { passive: true });