doli-front/src/router.js

75 lines
2.1 KiB
JavaScript
Raw Normal View History

import { auth } from './services/auth.js';
import { renderLoginPage } from './pages/LoginPage.js';
import { createSidebar } from './components/Sidebar.js';
import { getAvailablePages, getPageByRoute } from './pages/pagesRegistry.js';
// 🔧 Modo DEV: cambiar a false para activar login
const DEV_MODE = false;
export function initRouter() {
const app = document.querySelector('#app');
function navigate() {
const hash = window.location.hash || (DEV_MODE ? '#dashboard' : '#login');
const route = hash.substring(1); // Remove the # symbol
if (!DEV_MODE && !auth.checkAuth() && hash !== '#login') {
window.location.hash = '#login';
return;
}
app.innerHTML = '';
// For authenticated routes, add sidebar and main content wrapper
const isAuthenticated = DEV_MODE || auth.checkAuth();
if (isAuthenticated && hash !== '#login') {
const layout = document.createElement('div');
layout.className = 'app-layout';
// Create sidebar
const pages = getAvailablePages(true);
const sidebar = createSidebar(pages, route);
// Create main content area
const mainContent = document.createElement('main');
mainContent.className = 'main-content';
// Get page from registry
const page = getPageByRoute(route);
if (!page) {
// For unregistered routes, redirect to dashboard
window.location.hash = '#dashboard';
return;
}
if (!DEV_MODE && page.requiresAuth && !auth.checkAuth()) {
window.location.hash = '#login';
return;
}
// Render page content using registry
const pageContent = page.render();
mainContent.appendChild(pageContent);
layout.appendChild(sidebar);
layout.appendChild(mainContent);
app.appendChild(layout);
} else {
// For login page, no sidebar
switch (hash) {
case '#login':
app.appendChild(renderLoginPage(() => {
window.location.hash = '#dashboard';
}));
break;
default:
window.location.hash = '#login';
}
}
}
window.addEventListener('hashchange', navigate);
navigate();
}