Files
emailtemplate.it/public/assets/js/app.js
2025-12-07 02:49:46 +01:00

87 lines
2.7 KiB
JavaScript

// assets/js/app.js
import { initTabs } from './ui-tabs.js';
import { initLists } from './ui-list.js';
import { initCreate } from './ui-create.js';
import { initEditor } from './ui-editor.js';
import { initUserPanel } from './ui-user.js';
import { mountLogoutButton, ensureFloatingLogout } from './ui-auth.js';
import { apiAction } from './api.js';
/**
* Zeigt die App erst, wenn Auth validiert ist.
* Wichtig: KEIN finally → nur im Erfolgsfall UI freigeben (verhindert Flashing für Gäste).
*/
async function ensureAuthenticated() {
try {
const me = await apiAction('auth.me', { method: 'GET' });
if (!me?.ok || !me?.user) {
window.location.href = '/login.php';
return false;
}
window.__currentUser = me.user;
// ✅ nur für eingeloggte Nutzer: UI freigebensss
document.documentElement.classList.remove('auth-pending');
const appRoot = document.getElementById('app');
if (appRoot && appRoot.hasAttribute('hidden')) appRoot.removeAttribute('hidden');
return true;
} catch {
// apiAction leitet bei 401 ohnehin um
return false;
}
}
function initAppFeatures() {
initTabs();
initLists();
initCreate();
initEditor();
initUserPanel();
// Logout-Buttons
mountLogoutButton('#btn-logout', { redirect: '/login.php' });
ensureFloatingLogout({ redirect: '/login.php' });
}
// Sync-Nachrichten aus dem Editor-Iframe (unverändert, aber mit credentials)
async function handleEditorMessages(ev) {
const msg = ev.data || {};
if (msg.source !== 'email-editor' || msg.type !== 'save') return;
try {
const ctx = window.__currentEditorCtx || {};
const id = ctx.id;
const mode = (ctx.mode || msg.mode || '').toLowerCase();
const refs = Array.isArray(msg.refs) ? msg.refs : [];
if (!id || !mode) return;
if (mode === 'templates') {
await fetch('./api.php?resource=template_items&action=sync', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ template_id: id, items: refs })
});
} else if (mode === 'sections') {
await fetch('./api.php?resource=section_items&action=sync', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ section_id: id, items: refs.filter(r => r.ref_type === 'block') })
});
}
} catch (e) {
console.error('refs sync failed', e);
}
}
document.addEventListener('DOMContentLoaded', async () => {
const ok = await ensureAuthenticated();
if (!ok) return; // Gast → Redirect, UI bleibt verborgen
initAppFeatures(); // Eingeloggt → App initialisieren
});
window.addEventListener('message', handleEditorMessages);