- Router.add() now takes 3 params (pattern, title, onEnter) matching app.js usage - Fixed setActiveSidebar → setActivePage in all route callbacks - Removed premature hash-setting from connect.js — app.js now sole navigator (was firing router into a hidden container before showConnected ran) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
81 lines
2.1 KiB
JavaScript
81 lines
2.1 KiB
JavaScript
/**
|
|
* Minimal hash-based SPA router.
|
|
*
|
|
* Route format: { pattern: RegExp, title: string, template: string, onEnter: function(params, container) }
|
|
*
|
|
* The first matching route's onEnter is called with parsed params and a container element.
|
|
* The container is cleared before each navigation.
|
|
*
|
|
* Usage:
|
|
* Router.add(/^\/(.+)\/info$/, 'Server', 'html/serverInfo.html', ServerInfoPage);
|
|
* Router.add(/^\/(.+)\/player\/(.+)$/, 'Player Info', 'html/playerInfo.html', PlayerInfoPage);
|
|
* Router.start('#app-view');
|
|
*/
|
|
var Router = (function () {
|
|
'use strict';
|
|
|
|
var routes = [];
|
|
var viewSelector = null;
|
|
var currentCleanup = null;
|
|
|
|
function add(pattern, title, onEnter) {
|
|
routes.push({ pattern: pattern, title: title, onEnter: onEnter });
|
|
}
|
|
|
|
function navigate(hash) {
|
|
// strip leading # and optional /
|
|
var path = (hash || '').replace(/^#\/?/, '/');
|
|
if (!path || path === '/') path = '/home';
|
|
|
|
for (var i = 0; i < routes.length; i++) {
|
|
var r = routes[i];
|
|
var match = path.match(r.pattern);
|
|
if (match) {
|
|
// Store params for later use
|
|
var container = document.querySelector(viewSelector);
|
|
if (!container) return;
|
|
|
|
// Cleanup previous page
|
|
if (currentCleanup && typeof currentCleanup === 'function') {
|
|
currentCleanup();
|
|
currentCleanup = null;
|
|
}
|
|
|
|
// Clear container
|
|
container.innerHTML = '';
|
|
|
|
// Call onEnter with match groups + container
|
|
if (typeof r.onEnter === 'function') {
|
|
var result = r.onEnter(match, container);
|
|
if (typeof result === 'function') {
|
|
currentCleanup = result;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
function start(selector) {
|
|
viewSelector = selector;
|
|
window.addEventListener('hashchange', function () {
|
|
navigate(window.location.hash);
|
|
});
|
|
// Initial navigation
|
|
if (window.location.hash) {
|
|
navigate(window.location.hash);
|
|
}
|
|
}
|
|
|
|
function go(hash) {
|
|
window.location.hash = hash;
|
|
}
|
|
|
|
return {
|
|
add: add,
|
|
start: start,
|
|
go: go,
|
|
navigate: navigate
|
|
};
|
|
})();
|