920 lines
34 KiB
JavaScript
920 lines
34 KiB
JavaScript
/**
|
|||
|
|
* @file component-loader.js
|
||
|
|
* @description Loads shared EJS components (header, navbar) dynamically into static HTML pages
|
||
|
|
*
|
||
|
|
* Usage:
|
||
|
|
* await NCComponentLoader.load({
|
||
|
|
* siteTitle: 'MediaViewer',
|
||
|
|
* title: 'Home',
|
||
|
|
* headerCenterHTML: '<div>Custom header content</div>',
|
||
|
|
* navbarVariant: 'default',
|
||
|
|
* navbarItems: [{ label: 'Home', href: '/', icon: 'fas fa-home' }],
|
||
|
|
* navbarCurrentPath: window.location.pathname,
|
||
|
|
* });
|
||
|
|
*
|
||
|
|
* headerCenterHTML is rendered directly in the browser (never sent to the server as
|
||
|
|
* a query param) and inserted into the header's `[data-header-center-slot]` element.
|
||
|
|
* It must be a hardcoded string the caller owns — never interpolate user-controlled
|
||
|
|
* data into it, since it's set via innerHTML with no escaping.
|
||
|
|
*/
|
||
|
|
|
||
|
|
(function (window) {
|
||
|
|
'use strict';
|
||
|
|
|
||
|
|
const TOPBAR_SELECTOR = 'header[data-topbar="1"]';
|
||
|
|
|
||
|
|
const NCComponentLoader = {
|
||
|
|
/**
|
||
|
|
* Load shared header and navbar components
|
||
|
|
* @param {Object} options - Configuration for header/navbar rendering
|
||
|
|
* @param {string} options.siteTitle - Site/app title (e.g., 'MediaViewer')
|
||
|
|
* @param {string} options.title - Page title (e.g., 'Home')
|
||
|
|
* @param {string} [options.headerCenterHTML] - Hardcoded HTML the caller owns, inserted
|
||
|
|
* client-side into the header's center slot. Never derive this from user input.
|
||
|
|
* @param {boolean} [options.disableSignup] - Hide signup button
|
||
|
|
* @param {boolean} [options.enableSocketIO] - Load Socket.IO script
|
||
|
|
* @param {string} [options.appCssHref] - Additional app-specific CSS href
|
||
|
|
* @param {string} [options.extraScripts] - Additional scripts to load in footer
|
||
|
|
* @param {string} [options.navbarVariant] - Navbar variant identifier (e.g. 'default', 'admin')
|
||
|
|
* @param {Array} [options.navbarItems] - Array of { label, href, icon } nav items
|
||
|
|
* @param {string} [options.navbarCurrentPath] - Current path for active-link highlighting
|
||
|
|
* @param {string} [options.authPageToken] - Explicit token for /auth/me page-level requirement lookup
|
||
|
|
* @param {string} [options.navbarActive] - Explicit active item href (fallback)
|
||
|
|
* @returns {Promise<void>}
|
||
|
|
*/
|
||
|
|
async load(options = {}) {
|
||
|
|
const {
|
||
|
|
siteTitle = 'App',
|
||
|
|
title = '',
|
||
|
|
headerCenterHTML = '',
|
||
|
|
disableSignup = false,
|
||
|
|
enableSocketIO = false,
|
||
|
|
appCssHref = '',
|
||
|
|
// eslint-disable-next-line no-unused-vars
|
||
|
|
extraScripts: _extraScripts = '',
|
||
|
|
navbarVariant = '',
|
||
|
|
navbarItems = [],
|
||
|
|
navbarCurrentPath = '',
|
||
|
|
authPageToken = '',
|
||
|
|
// eslint-disable-next-line no-unused-vars
|
||
|
|
navbarActive: _navbarActive = '',
|
||
|
|
} = options;
|
||
|
|
|
||
|
|
try {
|
||
|
|
const resolvedNavbarCurrentPath = navbarCurrentPath || window.location.pathname;
|
||
|
|
const resolvedTitle = this._resolveTitleForLoad({
|
||
|
|
siteTitle,
|
||
|
|
title,
|
||
|
|
navbarItems,
|
||
|
|
navbarCurrentPath: resolvedNavbarCurrentPath,
|
||
|
|
});
|
||
|
|
|
||
|
|
this._navbarTitleContext = {
|
||
|
|
siteTitle,
|
||
|
|
navbarItems: Array.isArray(navbarItems) ? navbarItems : [],
|
||
|
|
};
|
||
|
|
this._bindNavbarTitleSync();
|
||
|
|
this._setDocumentTitle(siteTitle, resolvedTitle);
|
||
|
|
|
||
|
|
const resolvedAuthPageToken = this._resolveAuthPageToken(
|
||
|
|
authPageToken,
|
||
|
|
resolvedNavbarCurrentPath
|
||
|
|
);
|
||
|
|
|
||
|
|
const authState = await this._getAuthState(resolvedAuthPageToken);
|
||
|
|
window.__NC_AUTH_STATE = authState;
|
||
|
|
window.__NC_ACTIVE_PAGE_TOKEN =
|
||
|
|
authState.pageToken || this._normalizePageToken(resolvedAuthPageToken);
|
||
|
|
this._bindProtectedNavGuard();
|
||
|
|
const hideHeaderForAuth = this._isAuthRequiredWithoutUser(authState);
|
||
|
|
const hasNavbarConfig =
|
||
|
|
!!navbarVariant && Array.isArray(navbarItems) && navbarItems.length > 1;
|
||
|
|
const isDesktopViewport = this._isDesktopViewport();
|
||
|
|
const renderDesktopNavbar = hasNavbarConfig && isDesktopViewport && !hideHeaderForAuth;
|
||
|
|
|
||
|
|
// Build query string for header endpoint
|
||
|
|
const headerParams = new URLSearchParams({
|
||
|
|
siteTitle,
|
||
|
|
title: resolvedTitle,
|
||
|
|
disableSignup: disableSignup.toString(),
|
||
|
|
enableSocketIO: enableSocketIO.toString(),
|
||
|
|
appCssHref,
|
||
|
|
navbarVariant,
|
||
|
|
navbarItems: JSON.stringify(hasNavbarConfig ? navbarItems : []),
|
||
|
|
navbarCurrentPath: resolvedNavbarCurrentPath,
|
||
|
|
renderDesktopNavbar: renderDesktopNavbar.toString(),
|
||
|
|
});
|
||
|
|
|
||
|
|
// Fetch header
|
||
|
|
const headerResponse = await fetch(`/api/components/header?${headerParams}`);
|
||
|
|
if (!headerResponse.ok) {
|
||
|
|
throw new Error(`Failed to load header: ${headerResponse.status}`);
|
||
|
|
}
|
||
|
|
const headerHTML = await headerResponse.text();
|
||
|
|
|
||
|
|
// Inject header into placeholder
|
||
|
|
const headerPlaceholder = document.getElementById('header-placeholder');
|
||
|
|
if (headerPlaceholder) {
|
||
|
|
headerPlaceholder.innerHTML = headerHTML;
|
||
|
|
} else {
|
||
|
|
console.warn(
|
||
|
|
'[ComponentLoader] #header-placeholder not found; prepending header to body'
|
||
|
|
);
|
||
|
|
document.body.insertAdjacentHTML('afterbegin', headerHTML);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (headerCenterHTML) {
|
||
|
|
const centerSlot = document.querySelector('[data-header-center-slot]');
|
||
|
|
if (centerSlot) centerSlot.innerHTML = headerCenterHTML;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (hideHeaderForAuth) {
|
||
|
|
this._hideHeaderForAuthState();
|
||
|
|
}
|
||
|
|
|
||
|
|
// Re-initialize scripts that depend on dynamically loaded elements
|
||
|
|
// (auth-modal.js, theme-toggle.js, etc. should auto-initialize on DOMContentLoaded)
|
||
|
|
|
||
|
|
// Fetch and inject mobile navbar markup whenever nav config exists.
|
||
|
|
// CSS media queries handle visibility per viewport.
|
||
|
|
if (hasNavbarConfig) {
|
||
|
|
try {
|
||
|
|
const shouldRenderMobileNavbar = !hideHeaderForAuth;
|
||
|
|
if (!shouldRenderMobileNavbar) {
|
||
|
|
const existingNav = document.querySelector('nav[data-mobile-nav="1"]');
|
||
|
|
if (existingNav) existingNav.remove();
|
||
|
|
const navbarPlaceholder = document.getElementById('navbar-placeholder');
|
||
|
|
if (navbarPlaceholder) navbarPlaceholder.innerHTML = '';
|
||
|
|
} else {
|
||
|
|
const navbarParams = new URLSearchParams({
|
||
|
|
navbarVariant,
|
||
|
|
navbarItems: JSON.stringify(navbarItems),
|
||
|
|
navbarCurrentPath: resolvedNavbarCurrentPath,
|
||
|
|
});
|
||
|
|
const navbarResponse = await fetch(`/api/components/navbar?${navbarParams}`);
|
||
|
|
if (navbarResponse.ok) {
|
||
|
|
const navbarHTML = await navbarResponse.text();
|
||
|
|
const existingNav = document.querySelector('nav[data-mobile-nav="1"]');
|
||
|
|
if (existingNav) {
|
||
|
|
existingNav.remove();
|
||
|
|
}
|
||
|
|
const navbarPlaceholder = document.getElementById('navbar-placeholder');
|
||
|
|
const headerPlaceholder = document.getElementById('header-placeholder');
|
||
|
|
if (navbarPlaceholder) {
|
||
|
|
navbarPlaceholder.outerHTML = navbarHTML;
|
||
|
|
} else if (headerPlaceholder) {
|
||
|
|
headerPlaceholder.insertAdjacentHTML('beforeend', navbarHTML);
|
||
|
|
} else {
|
||
|
|
const topbar = document.querySelector('header[data-topbar="1"]');
|
||
|
|
if (topbar) {
|
||
|
|
topbar.insertAdjacentHTML('afterend', navbarHTML);
|
||
|
|
} else {
|
||
|
|
document.body.insertAdjacentHTML('beforeend', navbarHTML);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
} catch (navErr) {
|
||
|
|
console.warn('[ComponentLoader] Failed to load navbar:', navErr);
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
const existingNav = document.querySelector('nav[data-mobile-nav="1"]');
|
||
|
|
if (existingNav) existingNav.remove();
|
||
|
|
const navbarPlaceholder = document.getElementById('navbar-placeholder');
|
||
|
|
if (navbarPlaceholder) navbarPlaceholder.innerHTML = '';
|
||
|
|
}
|
||
|
|
|
||
|
|
this._syncTopbarMetrics();
|
||
|
|
this._syncBottomNavMetrics();
|
||
|
|
this._syncScrollShell();
|
||
|
|
this._applyAutoTopbarGap();
|
||
|
|
this._bindScrollShellObserver();
|
||
|
|
|
||
|
|
this._triggerScriptInitialization();
|
||
|
|
} catch (error) {
|
||
|
|
console.error('[ComponentLoader] Failed to load components:', error);
|
||
|
|
// Fallback: show a basic error message
|
||
|
|
document.body.insertAdjacentHTML(
|
||
|
|
'afterbegin',
|
||
|
|
`
|
||
|
|
<div style="background: #c53030; color: white; padding: 1rem; text-align: center;">
|
||
|
|
Failed to load page components. Please refresh the page.
|
||
|
|
</div>
|
||
|
|
`
|
||
|
|
);
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Trigger re-initialization of scripts that need dynamically loaded DOM elements
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_triggerScriptInitialization() {
|
||
|
|
// Dispatch custom event for scripts that need to re-initialize
|
||
|
|
const event = new CustomEvent('nc:componentsLoaded', {
|
||
|
|
bubbles: true,
|
||
|
|
cancelable: false,
|
||
|
|
});
|
||
|
|
document.dispatchEvent(event);
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Keep topbar-related CSS variables in sync with rendered header height.
|
||
|
|
* This avoids overlap when the fixed header height changes due to responsive content.
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_syncTopbarMetrics() {
|
||
|
|
const topbar = document.querySelector(TOPBAR_SELECTOR);
|
||
|
|
if (topbar) {
|
||
|
|
const height = Math.ceil(topbar.getBoundingClientRect().height || 0);
|
||
|
|
if (height) {
|
||
|
|
const px = `${height}px`;
|
||
|
|
document.documentElement.style.setProperty('--bar-height', px);
|
||
|
|
document.documentElement.style.setProperty('--topbar-height', px);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!this._resizeSyncBound) {
|
||
|
|
this._resizeSyncBound = true;
|
||
|
|
window.addEventListener('resize', () => {
|
||
|
|
if (this._resizeRaf) {
|
||
|
|
window.cancelAnimationFrame(this._resizeRaf);
|
||
|
|
}
|
||
|
|
this._resizeRaf = window.requestAnimationFrame(() => {
|
||
|
|
this._syncTopbarMetrics();
|
||
|
|
this._syncBottomNavMetrics();
|
||
|
|
this._syncScrollShell();
|
||
|
|
this._applyAutoTopbarGap();
|
||
|
|
});
|
||
|
|
});
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Resolve the currently visible fixed mobile navigation bar.
|
||
|
|
* @returns {HTMLElement | null}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_getVisibleMobileNav() {
|
||
|
|
const nav = document.querySelector('nav[data-bottom-nav][data-mobile-nav="1"]');
|
||
|
|
if (!nav || nav.hidden || nav.classList.contains('hidden')) return null;
|
||
|
|
|
||
|
|
const style = window.getComputedStyle(nav);
|
||
|
|
if (style.display === 'none' || style.visibility === 'hidden') return null;
|
||
|
|
if (style.position !== 'fixed') return null;
|
||
|
|
|
||
|
|
return nav;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Keep bottom-nav height variable in sync with the currently visible fixed mobile nav.
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_syncBottomNavMetrics() {
|
||
|
|
const mobileNav = this._getVisibleMobileNav();
|
||
|
|
const navHeight = mobileNav ? Math.ceil(mobileNav.getBoundingClientRect().height || 0) : 0;
|
||
|
|
document.documentElement.style.setProperty(
|
||
|
|
'--bottom-nav-height',
|
||
|
|
`${Math.max(0, navHeight)}px`
|
||
|
|
);
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Determine whether a candidate scroll host is currently visible.
|
||
|
|
* @param {HTMLElement | null} element
|
||
|
|
* @returns {boolean}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_isElementScrollHostVisible(element) {
|
||
|
|
if (!element) return false;
|
||
|
|
|
||
|
|
let node = element;
|
||
|
|
while (node && node.nodeType === 1) {
|
||
|
|
if (node.hidden || node.classList.contains('hidden')) return false;
|
||
|
|
if (String(node.getAttribute('aria-hidden') || '').toLowerCase() === 'true') return false;
|
||
|
|
|
||
|
|
const style = window.getComputedStyle(node);
|
||
|
|
if (style.display === 'none' || style.visibility === 'hidden') return false;
|
||
|
|
|
||
|
|
node = node.parentElement;
|
||
|
|
}
|
||
|
|
|
||
|
|
return true;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Pick the primary page content scroll host.
|
||
|
|
* @returns {HTMLElement | null}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_resolveScrollHost() {
|
||
|
|
const selectors = [
|
||
|
|
'main.fixed.left-0.right-0.overflow-y-auto',
|
||
|
|
'body > main',
|
||
|
|
'body > #main-content',
|
||
|
|
'body > .page-panel > main',
|
||
|
|
'body > .page-panel > #main-content',
|
||
|
|
];
|
||
|
|
|
||
|
|
for (const selector of selectors) {
|
||
|
|
const candidates = Array.from(document.querySelectorAll(selector));
|
||
|
|
const visibleCandidate = candidates.find(candidate =>
|
||
|
|
this._isElementScrollHostVisible(candidate)
|
||
|
|
);
|
||
|
|
if (visibleCandidate) return visibleCandidate;
|
||
|
|
}
|
||
|
|
|
||
|
|
for (const selector of selectors) {
|
||
|
|
const fallbackCandidate = document.querySelector(selector);
|
||
|
|
if (fallbackCandidate) return fallbackCandidate;
|
||
|
|
}
|
||
|
|
|
||
|
|
return null;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Parse a CSS length-like value into pixels with a safe fallback.
|
||
|
|
* @param {string} value
|
||
|
|
* @param {number} fallback
|
||
|
|
* @returns {number}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_parsePixelValue(value, fallback = 0) {
|
||
|
|
const parsed = Number.parseFloat(String(value || '').trim());
|
||
|
|
return Number.isFinite(parsed) ? parsed : fallback;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Keep non-fixed scroll hosts constrained to the viewport so they can scroll internally.
|
||
|
|
* @param {HTMLElement | null} scrollHost
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_syncScrollHostHeight(scrollHost) {
|
||
|
|
if (!scrollHost || scrollHost.classList.contains('fixed')) return;
|
||
|
|
|
||
|
|
const rootStyle = window.getComputedStyle(document.documentElement);
|
||
|
|
const topbarHeight = this._parsePixelValue(rootStyle.getPropertyValue('--topbar-height'), 56);
|
||
|
|
const bottomNavHeight = this._parsePixelValue(
|
||
|
|
rootStyle.getPropertyValue('--bottom-nav-height'),
|
||
|
|
0
|
||
|
|
);
|
||
|
|
const viewportHeight = window.innerHeight || document.documentElement.clientHeight || 0;
|
||
|
|
const boundedHeight = Math.max(
|
||
|
|
0,
|
||
|
|
Math.round(viewportHeight - topbarHeight - bottomNavHeight)
|
||
|
|
);
|
||
|
|
|
||
|
|
if (boundedHeight > 0) {
|
||
|
|
scrollHost.style.height = `${boundedHeight}px`;
|
||
|
|
scrollHost.dataset.ncScrollHostHeightManaged = '1';
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Keep non-fixed scroll host scrollbar at the viewport edge while preserving centered content gutters.
|
||
|
|
* @param {HTMLElement | null} scrollHost
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_syncScrollHostInlineGutters(scrollHost) {
|
||
|
|
if (!scrollHost || scrollHost.classList.contains('fixed')) {
|
||
|
|
this._clearManagedScrollHostInlineGutters(scrollHost);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (scrollHost.dataset.ncScrollHostInlineGutterManaged === '1') {
|
||
|
|
this._clearManagedScrollHostInlineGutters(scrollHost);
|
||
|
|
}
|
||
|
|
|
||
|
|
const style = window.getComputedStyle(scrollHost);
|
||
|
|
const viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0;
|
||
|
|
const hostMaxWidth = this._parsePixelValue(style.maxWidth, 0);
|
||
|
|
const hostRectWidth = Math.round(scrollHost.getBoundingClientRect().width || 0);
|
||
|
|
const constrainedWidth = hostMaxWidth > 0 ? hostMaxWidth : hostRectWidth;
|
||
|
|
|
||
|
|
// Only widen hosts that are intentionally constrained and centered.
|
||
|
|
if (!(constrainedWidth > 0 && viewportWidth - constrainedWidth > 1)) return;
|
||
|
|
|
||
|
|
const basePaddingLeft = this._parsePixelValue(style.paddingLeft, 0);
|
||
|
|
const basePaddingRight = this._parsePixelValue(style.paddingRight, 0);
|
||
|
|
const sideGutter = Math.max(0, Math.round((viewportWidth - constrainedWidth) / 2));
|
||
|
|
|
||
|
|
scrollHost.dataset.ncPrevInlineMaxWidth = scrollHost.style.maxWidth || '';
|
||
|
|
scrollHost.dataset.ncPrevInlineMarginLeft = scrollHost.style.marginLeft || '';
|
||
|
|
scrollHost.dataset.ncPrevInlineMarginRight = scrollHost.style.marginRight || '';
|
||
|
|
scrollHost.dataset.ncPrevInlineWidth = scrollHost.style.width || '';
|
||
|
|
scrollHost.dataset.ncPrevInlinePaddingLeft = scrollHost.style.paddingLeft || '';
|
||
|
|
scrollHost.dataset.ncPrevInlinePaddingRight = scrollHost.style.paddingRight || '';
|
||
|
|
|
||
|
|
// Width:auto ensures left/right fixed offsets remain authoritative on the scroll host.
|
||
|
|
scrollHost.style.width = 'auto';
|
||
|
|
scrollHost.style.maxWidth = 'none';
|
||
|
|
scrollHost.style.marginLeft = '0';
|
||
|
|
scrollHost.style.marginRight = '0';
|
||
|
|
scrollHost.style.paddingLeft = `${basePaddingLeft + sideGutter}px`;
|
||
|
|
scrollHost.style.paddingRight = `${basePaddingRight + sideGutter}px`;
|
||
|
|
scrollHost.dataset.ncScrollHostInlineGutterManaged = '1';
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Remove inline gutter overrides used to keep the scrollbar at viewport edge.
|
||
|
|
* @param {HTMLElement | null} scrollHost
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_clearManagedScrollHostInlineGutters(scrollHost) {
|
||
|
|
if (!scrollHost || scrollHost.dataset.ncScrollHostInlineGutterManaged !== '1') return;
|
||
|
|
|
||
|
|
scrollHost.style.maxWidth = scrollHost.dataset.ncPrevInlineMaxWidth || '';
|
||
|
|
scrollHost.style.marginLeft = scrollHost.dataset.ncPrevInlineMarginLeft || '';
|
||
|
|
scrollHost.style.marginRight = scrollHost.dataset.ncPrevInlineMarginRight || '';
|
||
|
|
scrollHost.style.width = scrollHost.dataset.ncPrevInlineWidth || '';
|
||
|
|
scrollHost.style.paddingLeft = scrollHost.dataset.ncPrevInlinePaddingLeft || '';
|
||
|
|
scrollHost.style.paddingRight = scrollHost.dataset.ncPrevInlinePaddingRight || '';
|
||
|
|
|
||
|
|
delete scrollHost.dataset.ncPrevInlineMaxWidth;
|
||
|
|
delete scrollHost.dataset.ncPrevInlineMarginLeft;
|
||
|
|
delete scrollHost.dataset.ncPrevInlineMarginRight;
|
||
|
|
delete scrollHost.dataset.ncPrevInlineWidth;
|
||
|
|
delete scrollHost.dataset.ncPrevInlinePaddingLeft;
|
||
|
|
delete scrollHost.dataset.ncPrevInlinePaddingRight;
|
||
|
|
delete scrollHost.dataset.ncScrollHostInlineGutterManaged;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Remove previously managed scroll-host height overrides.
|
||
|
|
* @param {HTMLElement | null} scrollHost
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_clearManagedScrollHostHeight(scrollHost) {
|
||
|
|
if (!scrollHost || scrollHost.dataset.ncScrollHostHeightManaged !== '1') return;
|
||
|
|
scrollHost.style.removeProperty('height');
|
||
|
|
delete scrollHost.dataset.ncScrollHostHeightManaged;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Ensure page scrolling happens inside content instead of the document body.
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_syncScrollShell() {
|
||
|
|
if (!document.body) return;
|
||
|
|
|
||
|
|
const scrollHost = this._resolveScrollHost();
|
||
|
|
const root = document.documentElement;
|
||
|
|
|
||
|
|
if (this._scrollHost && this._scrollHost !== scrollHost) {
|
||
|
|
this._clearManagedScrollHostHeight(this._scrollHost);
|
||
|
|
this._clearManagedScrollHostInlineGutters(this._scrollHost);
|
||
|
|
this._scrollHost.classList.remove('nc-scroll-host');
|
||
|
|
}
|
||
|
|
|
||
|
|
this._scrollHost = scrollHost || null;
|
||
|
|
|
||
|
|
if (!scrollHost) {
|
||
|
|
document.body.classList.remove('nc-content-scroll-shell');
|
||
|
|
root.classList.remove('nc-content-scroll-shell-root');
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
document.body.classList.add('nc-content-scroll-shell');
|
||
|
|
root.classList.add('nc-content-scroll-shell-root');
|
||
|
|
|
||
|
|
if (scrollHost.classList.contains('fixed')) {
|
||
|
|
this._clearManagedScrollHostHeight(scrollHost);
|
||
|
|
this._clearManagedScrollHostInlineGutters(scrollHost);
|
||
|
|
scrollHost.classList.remove('nc-scroll-host');
|
||
|
|
} else {
|
||
|
|
scrollHost.classList.add('nc-scroll-host');
|
||
|
|
this._syncScrollHostHeight(scrollHost);
|
||
|
|
this._syncScrollHostInlineGutters(scrollHost);
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Schedule a single-frame sync for topbar/nav metrics and scroll shell classes.
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_scheduleScrollShellSync() {
|
||
|
|
if (this._scrollShellRaf) {
|
||
|
|
window.cancelAnimationFrame(this._scrollShellRaf);
|
||
|
|
}
|
||
|
|
|
||
|
|
this._scrollShellRaf = window.requestAnimationFrame(() => {
|
||
|
|
this._scrollShellRaf = null;
|
||
|
|
this._syncTopbarMetrics();
|
||
|
|
this._syncBottomNavMetrics();
|
||
|
|
this._syncScrollShell();
|
||
|
|
this._applyAutoTopbarGap();
|
||
|
|
});
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Determine whether a mutation can affect scroll-shell host selection or offsets.
|
||
|
|
* @param {MutationRecord[]} mutationList
|
||
|
|
* @returns {boolean}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_shouldResyncScrollShellForMutation(mutationList) {
|
||
|
|
const relevantSelector =
|
||
|
|
'main, #main-content, .page-panel, nav[data-bottom-nav], header[data-topbar="1"], body';
|
||
|
|
|
||
|
|
const isElementNode = node => node && node.nodeType === 1;
|
||
|
|
const hasRelevantNode = node => {
|
||
|
|
if (!isElementNode(node)) return false;
|
||
|
|
if (node.matches(relevantSelector)) return true;
|
||
|
|
return !!node.querySelector(relevantSelector);
|
||
|
|
};
|
||
|
|
|
||
|
|
for (const mutation of mutationList) {
|
||
|
|
if (mutation.type === 'attributes') {
|
||
|
|
if (isElementNode(mutation.target) && mutation.target.matches(relevantSelector)) {
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (mutation.type === 'childList') {
|
||
|
|
const target = mutation.target;
|
||
|
|
if (
|
||
|
|
!isElementNode(target) ||
|
||
|
|
!target.matches('body, .page-panel, #header-placeholder, #navbar-placeholder')
|
||
|
|
) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
|
||
|
|
for (const node of mutation.addedNodes) {
|
||
|
|
if (hasRelevantNode(node)) return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
for (const node of mutation.removedNodes) {
|
||
|
|
if (hasRelevantNode(node)) return true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return false;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Keep the scroll shell in sync when panel visibility or fixed chrome changes at runtime.
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_bindScrollShellObserver() {
|
||
|
|
if (this._scrollShellObserverBound || !document.body || !window.MutationObserver) return;
|
||
|
|
this._scrollShellObserverBound = true;
|
||
|
|
|
||
|
|
this._scrollShellObserver = new MutationObserver(mutationList => {
|
||
|
|
if (!this._shouldResyncScrollShellForMutation(mutationList)) return;
|
||
|
|
this._scheduleScrollShellSync();
|
||
|
|
});
|
||
|
|
|
||
|
|
this._scrollShellObserver.observe(document.body, {
|
||
|
|
subtree: true,
|
||
|
|
childList: true,
|
||
|
|
attributes: true,
|
||
|
|
attributeFilter: ['class', 'hidden', 'style', 'aria-hidden'],
|
||
|
|
});
|
||
|
|
|
||
|
|
if (!this._scrollShellHistoryBound) {
|
||
|
|
this._scrollShellHistoryBound = true;
|
||
|
|
window.addEventListener('hashchange', () => this._scheduleScrollShellSync());
|
||
|
|
window.addEventListener('popstate', () => this._scheduleScrollShellSync());
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Detect whether page content already has a topbar offset.
|
||
|
|
* @returns {boolean}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_hasExplicitTopbarOffset() {
|
||
|
|
const classBasedOffset = document.querySelector(
|
||
|
|
'.pt-topbar-gap, [class*="pt-[var(--topbar-height"], [class*="pt-[calc(var(--topbar-height"]'
|
||
|
|
);
|
||
|
|
if (classBasedOffset) return true;
|
||
|
|
|
||
|
|
const inlineOffset = document.querySelector(
|
||
|
|
'[style*="padding-top"][style*="--topbar-height"], [style*="top: calc(var(--topbar-height"], [style*="top: var(--topbar-height"]'
|
||
|
|
);
|
||
|
|
return !!inlineOffset;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Apply a safe fallback top gap only when a fixed topbar is present and no explicit gap exists.
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_applyAutoTopbarGap() {
|
||
|
|
const topbar = document.querySelector(TOPBAR_SELECTOR);
|
||
|
|
const topbarHidden =
|
||
|
|
!topbar || topbar.hidden || topbar.classList.contains('hidden') || !topbar.offsetParent;
|
||
|
|
if (topbarHidden || !document.body) {
|
||
|
|
if (document.body) document.body.classList.remove('nc-auto-topbar-gap');
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
if (document.body.classList.contains('nc-content-scroll-shell')) {
|
||
|
|
document.body.classList.remove('nc-auto-topbar-gap');
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
if (this._hasExplicitTopbarOffset()) {
|
||
|
|
document.body.classList.remove('nc-auto-topbar-gap');
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
document.body.classList.add('nc-auto-topbar-gap');
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Determine whether current viewport is desktop width.
|
||
|
|
* @returns {boolean}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_isDesktopViewport() {
|
||
|
|
try {
|
||
|
|
return !!window.matchMedia && window.matchMedia('(min-width: 768px)').matches;
|
||
|
|
} catch {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Normalize a page token (path+query or hash token) for reliable key lookups.
|
||
|
|
* @param {string} value
|
||
|
|
* @returns {string}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_normalizePageToken(value) {
|
||
|
|
const raw = String(value || '').trim();
|
||
|
|
if (!raw) return '/';
|
||
|
|
if (raw.startsWith('#')) return raw.toLowerCase();
|
||
|
|
try {
|
||
|
|
const parsed = new URL(raw, window.location.origin);
|
||
|
|
const pathname = String(parsed.pathname || '/').toLowerCase();
|
||
|
|
const search = parsed.searchParams.toString().toLowerCase();
|
||
|
|
const hash = String(parsed.hash || '').toLowerCase();
|
||
|
|
if (hash && (pathname === '/' || pathname === '') && !search) return hash;
|
||
|
|
return search ? `${pathname}?${search}` : pathname;
|
||
|
|
} catch {
|
||
|
|
return raw.toLowerCase();
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Compose a canonical browser title in "Project - Tab" form.
|
||
|
|
* @param {string} siteTitle
|
||
|
|
* @param {string} tabTitle
|
||
|
|
* @returns {string}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_composeDocumentTitle(siteTitle, tabTitle = '') {
|
||
|
|
const normalizedSiteTitle = String(siteTitle || '').trim() || 'App';
|
||
|
|
const normalizedTabTitle = String(tabTitle || '').trim();
|
||
|
|
return normalizedTabTitle
|
||
|
|
? `${normalizedSiteTitle} - ${normalizedTabTitle}`
|
||
|
|
: normalizedSiteTitle;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Update the active browser tab title.
|
||
|
|
* @param {string} siteTitle
|
||
|
|
* @param {string} tabTitle
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_setDocumentTitle(siteTitle, tabTitle = '') {
|
||
|
|
document.title = this._composeDocumentTitle(siteTitle, tabTitle);
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Resolve navbar label by href/path token.
|
||
|
|
* @param {Array} navbarItems
|
||
|
|
* @param {string} hrefValue
|
||
|
|
* @returns {string}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_resolveNavbarLabel(navbarItems, hrefValue) {
|
||
|
|
if (!Array.isArray(navbarItems) || navbarItems.length === 0) return '';
|
||
|
|
|
||
|
|
const normalizedTarget = this._normalizePageToken(hrefValue);
|
||
|
|
for (const item of navbarItems) {
|
||
|
|
const normalizedItem = this._normalizePageToken(item && item.href ? item.href : '');
|
||
|
|
if (normalizedItem !== normalizedTarget) continue;
|
||
|
|
const label = String(item && item.label ? item.label : '').trim();
|
||
|
|
if (label) return label;
|
||
|
|
}
|
||
|
|
|
||
|
|
return '';
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Determine the title to render for initial component load.
|
||
|
|
* @param {{siteTitle: string, title: string, navbarItems: Array, navbarCurrentPath: string}} input
|
||
|
|
* @returns {string}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_resolveTitleForLoad(input = {}) {
|
||
|
|
const explicitTitle = String(input.title || '').trim();
|
||
|
|
if (explicitTitle) return explicitTitle;
|
||
|
|
|
||
|
|
const navbarItems = Array.isArray(input.navbarItems) ? input.navbarItems : [];
|
||
|
|
const fromCurrentPath = this._resolveNavbarLabel(navbarItems, input.navbarCurrentPath || '');
|
||
|
|
if (fromCurrentPath) return fromCurrentPath;
|
||
|
|
|
||
|
|
const fromLocation = this._resolveNavbarLabel(
|
||
|
|
navbarItems,
|
||
|
|
`${window.location.pathname || '/'}${window.location.search || ''}${window.location.hash || ''}`
|
||
|
|
);
|
||
|
|
if (fromLocation) return fromLocation;
|
||
|
|
|
||
|
|
const firstLabel = String(
|
||
|
|
navbarItems[0] && navbarItems[0].label ? navbarItems[0].label : ''
|
||
|
|
).trim();
|
||
|
|
return firstLabel || '';
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Keep browser title in sync with bottom-nav tab clicks.
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_bindNavbarTitleSync() {
|
||
|
|
if (this._navbarTitleSyncBound) return;
|
||
|
|
this._navbarTitleSyncBound = true;
|
||
|
|
|
||
|
|
document.addEventListener(
|
||
|
|
'click',
|
||
|
|
event => {
|
||
|
|
const link = event.target.closest('nav[data-bottom-nav] a[href]');
|
||
|
|
if (!link) return;
|
||
|
|
|
||
|
|
const context = this._navbarTitleContext || {};
|
||
|
|
const contextSiteTitle = String(context.siteTitle || '').trim();
|
||
|
|
const contextNavbarItems = Array.isArray(context.navbarItems) ? context.navbarItems : [];
|
||
|
|
if (!contextSiteTitle || contextNavbarItems.length === 0) return;
|
||
|
|
|
||
|
|
const href = link.getAttribute('href') || link.href || '';
|
||
|
|
const tabTitle =
|
||
|
|
this._resolveNavbarLabel(contextNavbarItems, href) ||
|
||
|
|
String(link.textContent || '').trim();
|
||
|
|
if (!tabTitle) return;
|
||
|
|
|
||
|
|
this._setDocumentTitle(contextSiteTitle, tabTitle);
|
||
|
|
},
|
||
|
|
true
|
||
|
|
);
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Resolve which page token should be used when probing /auth/me.
|
||
|
|
* @param {string} authPageToken
|
||
|
|
* @param {string} navbarCurrentPath
|
||
|
|
* @returns {string}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_resolveAuthPageToken(authPageToken, navbarCurrentPath) {
|
||
|
|
const explicitToken = String(authPageToken || '').trim();
|
||
|
|
if (explicitToken) return this._normalizePageToken(explicitToken);
|
||
|
|
|
||
|
|
const navbarToken = String(navbarCurrentPath || '').trim();
|
||
|
|
if (navbarToken) return this._normalizePageToken(navbarToken);
|
||
|
|
|
||
|
|
const locationToken = `${window.location.pathname || '/'}${window.location.search || ''}${window.location.hash || ''}`;
|
||
|
|
return this._normalizePageToken(locationToken);
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Determine whether the given page token is protected for current auth state.
|
||
|
|
* @param {string} pageToken
|
||
|
|
* @param {{loginRequiredPages?: object, loginRequiredAllPages?: boolean}} [authState]
|
||
|
|
* @returns {boolean}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_isPageLoginRequired(pageToken, authState = window.__NC_AUTH_STATE || {}) {
|
||
|
|
const requiredAllPages = authState.loginRequiredAllPages === true;
|
||
|
|
const requiredPages =
|
||
|
|
authState.loginRequiredPages && typeof authState.loginRequiredPages === 'object'
|
||
|
|
? authState.loginRequiredPages
|
||
|
|
: {};
|
||
|
|
|
||
|
|
const normalizedToken = this._normalizePageToken(pageToken);
|
||
|
|
return requiredAllPages || requiredPages[normalizedToken] === true;
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Attach a capturing nav click guard so protected tabs cannot be entered when logged out.
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_bindProtectedNavGuard() {
|
||
|
|
if (this._protectedNavGuardBound) return;
|
||
|
|
this._protectedNavGuardBound = true;
|
||
|
|
|
||
|
|
window.addEventListener('auth:login-success', () => {
|
||
|
|
const state = window.__NC_AUTH_STATE || {};
|
||
|
|
window.__NC_AUTH_STATE = {
|
||
|
|
...state,
|
||
|
|
user: state.user || { id: 'session' },
|
||
|
|
};
|
||
|
|
});
|
||
|
|
|
||
|
|
document.addEventListener(
|
||
|
|
'click',
|
||
|
|
event => {
|
||
|
|
const link = event.target.closest('nav[data-bottom-nav] a[href]');
|
||
|
|
if (!link) return;
|
||
|
|
|
||
|
|
const href = link.getAttribute('href') || link.href || '';
|
||
|
|
const pageToken = this._normalizePageToken(href);
|
||
|
|
window.__NC_ACTIVE_PAGE_TOKEN = pageToken;
|
||
|
|
|
||
|
|
const authState = window.__NC_AUTH_STATE || {};
|
||
|
|
if (authState.user) return;
|
||
|
|
|
||
|
|
const isProtected = this._isPageLoginRequired(pageToken, authState);
|
||
|
|
if (!isProtected) return;
|
||
|
|
|
||
|
|
event.preventDefault();
|
||
|
|
event.stopImmediatePropagation();
|
||
|
|
|
||
|
|
const loginButton = document.getElementById('authLoginOpenBtn');
|
||
|
|
if (loginButton) {
|
||
|
|
loginButton.click();
|
||
|
|
}
|
||
|
|
if (window.toast && typeof window.toast.info === 'function') {
|
||
|
|
window.toast.info('Log in is required for this page.');
|
||
|
|
}
|
||
|
|
},
|
||
|
|
true
|
||
|
|
);
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Fetch current auth state. Fail-open to avoid blocking page chrome on probe errors.
|
||
|
|
* @param {string} pageToken
|
||
|
|
* @returns {Promise<{authRequired: boolean, user: object | null}>}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
async _getAuthState(pageToken) {
|
||
|
|
const fallbackPage = `${window.location.pathname || '/'}${window.location.search || ''}${window.location.hash || ''}`;
|
||
|
|
const currentPage = this._normalizePageToken(pageToken || fallbackPage);
|
||
|
|
|
||
|
|
try {
|
||
|
|
const res = await fetch(`/auth/me?page=${encodeURIComponent(currentPage)}`, {
|
||
|
|
credentials: 'same-origin',
|
||
|
|
headers: { Accept: 'application/json' },
|
||
|
|
});
|
||
|
|
if (!res.ok) {
|
||
|
|
return {
|
||
|
|
authRequired: false,
|
||
|
|
user: null,
|
||
|
|
loginRequiredPages: {},
|
||
|
|
loginRequiredAllPages: false,
|
||
|
|
pageToken: currentPage,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
const auth = await res.json();
|
||
|
|
const pages =
|
||
|
|
auth && auth.loginRequiredPages && typeof auth.loginRequiredPages === 'object'
|
||
|
|
? auth.loginRequiredPages
|
||
|
|
: {};
|
||
|
|
return {
|
||
|
|
authRequired: !!(auth && auth.authRequired === true),
|
||
|
|
user: (auth && auth.user) || null,
|
||
|
|
loginRequiredPages: pages,
|
||
|
|
loginRequiredAllPages: !!(auth && auth.loginRequiredAllPages === true),
|
||
|
|
pageToken: currentPage,
|
||
|
|
};
|
||
|
|
} catch {
|
||
|
|
return {
|
||
|
|
authRequired: false,
|
||
|
|
user: null,
|
||
|
|
loginRequiredPages: {},
|
||
|
|
loginRequiredAllPages: false,
|
||
|
|
pageToken: currentPage,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Whether auth gate is enabled and there is no active session.
|
||
|
|
* @param {{authRequired: boolean, user: object | null}} authState
|
||
|
|
* @returns {boolean}
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_isAuthRequiredWithoutUser(authState) {
|
||
|
|
return !!(authState && authState.authRequired === true && !authState.user);
|
||
|
|
},
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Hide visible topbar chrome while keeping auth modal DOM available.
|
||
|
|
* @private
|
||
|
|
*/
|
||
|
|
_hideHeaderForAuthState() {
|
||
|
|
const topbar = document.querySelector(TOPBAR_SELECTOR);
|
||
|
|
if (topbar) {
|
||
|
|
topbar.classList.add('hidden');
|
||
|
|
topbar.setAttribute('aria-hidden', 'true');
|
||
|
|
}
|
||
|
|
document.documentElement.style.setProperty('--bar-height', '0px');
|
||
|
|
document.documentElement.style.setProperty('--topbar-height', '0px');
|
||
|
|
document.documentElement.style.setProperty('--bottom-nav-height', '0px');
|
||
|
|
if (document.body) document.body.classList.remove('nc-auto-topbar-gap');
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
// Export to global namespace
|
||
|
|
window.NCComponentLoader = NCComponentLoader;
|
||
|
|
})(window);
|