Migrate auth to AuthGuard, retiring local Postgres-backed accounts
Same pattern as GameStream (commit 6a46007), adapted for CollabTable being genuinely multi-user (not single-admin): admin user management (list/create/update/delete, role reassignment, superadmin protection) is fully proxied to AuthGuard, which already enforces the same rules CollabTable checked locally. Cookie forwarding, no local session token, AUTHGUARD_URL optional (unset = auth fully disabled), transport failures always surface as errAuthGuardUnavailable rather than ever letting a request through - proven with live tests against a closed socket. CollabTable's device-sync API token feature (separate from browser sessions) is deliberately left local-only regardless of AUTHGUARD_URL, keyed by a new currentUserID helper (AuthGuard's id when enabled, the shared placeholder id 0 when disabled) - a real, functional token either way, not faked data. Real bug found and fixed: api_tokens.user_id had a hard FK into the local auth_users table, which would reject new tokens once accounts stop being written locally. Dropped the now-invalid FK. Known, accepted gap (same as GameStream): self-service profile editing for non-admin accounts is lost, since AuthGuard only exposes an admin endpoint, no self-edit. TOTP QR issuer branding now comes from AuthGuard rather than CollabTable. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a1c29728f0
commit
9a6ec940f7
48 files changed
+12401
-511
No files matched your search
@@ -0,0 +1,920 @@
|
||||
/**
|
||||
* @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);
|
||||
@@ -0,0 +1,204 @@
|
||||
// NCExpandableContainer
|
||||
// Shared helper for expandable/collapsible containers with optional persistence.
|
||||
//
|
||||
// Usage:
|
||||
// const controller = window.NCExpandableContainer.bind({
|
||||
// toggleEl: 'filtersToggle',
|
||||
// contentEl: 'filtersBody',
|
||||
// chevronEl: 'filtersChevron',
|
||||
// storageKey: 'app:filters-open',
|
||||
// storageFormat: 'flag', // 'json' | 'flag'
|
||||
// defaultExpanded: false,
|
||||
// initFromAria: true,
|
||||
// chevronMode: 'class', // 'class' | 'style'
|
||||
// chevronRotateClass: 'rotate-180',
|
||||
// syncHiddenAttribute: true,
|
||||
// onChange: expanded => { ... },
|
||||
// });
|
||||
|
||||
(function (global) {
|
||||
'use strict';
|
||||
|
||||
var controllerByToggle = new WeakMap();
|
||||
|
||||
function toElement(target) {
|
||||
if (!target) return null;
|
||||
if (target instanceof Element) return target;
|
||||
|
||||
var value = String(target || '').trim();
|
||||
if (!value) return null;
|
||||
|
||||
if (value.charAt(0) === '#') {
|
||||
try {
|
||||
return document.querySelector(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
var byId = document.getElementById(value);
|
||||
if (byId) return byId;
|
||||
|
||||
try {
|
||||
return document.querySelector(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readStorageBoolean(storageKey, storageFormat) {
|
||||
if (!storageKey) return null;
|
||||
try {
|
||||
var raw = localStorage.getItem(storageKey);
|
||||
if (raw == null) return null;
|
||||
if (storageFormat === 'flag') return raw === '1';
|
||||
return !!JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeStorageBoolean(storageKey, value, storageFormat) {
|
||||
if (!storageKey) return;
|
||||
try {
|
||||
if (storageFormat === 'flag') localStorage.setItem(storageKey, value ? '1' : '0');
|
||||
else localStorage.setItem(storageKey, JSON.stringify(!!value));
|
||||
} catch {
|
||||
// Ignore storage failures.
|
||||
}
|
||||
}
|
||||
|
||||
function applyChevronState(chevronEl, expanded, chevronMode, chevronRotateClass) {
|
||||
if (!chevronEl) return;
|
||||
if (chevronMode === 'style') {
|
||||
chevronEl.style.transform = expanded ? 'rotate(180deg)' : '';
|
||||
return;
|
||||
}
|
||||
chevronEl.classList.toggle(chevronRotateClass, !!expanded);
|
||||
}
|
||||
|
||||
function bind(options) {
|
||||
var config = options || {};
|
||||
var toggleEl = toElement(config.toggleEl || config.toggle || config.toggleId);
|
||||
var contentEl = toElement(config.contentEl || config.content || config.contentId);
|
||||
if (!toggleEl || !contentEl) return null;
|
||||
|
||||
if (config.allowRebind !== true && controllerByToggle.has(toggleEl)) {
|
||||
return controllerByToggle.get(toggleEl);
|
||||
}
|
||||
|
||||
var chevronEl = toElement(config.chevronEl || config.chevron || config.chevronId);
|
||||
var hiddenClass = String(config.hiddenClass || 'hidden');
|
||||
var eventName = String(config.eventName || 'click');
|
||||
var storageKey = config.storageKey ? String(config.storageKey) : '';
|
||||
var storageFormat = config.storageFormat === 'flag' ? 'flag' : 'json';
|
||||
var defaultExpanded = config.defaultExpanded === true;
|
||||
var initFromAria = config.initFromAria !== false;
|
||||
var updateAria = config.updateAria !== false;
|
||||
var syncHiddenAttribute = config.syncHiddenAttribute === true;
|
||||
var persistState = config.persistState !== false;
|
||||
var emitInitial = config.emitInitial !== false;
|
||||
var chevronMode = config.chevronMode === 'style' ? 'style' : 'class';
|
||||
var chevronRotateClass = String(config.chevronRotateClass || 'rotate-180');
|
||||
var onChange = typeof config.onChange === 'function' ? config.onChange : null;
|
||||
var onBeforeToggle =
|
||||
typeof config.onBeforeToggle === 'function' ? config.onBeforeToggle : null;
|
||||
|
||||
var expanded = defaultExpanded;
|
||||
|
||||
var stored = readStorageBoolean(storageKey, storageFormat);
|
||||
if (typeof stored === 'boolean') {
|
||||
expanded = stored;
|
||||
} else if (initFromAria && toggleEl.hasAttribute('aria-expanded')) {
|
||||
expanded = toggleEl.getAttribute('aria-expanded') === 'true';
|
||||
}
|
||||
|
||||
function applyExpanded(nextExpanded, opts) {
|
||||
var applyOptions = opts || {};
|
||||
var persist = applyOptions.persist !== false;
|
||||
var emit = applyOptions.emit !== false;
|
||||
|
||||
expanded = !!nextExpanded;
|
||||
|
||||
contentEl.classList.toggle(hiddenClass, !expanded);
|
||||
|
||||
if (syncHiddenAttribute) {
|
||||
contentEl.hidden = !expanded;
|
||||
}
|
||||
|
||||
if (updateAria) {
|
||||
toggleEl.setAttribute('aria-expanded', String(expanded));
|
||||
}
|
||||
|
||||
applyChevronState(chevronEl, expanded, chevronMode, chevronRotateClass);
|
||||
|
||||
if (persist && persistState && storageKey) {
|
||||
writeStorageBoolean(storageKey, expanded, storageFormat);
|
||||
}
|
||||
|
||||
if (emit && onChange) {
|
||||
onChange(expanded, {
|
||||
toggleEl: toggleEl,
|
||||
contentEl: contentEl,
|
||||
chevronEl: chevronEl,
|
||||
controller: controller,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function handleToggle(event) {
|
||||
if (onBeforeToggle) {
|
||||
try {
|
||||
if (onBeforeToggle(event, expanded) === false) return;
|
||||
} catch {
|
||||
// Ignore before-toggle hook errors.
|
||||
}
|
||||
}
|
||||
applyExpanded(!expanded);
|
||||
}
|
||||
|
||||
toggleEl.addEventListener(eventName, handleToggle);
|
||||
|
||||
var controller = {
|
||||
elements: {
|
||||
toggleEl: toggleEl,
|
||||
contentEl: contentEl,
|
||||
chevronEl: chevronEl,
|
||||
},
|
||||
isExpanded: function () {
|
||||
return expanded;
|
||||
},
|
||||
setExpanded: function (nextExpanded, opts) {
|
||||
applyExpanded(nextExpanded, opts);
|
||||
},
|
||||
toggle: function (opts) {
|
||||
applyExpanded(!expanded, opts);
|
||||
},
|
||||
destroy: function () {
|
||||
toggleEl.removeEventListener(eventName, handleToggle);
|
||||
controllerByToggle.delete(toggleEl);
|
||||
},
|
||||
};
|
||||
|
||||
controllerByToggle.set(toggleEl, controller);
|
||||
|
||||
applyExpanded(expanded, { persist: false, emit: emitInitial });
|
||||
|
||||
return controller;
|
||||
}
|
||||
|
||||
function bindMany(configs) {
|
||||
if (!Array.isArray(configs)) return [];
|
||||
return configs.map(function (config) {
|
||||
return bind(config);
|
||||
});
|
||||
}
|
||||
|
||||
global.NCExpandableContainer = {
|
||||
bind: bind,
|
||||
bindMany: bindMany,
|
||||
readStorageBoolean: readStorageBoolean,
|
||||
writeStorageBoolean: writeStorageBoolean,
|
||||
applyChevronState: applyChevronState,
|
||||
};
|
||||
})(window);
|
||||
@@ -0,0 +1,266 @@
|
||||
(() => {
|
||||
if (window.NCHeaderControls) return;
|
||||
|
||||
const state = {
|
||||
level: 'checking',
|
||||
health: null,
|
||||
readiness: null,
|
||||
service: '',
|
||||
checkedAt: null,
|
||||
loading: false,
|
||||
};
|
||||
const boundButtons = new WeakSet();
|
||||
let statusRequest = null;
|
||||
let statusTimer = null;
|
||||
let activeDialog = null;
|
||||
let activeOpener = null;
|
||||
|
||||
const levelLabels = {
|
||||
checking: 'Checking',
|
||||
healthy: 'Healthy',
|
||||
degraded: 'Degraded',
|
||||
offline: 'Offline',
|
||||
};
|
||||
const levelIcons = {
|
||||
checking: 'fa-circle-question',
|
||||
healthy: 'fa-circle-check',
|
||||
degraded: 'fa-triangle-exclamation',
|
||||
offline: 'fa-circle-xmark',
|
||||
};
|
||||
const levelColors = {
|
||||
checking: 'var(--color-bar-text-muted)',
|
||||
healthy: 'var(--color-success-strong, #16a34a)',
|
||||
degraded: 'var(--color-warning, #f59e0b)',
|
||||
offline: 'var(--color-danger, #ef4444)',
|
||||
};
|
||||
|
||||
function setDialogVisible(dialog, visible) {
|
||||
if (!dialog) return;
|
||||
dialog.hidden = !visible;
|
||||
dialog.style.display = visible ? 'grid' : 'none';
|
||||
dialog.setAttribute('aria-hidden', visible ? 'false' : 'true');
|
||||
}
|
||||
|
||||
function createOverlay(id, title, description) {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.id = id;
|
||||
overlay.hidden = true;
|
||||
overlay.setAttribute('aria-hidden', 'true');
|
||||
overlay.setAttribute('role', 'dialog');
|
||||
overlay.setAttribute('aria-modal', 'true');
|
||||
overlay.setAttribute('aria-labelledby', `${id}Title`);
|
||||
overlay.className = 'fixed inset-0 z-[210] hidden place-items-center bg-black/70 p-4';
|
||||
overlay.style.background = 'var(--color-overlay, rgba(0, 0, 0, 0.7))';
|
||||
overlay.innerHTML = `
|
||||
<div class="relative w-[min(560px,92vw)] overflow-hidden rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-surface)] text-[var(--color-text)] shadow-2xl" role="document">
|
||||
<button type="button" data-dialog-close aria-label="Close" class="absolute right-2.5 top-2.5 inline-flex h-9 w-9 items-center justify-center rounded-full border border-[var(--color-border-strong)] bg-[var(--color-bg-soft)] text-[var(--color-text)] shadow-sm hover:bg-[var(--color-surface)]"><i class="fas fa-xmark" aria-hidden="true"></i></button>
|
||||
<div class="flex flex-col gap-1 px-4 pb-2 pt-4">
|
||||
<h2 id="${id}Title" class="m-0 text-lg font-[650]">${title}</h2>
|
||||
<p class="m-0 text-sm text-[var(--color-text-dim)]">${description}</p>
|
||||
</div>
|
||||
<div data-dialog-body class="px-4 pb-4 pt-3"></div>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(overlay);
|
||||
overlay.addEventListener('click', event => {
|
||||
if (event.target === overlay) closeDialog(overlay);
|
||||
});
|
||||
overlay.querySelector('[data-dialog-close]')?.addEventListener('click', () => closeDialog(overlay));
|
||||
return overlay;
|
||||
}
|
||||
|
||||
function ensureSettingsDialog() {
|
||||
let overlay = document.getElementById('ncSettingsOverlay');
|
||||
if (overlay) return overlay;
|
||||
|
||||
overlay = createOverlay('ncSettingsOverlay', 'Settings', 'Personalize the shared MediaCollection interface.');
|
||||
const body = overlay.querySelector('[data-dialog-body]');
|
||||
body.innerHTML = `
|
||||
<div class="flex items-center justify-between gap-3 rounded-md border border-[var(--color-border-strong)] bg-[var(--color-bg-soft)] px-3 py-3">
|
||||
<div>
|
||||
<div class="text-sm font-medium">Theme</div>
|
||||
<div class="mt-1 text-xs text-[var(--color-text-dim)]">Switch between the light and dark appearance.</div>
|
||||
</div>
|
||||
<button type="button" data-theme-toggle class="inline-flex min-w-[92px] items-center justify-center rounded-full border border-[var(--color-border-strong)] bg-[var(--color-surface)] px-3 py-2 text-sm font-semibold text-[var(--color-text)] shadow-sm hover:bg-[var(--color-surface-raised)]" title="Toggle dark / light theme" aria-label="Toggle theme">Toggle</button>
|
||||
</div>
|
||||
`;
|
||||
return overlay;
|
||||
}
|
||||
|
||||
function ensureStatusDialog() {
|
||||
let overlay = document.getElementById('ncStatusOverlay');
|
||||
if (overlay) return overlay;
|
||||
|
||||
overlay = createOverlay('ncStatusOverlay', 'Status', 'Live liveness and database readiness checks.');
|
||||
const body = overlay.querySelector('[data-dialog-body]');
|
||||
body.innerHTML = `
|
||||
<div class="mb-4 flex items-center gap-3 rounded-md border border-[var(--color-border-strong)] bg-[var(--color-bg-soft)] px-3 py-3" aria-live="polite">
|
||||
<i data-status-overall-icon class="fas fa-circle-question text-lg" aria-hidden="true"></i>
|
||||
<span data-status-overall class="font-semibold">Checking</span>
|
||||
<span data-status-checked class="ml-auto text-xs text-[var(--color-text-dim)]"></span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 text-sm">
|
||||
<div class="flex items-center justify-between gap-4 rounded-md border border-[var(--color-border-strong)] px-3 py-2"><span>Liveness</span><span data-status-health>Not checked</span></div>
|
||||
<div class="flex items-center justify-between gap-4 rounded-md border border-[var(--color-border-strong)] px-3 py-2"><span>Readiness / database</span><span data-status-readiness>Not checked</span></div>
|
||||
</div>
|
||||
<p data-status-service class="mt-3 mb-0 text-xs text-[var(--color-text-dim)]"></p>
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<button type="button" data-status-refresh class="inline-flex items-center gap-2 rounded-full border border-[var(--color-border-strong)] bg-[var(--color-surface)] px-3 py-2 text-sm font-semibold text-[var(--color-text)] shadow-sm hover:bg-[var(--color-surface-raised)]"><i class="fas fa-rotate" aria-hidden="true"></i>Refresh</button>
|
||||
<button type="button" data-dialog-close class="inline-flex items-center justify-center rounded-full bg-[var(--color-action)] px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-[var(--color-action-hover)]">Dismiss</button>
|
||||
</div>
|
||||
`;
|
||||
overlay.querySelector('[data-status-refresh]')?.addEventListener('click', () => void refreshStatus());
|
||||
overlay.querySelectorAll('[data-dialog-close]').forEach(button => {
|
||||
button.addEventListener('click', () => closeDialog(overlay));
|
||||
});
|
||||
return overlay;
|
||||
}
|
||||
|
||||
function openDialog(dialog, opener) {
|
||||
activeDialog = dialog;
|
||||
activeOpener = opener || null;
|
||||
setDialogVisible(dialog, true);
|
||||
window.setTimeout(() => dialog.querySelector('[data-dialog-close]')?.focus(), 0);
|
||||
}
|
||||
|
||||
function closeDialog(dialog) {
|
||||
if (!dialog) return;
|
||||
setDialogVisible(dialog, false);
|
||||
if (activeDialog === dialog) {
|
||||
const opener = activeOpener;
|
||||
activeDialog = null;
|
||||
activeOpener = null;
|
||||
opener?.focus?.();
|
||||
}
|
||||
}
|
||||
|
||||
async function probe(path) {
|
||||
try {
|
||||
const response = await fetch(path, {
|
||||
credentials: 'same-origin',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
const payload = await response.json().catch(() => null);
|
||||
return {
|
||||
ok: response.ok && payload?.ok !== false,
|
||||
status: response.status,
|
||||
service: payload?.service || '',
|
||||
error: response.ok ? '' : payload?.error || response.statusText || `HTTP ${response.status}`,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
status: null,
|
||||
service: '',
|
||||
error: error instanceof Error ? error.message : 'Unavailable',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function resultLabel(result) {
|
||||
if (!result) return 'Not checked';
|
||||
if (result.ok) return 'OK';
|
||||
return result.error || (result.status ? `HTTP ${result.status}` : 'Unavailable');
|
||||
}
|
||||
|
||||
function renderStatus() {
|
||||
const iconClass = levelIcons[state.level];
|
||||
const color = levelColors[state.level];
|
||||
document.querySelectorAll('[data-status-button]').forEach(button => {
|
||||
const icon = button.querySelector('[data-status-icon]');
|
||||
if (icon) {
|
||||
icon.className = `fas ${iconClass}`;
|
||||
icon.style.color = color;
|
||||
}
|
||||
button.title = `Service status: ${levelLabels[state.level]}`;
|
||||
button.setAttribute('aria-label', `Service status: ${levelLabels[state.level]}`);
|
||||
});
|
||||
|
||||
const dialog = document.getElementById('ncStatusOverlay');
|
||||
if (!dialog) return;
|
||||
const overallIcon = dialog.querySelector('[data-status-overall-icon]');
|
||||
if (overallIcon) {
|
||||
overallIcon.className = `fas ${iconClass} text-lg`;
|
||||
overallIcon.style.color = color;
|
||||
}
|
||||
const overall = dialog.querySelector('[data-status-overall]');
|
||||
if (overall) {
|
||||
overall.textContent = levelLabels[state.level];
|
||||
overall.style.color = color;
|
||||
}
|
||||
const checked = dialog.querySelector('[data-status-checked]');
|
||||
if (checked) checked.textContent = state.checkedAt ? new Date(state.checkedAt).toLocaleTimeString() : '';
|
||||
const health = dialog.querySelector('[data-status-health]');
|
||||
if (health) {
|
||||
health.textContent = resultLabel(state.health);
|
||||
health.style.color = state.health?.ok ? 'var(--color-success-strong, #16a34a)' : 'var(--color-danger, #ef4444)';
|
||||
}
|
||||
const readiness = dialog.querySelector('[data-status-readiness]');
|
||||
if (readiness) {
|
||||
readiness.textContent = resultLabel(state.readiness);
|
||||
readiness.style.color = state.readiness?.ok ? 'var(--color-success-strong, #16a34a)' : 'var(--color-danger, #ef4444)';
|
||||
}
|
||||
const service = dialog.querySelector('[data-status-service]');
|
||||
if (service) service.textContent = state.service ? `Service: ${state.service}` : '';
|
||||
const refreshButton = dialog.querySelector('[data-status-refresh]');
|
||||
if (refreshButton) refreshButton.disabled = state.loading;
|
||||
}
|
||||
|
||||
function refreshStatus() {
|
||||
if (statusRequest) return statusRequest;
|
||||
state.loading = true;
|
||||
renderStatus();
|
||||
statusRequest = Promise.all([probe('/healthz'), probe('/ready')])
|
||||
.then(([health, readiness]) => {
|
||||
state.health = health;
|
||||
state.readiness = readiness;
|
||||
state.service = health.service || readiness.service || '';
|
||||
state.level = health.ok && readiness.ok ? 'healthy' : health.ok ? 'degraded' : 'offline';
|
||||
state.checkedAt = new Date().toISOString();
|
||||
})
|
||||
.finally(() => {
|
||||
state.loading = false;
|
||||
statusRequest = null;
|
||||
renderStatus();
|
||||
});
|
||||
return statusRequest;
|
||||
}
|
||||
|
||||
function bindHeaderButtons() {
|
||||
document.querySelectorAll('[data-settings-button], [data-settings-menu-button]').forEach(button => {
|
||||
if (boundButtons.has(button)) return;
|
||||
boundButtons.add(button);
|
||||
button.addEventListener('click', () => openDialog(ensureSettingsDialog(), button));
|
||||
});
|
||||
document.querySelectorAll('[data-status-button]').forEach(button => {
|
||||
if (boundButtons.has(button)) return;
|
||||
boundButtons.add(button);
|
||||
button.addEventListener('click', () => {
|
||||
const dialog = ensureStatusDialog();
|
||||
openDialog(dialog, button);
|
||||
void refreshStatus();
|
||||
});
|
||||
});
|
||||
renderStatus();
|
||||
}
|
||||
|
||||
function init() {
|
||||
if (!document.body) return;
|
||||
ensureSettingsDialog();
|
||||
ensureStatusDialog();
|
||||
bindHeaderButtons();
|
||||
window.NCThemeToggle?.init?.();
|
||||
if (!statusTimer) {
|
||||
void refreshStatus();
|
||||
statusTimer = window.setInterval(() => void refreshStatus(), 15_000);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.key === 'Escape' && activeDialog) closeDialog(activeDialog);
|
||||
});
|
||||
document.addEventListener('DOMContentLoaded', init, { once: true });
|
||||
document.addEventListener('nc:componentsLoaded', init);
|
||||
|
||||
window.NCHeaderControls = { init, refreshStatus };
|
||||
})();
|
||||
@@ -0,0 +1,442 @@
|
||||
/**
|
||||
* Shared Results container helpers.
|
||||
*
|
||||
* Exposes:
|
||||
* - window.NCResultsContainer.apply(config)
|
||||
* - window.NCResultsContainer.ensurePaginationBars(paginationBars)
|
||||
*/
|
||||
(() => {
|
||||
const VIEW_MODES = [
|
||||
{
|
||||
value: 'list',
|
||||
label: 'List view',
|
||||
icon: '<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" class="h-4 w-4"><path d="M4 6h16M4 12h16M4 18h16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',
|
||||
},
|
||||
{
|
||||
value: 'grid',
|
||||
label: 'Grid view',
|
||||
icon: '<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" class="h-4 w-4"><rect x="4" y="4" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2"/><rect x="14" y="4" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2"/><rect x="4" y="14" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2"/><rect x="14" y="14" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2"/></svg>',
|
||||
},
|
||||
];
|
||||
|
||||
const VIEW_MODE_SYNC_KEY = '__ncViewModeSelectorSync';
|
||||
const VIEW_MODE_CHANGE_KEY = '__ncViewModeSelectorChange';
|
||||
const DEFAULT_RESULTS_CONTAINER_CLASSES = [
|
||||
'rounded-lg',
|
||||
'border',
|
||||
'border-[var(--color-border)]',
|
||||
'bg-[var(--color-surface)]',
|
||||
];
|
||||
|
||||
function toElement(target) {
|
||||
if (!target) return null;
|
||||
if (target instanceof Element) return target;
|
||||
if (typeof target === 'string') {
|
||||
return document.getElementById(target) || document.querySelector(target);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toElementList(targets) {
|
||||
if (!targets) return [];
|
||||
const list = Array.isArray(targets) ? targets : [targets];
|
||||
return list.map(toElement).filter(el => el instanceof Element);
|
||||
}
|
||||
|
||||
function addClasses(el, classNames) {
|
||||
if (!el || !classNames) return;
|
||||
const list = Array.isArray(classNames) ? classNames : String(classNames).split(/\s+/);
|
||||
for (const name of list) {
|
||||
const token = String(name || '').trim();
|
||||
if (token) el.classList.add(token);
|
||||
}
|
||||
}
|
||||
|
||||
function ensurePaginationBars(bars) {
|
||||
for (const bar of toElementList(bars)) {
|
||||
if (!bar.style.minHeight) bar.style.minHeight = '48px';
|
||||
bar.classList.add('w-full');
|
||||
bar.dataset.ncPaginationSlot = '1';
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeViewModeConfig(config) {
|
||||
if (!config) return null;
|
||||
if (config instanceof Element || typeof config === 'string') {
|
||||
return { select: config };
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function normalizeModeValue(mode, fallback = 'grid') {
|
||||
const value = String(mode || '').toLowerCase();
|
||||
if (value === 'compact') return 'list';
|
||||
if (value === 'list' || value === 'grid') return value;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function readStoredMode(storageKey) {
|
||||
if (!storageKey) return null;
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey);
|
||||
return raw ? normalizeModeValue(raw, null) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoredMode(storageKey, mode) {
|
||||
if (!storageKey) return;
|
||||
try {
|
||||
window.localStorage.setItem(storageKey, mode);
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
function applyViewModeSelector(resultsContainer, config) {
|
||||
const viewMode = normalizeViewModeConfig(config);
|
||||
if (!resultsContainer || !viewMode) return;
|
||||
|
||||
const resultsContent = resultsContainer.querySelector('[data-nc-results-content="1"]');
|
||||
|
||||
function applyModeToResultsContent(mode) {
|
||||
if (!resultsContent) return;
|
||||
resultsContent.dataset.ncDisplayMode = normalizeModeValue(mode, 'grid');
|
||||
}
|
||||
|
||||
const select = toElement(
|
||||
viewMode.select ||
|
||||
viewMode.selectInput ||
|
||||
viewMode.selectElement ||
|
||||
viewMode.target ||
|
||||
viewMode.id
|
||||
);
|
||||
const selectEl = select && select.tagName === 'SELECT' ? select : null;
|
||||
|
||||
const selectId = (selectEl && selectEl.id) || String(viewMode.key || 'view-mode');
|
||||
const selectorId = `nc-view-mode-selector-${selectId}`;
|
||||
|
||||
let modes = VIEW_MODES;
|
||||
if (Array.isArray(viewMode.modes) && viewMode.modes.length > 0) {
|
||||
const allowed = new Set(
|
||||
viewMode.modes.map(mode => normalizeModeValue(mode, null)).filter(Boolean)
|
||||
);
|
||||
modes = VIEW_MODES.filter(mode => allowed.has(mode.value));
|
||||
}
|
||||
if (selectEl) {
|
||||
const modeValues = new Set(
|
||||
Array.from(selectEl.options || [])
|
||||
.map(opt => normalizeModeValue(opt.value, null))
|
||||
.filter(Boolean)
|
||||
);
|
||||
modes = modes.filter(mode => modeValues.has(mode.value));
|
||||
}
|
||||
if (!modes.length) return;
|
||||
|
||||
const defaultMode = normalizeModeValue(viewMode.defaultMode, 'grid');
|
||||
const storageKey =
|
||||
typeof viewMode.storageKey === 'string' && viewMode.storageKey.trim().length > 0
|
||||
? viewMode.storageKey.trim()
|
||||
: null;
|
||||
|
||||
let inlineMode = defaultMode;
|
||||
if (!selectEl) {
|
||||
const fromGetter =
|
||||
typeof viewMode.getMode === 'function'
|
||||
? normalizeModeValue(viewMode.getMode(), defaultMode)
|
||||
: null;
|
||||
const fromStorage = readStoredMode(storageKey);
|
||||
inlineMode = fromGetter || fromStorage || defaultMode;
|
||||
}
|
||||
|
||||
function getActiveMode() {
|
||||
if (selectEl) return normalizeModeValue(selectEl.value, defaultMode);
|
||||
return normalizeModeValue(inlineMode, defaultMode);
|
||||
}
|
||||
|
||||
function setActiveMode(mode, source = 'ui') {
|
||||
const nextMode = normalizeModeValue(mode, defaultMode);
|
||||
const available = modes.some(m => m.value === nextMode);
|
||||
if (!available) return;
|
||||
|
||||
applyModeToResultsContent(nextMode);
|
||||
|
||||
if (selectEl) {
|
||||
if (normalizeModeValue(selectEl.value, defaultMode) !== nextMode) {
|
||||
selectEl.value = nextMode;
|
||||
if (source !== 'select') {
|
||||
selectEl.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
inlineMode = nextMode;
|
||||
if (typeof viewMode.setMode === 'function') {
|
||||
try {
|
||||
viewMode.setMode(nextMode);
|
||||
} catch {
|
||||
// ignore consumer callback errors
|
||||
}
|
||||
}
|
||||
writeStoredMode(storageKey, nextMode);
|
||||
}
|
||||
|
||||
if (!selectEl && typeof viewMode.onModeChange === 'function') {
|
||||
try {
|
||||
viewMode.onModeChange(nextMode);
|
||||
} catch {
|
||||
// ignore consumer callback errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ownedHostSelector = '[data-nc-display-mode-host="1"]';
|
||||
|
||||
function getOwnedHosts() {
|
||||
return Array.from(resultsContainer.querySelectorAll(ownedHostSelector)).filter(
|
||||
host => host.dataset.ncViewModeOwner === selectorId
|
||||
);
|
||||
}
|
||||
|
||||
function hasResultCards() {
|
||||
if (!(resultsContent instanceof Element)) return false;
|
||||
return Boolean(resultsContent.querySelector('[data-nc-result-card="1"]'));
|
||||
}
|
||||
|
||||
function syncSelectorVisibility() {
|
||||
const showSelector = hasResultCards();
|
||||
for (const host of getOwnedHosts()) {
|
||||
host.classList.toggle('hidden', !showSelector);
|
||||
}
|
||||
|
||||
if (selectEl && viewMode.hideSelect === false) {
|
||||
selectEl.classList.toggle('hidden', !showSelector);
|
||||
selectEl.setAttribute('aria-hidden', showSelector ? 'false' : 'true');
|
||||
}
|
||||
}
|
||||
|
||||
function resolveRenderHosts() {
|
||||
const centerSlots = Array.from(
|
||||
resultsContainer.querySelectorAll('[data-nc-pagination-center-slot="1"]')
|
||||
);
|
||||
const paginationBars = Array.from(
|
||||
resultsContainer.querySelectorAll('[data-nc-pagination-slot="1"]')
|
||||
);
|
||||
const hosts = [];
|
||||
|
||||
if (centerSlots.length) {
|
||||
for (const slot of centerSlots) {
|
||||
let host = Array.from(slot.querySelectorAll(ownedHostSelector)).find(
|
||||
candidate => candidate.dataset.ncViewModeOwner === selectorId
|
||||
);
|
||||
if (!host) {
|
||||
host = document.createElement('div');
|
||||
host.className = 'flex items-center justify-center';
|
||||
host.dataset.ncDisplayModeHost = '1';
|
||||
host.dataset.ncViewModeOwner = selectorId;
|
||||
slot.appendChild(host);
|
||||
}
|
||||
hosts.push(host);
|
||||
}
|
||||
} else {
|
||||
let host = getOwnedHosts().find(candidate => candidate.dataset.ncViewModeFallback === '1');
|
||||
if (!host) {
|
||||
host = document.createElement('div');
|
||||
host.className = 'mb-3 flex items-center justify-center';
|
||||
host.dataset.ncDisplayModeHost = '1';
|
||||
host.dataset.ncViewModeOwner = selectorId;
|
||||
host.dataset.ncViewModeFallback = '1';
|
||||
}
|
||||
|
||||
const anchor = paginationBars.find(bar => bar && bar.parentElement === resultsContainer);
|
||||
if (anchor) {
|
||||
resultsContainer.insertBefore(host, anchor);
|
||||
} else {
|
||||
resultsContainer.insertBefore(host, resultsContainer.firstChild);
|
||||
}
|
||||
hosts.push(host);
|
||||
}
|
||||
|
||||
const keep = new Set(hosts);
|
||||
for (const existingHost of getOwnedHosts()) {
|
||||
if (!keep.has(existingHost)) existingHost.remove();
|
||||
}
|
||||
|
||||
return hosts;
|
||||
}
|
||||
|
||||
let syncActiveButtons = () => {};
|
||||
|
||||
function renderSelectorHosts() {
|
||||
const hosts = resolveRenderHosts();
|
||||
const buttonGroups = [];
|
||||
|
||||
for (const host of hosts) {
|
||||
host.innerHTML = '';
|
||||
|
||||
const shell = document.createElement('div');
|
||||
shell.className = 'inline-flex items-center justify-center';
|
||||
|
||||
const group = document.createElement('div');
|
||||
group.className = 'inline-flex items-center gap-1.5';
|
||||
group.setAttribute('role', 'group');
|
||||
group.setAttribute('aria-label', viewMode.ariaLabel || 'Display mode');
|
||||
|
||||
const buttonByMode = new Map();
|
||||
for (const mode of modes) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className =
|
||||
'inline-flex h-8 w-8 items-center justify-center rounded border border-transparent text-[var(--color-text-dim)] transition-colors hover:text-[var(--color-text)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-300/20';
|
||||
button.setAttribute('aria-label', mode.label);
|
||||
button.setAttribute('title', mode.label);
|
||||
button.dataset.ncDisplayMode = mode.value;
|
||||
button.innerHTML = mode.icon;
|
||||
button.addEventListener('click', () => {
|
||||
if (getActiveMode() === mode.value) return;
|
||||
setActiveMode(mode.value, 'ui');
|
||||
syncActiveButtons();
|
||||
});
|
||||
buttonByMode.set(mode.value, button);
|
||||
group.appendChild(button);
|
||||
}
|
||||
|
||||
buttonGroups.push(buttonByMode);
|
||||
shell.appendChild(group);
|
||||
host.appendChild(shell);
|
||||
}
|
||||
|
||||
syncActiveButtons = () => {
|
||||
const activeMode = getActiveMode();
|
||||
for (const group of buttonGroups) {
|
||||
for (const mode of modes) {
|
||||
const button = group.get(mode.value);
|
||||
if (!button) continue;
|
||||
const active = mode.value === activeMode;
|
||||
button.setAttribute('aria-pressed', active ? 'true' : 'false');
|
||||
button.classList.toggle('text-[var(--color-text)]', active);
|
||||
button.classList.toggle('text-[var(--color-text-dim)]', !active);
|
||||
button.classList.toggle('bg-[var(--color-surface)]', active);
|
||||
button.classList.toggle('border-[var(--color-border-strong)]', active);
|
||||
button.classList.toggle('shadow-[var(--shadow-sm)]', active);
|
||||
button.classList.toggle('opacity-100', active);
|
||||
button.classList.toggle('border-transparent', !active);
|
||||
button.classList.toggle('opacity-80', !active);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
syncActiveButtons();
|
||||
syncSelectorVisibility();
|
||||
}
|
||||
|
||||
if (selectEl && viewMode.hideSelect !== false) {
|
||||
selectEl.style.display = 'none';
|
||||
selectEl.setAttribute('aria-hidden', 'true');
|
||||
selectEl.tabIndex = -1;
|
||||
}
|
||||
|
||||
if (selectEl && typeof selectEl[VIEW_MODE_SYNC_KEY] === 'function') {
|
||||
selectEl.removeEventListener('change', selectEl[VIEW_MODE_SYNC_KEY]);
|
||||
}
|
||||
if (selectEl && typeof selectEl[VIEW_MODE_CHANGE_KEY] === 'function') {
|
||||
selectEl.removeEventListener('change', selectEl[VIEW_MODE_CHANGE_KEY]);
|
||||
}
|
||||
if (selectEl) {
|
||||
selectEl[VIEW_MODE_SYNC_KEY] = () => syncActiveButtons();
|
||||
selectEl[VIEW_MODE_CHANGE_KEY] = () => {
|
||||
const currentMode = getActiveMode();
|
||||
applyModeToResultsContent(currentMode);
|
||||
if (storageKey) writeStoredMode(storageKey, currentMode);
|
||||
if (typeof viewMode.onModeChange === 'function') {
|
||||
try {
|
||||
viewMode.onModeChange(currentMode);
|
||||
} catch {
|
||||
// ignore consumer callback errors
|
||||
}
|
||||
}
|
||||
};
|
||||
selectEl.addEventListener('change', selectEl[VIEW_MODE_SYNC_KEY]);
|
||||
selectEl.addEventListener('change', selectEl[VIEW_MODE_CHANGE_KEY]);
|
||||
|
||||
const stored = readStoredMode(storageKey);
|
||||
if (stored && modes.some(mode => mode.value === stored) && selectEl.value !== stored) {
|
||||
selectEl.value = stored;
|
||||
selectEl.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
} else {
|
||||
setActiveMode(inlineMode, 'init');
|
||||
}
|
||||
|
||||
const paginationListenerKey = `__ncViewModePaginationListener_${selectorId}`;
|
||||
if (typeof resultsContainer[paginationListenerKey] === 'function') {
|
||||
resultsContainer.removeEventListener(
|
||||
'nc:pagination-rendered',
|
||||
resultsContainer[paginationListenerKey]
|
||||
);
|
||||
}
|
||||
const onPaginationRendered = event => {
|
||||
const target = event?.target;
|
||||
if (!(target instanceof Element)) return;
|
||||
if (!resultsContainer.contains(target)) return;
|
||||
if (target.dataset.ncPaginationSlot !== '1') return;
|
||||
renderSelectorHosts();
|
||||
};
|
||||
resultsContainer[paginationListenerKey] = onPaginationRendered;
|
||||
resultsContainer.addEventListener('nc:pagination-rendered', onPaginationRendered);
|
||||
|
||||
const resultsObserverKey = `__ncViewModeResultsObserver_${selectorId}`;
|
||||
const existingObserver = resultsContainer[resultsObserverKey];
|
||||
if (existingObserver && typeof existingObserver.disconnect === 'function') {
|
||||
existingObserver.disconnect();
|
||||
}
|
||||
if (resultsContent instanceof Element && typeof MutationObserver !== 'undefined') {
|
||||
const observer = new MutationObserver(() => {
|
||||
syncSelectorVisibility();
|
||||
});
|
||||
observer.observe(resultsContent, { childList: true, subtree: true });
|
||||
resultsContainer[resultsObserverKey] = observer;
|
||||
}
|
||||
|
||||
renderSelectorHosts();
|
||||
applyModeToResultsContent(getActiveMode());
|
||||
syncSelectorVisibility();
|
||||
}
|
||||
|
||||
function applyResultsContainer(config = {}) {
|
||||
const container = toElement(config.container || config.resultsContainer || config.id);
|
||||
if (!container) return null;
|
||||
|
||||
if (config.useDefaultShellClasses === true) {
|
||||
addClasses(container, DEFAULT_RESULTS_CONTAINER_CLASSES);
|
||||
}
|
||||
addClasses(container, config.classes);
|
||||
|
||||
const role = Object.prototype.hasOwnProperty.call(config, 'role') ? config.role : 'region';
|
||||
if (role) container.setAttribute('role', role);
|
||||
if (config.label) container.setAttribute('aria-label', config.label);
|
||||
|
||||
container.dataset.ncResultsContainer = '1';
|
||||
|
||||
const content = toElement(config.resultsContent || config.grid || config.list);
|
||||
if (content) {
|
||||
content.dataset.ncResultsContent = '1';
|
||||
if (!content.hasAttribute('aria-live')) content.setAttribute('aria-live', 'polite');
|
||||
}
|
||||
|
||||
const emptyState = toElement(config.emptyState);
|
||||
if (emptyState) emptyState.dataset.ncResultsEmpty = '1';
|
||||
|
||||
ensurePaginationBars(config.topPagination);
|
||||
ensurePaginationBars(config.bottomPagination);
|
||||
ensurePaginationBars(config.paginationBars);
|
||||
applyViewModeSelector(container, config.viewModeSelector || config.viewMode);
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
window.NCResultsContainer = {
|
||||
apply: applyResultsContainer,
|
||||
ensurePaginationBars,
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,433 @@
|
||||
/**
|
||||
* Shared Search/Filter container helpers.
|
||||
*
|
||||
* Exposes:
|
||||
* - window.NCSearchFilterContainer.apply(config)
|
||||
* - window.NCSearchFilterContainer.applyStandardControls(config)
|
||||
*/
|
||||
(() => {
|
||||
const DEFAULT_FILTER_CONTAINER_CLASSES = [
|
||||
'rounded-lg',
|
||||
'border',
|
||||
'border-[var(--color-border)]',
|
||||
'bg-[var(--color-surface)]',
|
||||
];
|
||||
|
||||
const DEFAULT_PER_PAGE_VALUES = [12, 24, 48, 96];
|
||||
const DEFAULT_PER_PAGE_VALUE = 24;
|
||||
|
||||
const DEFAULT_SORT_OPTIONS = [
|
||||
{ value: 'time_desc', label: 'Time (Newest first)' },
|
||||
{ value: 'time_asc', label: 'Time (Oldest first)' },
|
||||
{ value: 'title_asc', label: 'Title (A-Z)' },
|
||||
{ value: 'title_desc', label: 'Title (Z-A)' },
|
||||
{ value: 'length_asc', label: 'Length (Short to long)' },
|
||||
{ value: 'length_desc', label: 'Length (Long to short)' },
|
||||
{ value: 'resolution_asc', label: 'Resolution (Low to high)' },
|
||||
{ value: 'resolution_desc', label: 'Resolution (High to low)' },
|
||||
{ value: 'speed_asc', label: 'Speed (Slow to fast)' },
|
||||
{ value: 'speed_desc', label: 'Speed (Fast to slow)' },
|
||||
];
|
||||
|
||||
function toElement(target) {
|
||||
if (!target) return null;
|
||||
if (target instanceof Element) return target;
|
||||
if (typeof target === 'string') {
|
||||
return document.getElementById(target) || document.querySelector(target);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addClasses(el, classNames) {
|
||||
if (!el || !classNames) return;
|
||||
const list = Array.isArray(classNames) ? classNames : String(classNames).split(/\s+/);
|
||||
for (const name of list) {
|
||||
const token = String(name || '').trim();
|
||||
if (token) el.classList.add(token);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeSearchInputAria(inputEl, fallbackLabel) {
|
||||
if (!inputEl || inputEl.hasAttribute('aria-label')) return;
|
||||
const placeholder = String(inputEl.getAttribute('placeholder') || '').trim();
|
||||
inputEl.setAttribute('aria-label', placeholder || fallbackLabel || 'Search');
|
||||
}
|
||||
|
||||
function cloneOptions(options) {
|
||||
return (Array.isArray(options) ? options : []).map(option => ({
|
||||
value: String(option.value),
|
||||
label: String(option.label),
|
||||
}));
|
||||
}
|
||||
|
||||
function normalizePerPageOptions() {
|
||||
return DEFAULT_PER_PAGE_VALUES.map(value => ({
|
||||
value: String(value),
|
||||
label: `${value} per page`,
|
||||
}));
|
||||
}
|
||||
|
||||
function normalizeSortOptions(options) {
|
||||
const source = Array.isArray(options) && options.length ? options : DEFAULT_SORT_OPTIONS;
|
||||
return source
|
||||
.map(entry => {
|
||||
if (!entry) return null;
|
||||
if (typeof entry === 'object') {
|
||||
const value = String(entry.value ?? '').trim();
|
||||
if (!value) return null;
|
||||
const label = String(entry.label ?? value).trim() || value;
|
||||
return { value, label };
|
||||
}
|
||||
const value = String(entry).trim();
|
||||
if (!value) return null;
|
||||
return { value, label: value };
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function setSelectOptions(selectEl, options, selectedValue, fallbackValue = options[0]?.value) {
|
||||
if (!selectEl || !options.length) return null;
|
||||
|
||||
const normalizedSelected = String(selectedValue ?? selectEl.value ?? '').trim();
|
||||
const values = new Set(options.map(option => option.value));
|
||||
const resolvedValue =
|
||||
normalizedSelected && values.has(normalizedSelected)
|
||||
? normalizedSelected
|
||||
: values.has(String(fallbackValue))
|
||||
? String(fallbackValue)
|
||||
: String(options[0].value);
|
||||
|
||||
selectEl.innerHTML = '';
|
||||
options.forEach(option => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = option.value;
|
||||
opt.textContent = option.label;
|
||||
selectEl.appendChild(opt);
|
||||
});
|
||||
selectEl.value = resolvedValue;
|
||||
return resolvedValue;
|
||||
}
|
||||
|
||||
function applyStandardControls(config = {}) {
|
||||
const searchInput = toElement(config.searchInput);
|
||||
const perPageSelect = toElement(config.perPageSelect || config.perPageInput);
|
||||
const sortSelect = toElement(config.sortSelect || config.sortInput);
|
||||
|
||||
if (searchInput) {
|
||||
const placeholder = String(config.searchPlaceholder || '').trim();
|
||||
const shouldSetPlaceholder =
|
||||
!!placeholder &&
|
||||
(config.forceSearchPlaceholder === true ||
|
||||
!String(searchInput.getAttribute('placeholder') || '').trim());
|
||||
if (shouldSetPlaceholder) searchInput.setAttribute('placeholder', placeholder);
|
||||
normalizeSearchInputAria(searchInput, config.searchLabel || config.label);
|
||||
}
|
||||
|
||||
const perPageOptions = normalizePerPageOptions();
|
||||
const sortOptions = normalizeSortOptions(config.sortOptions);
|
||||
|
||||
const perPageValue = perPageSelect
|
||||
? setSelectOptions(perPageSelect, perPageOptions, config.perPageValue, DEFAULT_PER_PAGE_VALUE)
|
||||
: null;
|
||||
const sortValue = sortSelect
|
||||
? setSelectOptions(sortSelect, sortOptions, config.sortValue)
|
||||
: null;
|
||||
|
||||
return {
|
||||
searchInput,
|
||||
perPageSelect,
|
||||
sortSelect,
|
||||
perPageValue,
|
||||
sortValue,
|
||||
};
|
||||
}
|
||||
|
||||
function toElementInContainer(target, container) {
|
||||
if (!target || !container) return null;
|
||||
if (target instanceof Element) {
|
||||
return container.contains(target) ? target : null;
|
||||
}
|
||||
if (typeof target === 'string') {
|
||||
const value = target.trim();
|
||||
if (!value) return null;
|
||||
|
||||
const safeValue = value.split('"').join('\\"');
|
||||
const byIdInContainer = container.querySelector(`[id="${safeValue}"]`);
|
||||
if (byIdInContainer) return byIdInContainer;
|
||||
|
||||
try {
|
||||
const bySelectorInContainer = container.querySelector(value);
|
||||
if (bySelectorInContainer) return bySelectorInContainer;
|
||||
} catch {
|
||||
// Ignore invalid selectors and continue to ID lookup.
|
||||
}
|
||||
|
||||
const byId = document.getElementById(value);
|
||||
if (byId && container.contains(byId)) return byId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeFilterTargets(filterControls) {
|
||||
if (!filterControls) return [];
|
||||
if (Array.isArray(filterControls)) return filterControls;
|
||||
return [filterControls];
|
||||
}
|
||||
|
||||
function resolveControlNode(controlEl, container) {
|
||||
if (!controlEl || !container.contains(controlEl)) return null;
|
||||
|
||||
let node = controlEl;
|
||||
const parent = controlEl.parentElement;
|
||||
|
||||
if (parent && parent !== container) {
|
||||
const hasAssociatedLabel =
|
||||
!!controlEl.id &&
|
||||
Array.from(parent.children).some(child => {
|
||||
return child.tagName === 'LABEL' && child.getAttribute('for') === controlEl.id;
|
||||
});
|
||||
|
||||
if (parent.tagName === 'LABEL' || parent.children.length === 1 || hasAssociatedLabel) {
|
||||
node = parent;
|
||||
}
|
||||
}
|
||||
|
||||
if (!container.contains(node)) return null;
|
||||
return node;
|
||||
}
|
||||
|
||||
function resolveDropdownHost(container, searchInput, placement) {
|
||||
const placementValue = String(placement || '').toLowerCase();
|
||||
const desiredPlacement = placementValue === 'inline' ? 'inline' : 'below-search';
|
||||
|
||||
let row = null;
|
||||
if (searchInput && container.contains(searchInput)) {
|
||||
const matchedRow = searchInput.closest('.flex');
|
||||
if (matchedRow && container.contains(matchedRow)) {
|
||||
row = matchedRow;
|
||||
}
|
||||
}
|
||||
|
||||
if (desiredPlacement === 'below-search') {
|
||||
if (row?.parentElement && container.contains(row.parentElement)) {
|
||||
return {
|
||||
host: row.parentElement,
|
||||
row,
|
||||
mode: 'below-search',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
host: container,
|
||||
row,
|
||||
mode: 'below-search',
|
||||
};
|
||||
}
|
||||
|
||||
if (row) {
|
||||
return {
|
||||
host: row,
|
||||
row,
|
||||
mode: 'inline',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
host: container,
|
||||
row: null,
|
||||
mode: desiredPlacement,
|
||||
};
|
||||
}
|
||||
|
||||
function hidePrimaryTitle(container) {
|
||||
const headings = Array.from(container.querySelectorAll('h1, h2, h3, h4, h5, h6'));
|
||||
const target = headings.find(heading => !heading.closest('button, summary'));
|
||||
if (!target) return;
|
||||
|
||||
const parent = target.parentElement;
|
||||
target.remove();
|
||||
|
||||
if (
|
||||
parent &&
|
||||
parent !== container &&
|
||||
parent.children.length === 0 &&
|
||||
!String(parent.textContent || '').trim()
|
||||
) {
|
||||
parent.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function ensureFiltersDropdown(config = {}) {
|
||||
const container = config.container;
|
||||
if (!container) return null;
|
||||
|
||||
const targets = [];
|
||||
const explicitTargets = normalizeFilterTargets(config.filterControls);
|
||||
explicitTargets.forEach(target => {
|
||||
const el = toElementInContainer(target, container);
|
||||
if (el) targets.push(el);
|
||||
});
|
||||
|
||||
if (config.includeStandardControls === true) {
|
||||
const perPage = toElementInContainer(config.perPageSelect, container);
|
||||
const sort = toElementInContainer(config.sortSelect, container);
|
||||
if (perPage) targets.push(perPage);
|
||||
if (sort) targets.push(sort);
|
||||
}
|
||||
|
||||
if (!targets.length) {
|
||||
const existing = container.querySelector('[data-nc-filters-dropdown="1"]');
|
||||
if (existing) existing.remove();
|
||||
return null;
|
||||
}
|
||||
|
||||
const placement = resolveDropdownHost(
|
||||
container,
|
||||
config.searchInput,
|
||||
config.filterDropdownPlacement
|
||||
);
|
||||
const host = placement.host;
|
||||
if (!host) return null;
|
||||
|
||||
let details = container.querySelector('[data-nc-filters-dropdown="1"]');
|
||||
let panel = container.querySelector('[data-nc-filters-dropdown-panel="1"]');
|
||||
let summary = container.querySelector('[data-nc-filters-dropdown-toggle="1"]');
|
||||
|
||||
if (!details || !panel || !summary) {
|
||||
details = document.createElement('details');
|
||||
details.dataset.ncFiltersDropdown = '1';
|
||||
details.className = placement.mode === 'below-search' ? 'relative mt-2 w-full' : 'relative';
|
||||
|
||||
summary = document.createElement('summary');
|
||||
summary.dataset.ncFiltersDropdownToggle = '1';
|
||||
summary.className =
|
||||
placement.mode === 'below-search'
|
||||
? 'inline-flex w-full cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]'
|
||||
: 'inline-flex cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]';
|
||||
summary.textContent = String(config.filterDropdownLabel || 'FILTERS');
|
||||
summary.style.listStyle = 'none';
|
||||
|
||||
panel = document.createElement('div');
|
||||
panel.dataset.ncFiltersDropdownPanel = '1';
|
||||
panel.className =
|
||||
'mt-2 flex flex-wrap items-center gap-3 rounded-md border border-[var(--color-border)] bg-[var(--color-surface)] p-3';
|
||||
|
||||
details.appendChild(summary);
|
||||
details.appendChild(panel);
|
||||
} else {
|
||||
details.className = placement.mode === 'below-search' ? 'relative mt-2 w-full' : 'relative';
|
||||
summary.className =
|
||||
placement.mode === 'below-search'
|
||||
? 'inline-flex w-full cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]'
|
||||
: 'inline-flex cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]';
|
||||
summary.textContent = String(config.filterDropdownLabel || 'FILTERS');
|
||||
}
|
||||
|
||||
if (
|
||||
placement.mode === 'below-search' &&
|
||||
placement.row &&
|
||||
placement.row.parentElement === host
|
||||
) {
|
||||
host.insertBefore(details, placement.row.nextSibling);
|
||||
} else if (!host.contains(details)) {
|
||||
host.appendChild(details);
|
||||
}
|
||||
|
||||
const movedNodes = [];
|
||||
const seen = new Set();
|
||||
const searchNode = resolveControlNode(config.searchInput, container);
|
||||
|
||||
targets.forEach(target => {
|
||||
const node = resolveControlNode(target, container);
|
||||
if (!node || node === searchNode || node.contains(searchNode)) return;
|
||||
if (seen.has(node)) return;
|
||||
|
||||
const hiddenControl =
|
||||
target.type === 'hidden' ||
|
||||
target.hidden === true ||
|
||||
target.classList?.contains('hidden') ||
|
||||
node.hidden === true ||
|
||||
node.classList?.contains('hidden');
|
||||
if (hiddenControl) return;
|
||||
|
||||
seen.add(node);
|
||||
movedNodes.push(node);
|
||||
});
|
||||
|
||||
movedNodes.forEach(node => {
|
||||
if (!panel.contains(node)) panel.appendChild(node);
|
||||
});
|
||||
|
||||
if (!panel.children.length) {
|
||||
details.remove();
|
||||
return null;
|
||||
}
|
||||
|
||||
return details;
|
||||
}
|
||||
|
||||
function applyFilterContainer(config = {}) {
|
||||
const container = toElement(config.container || config.filterContainer || config.id);
|
||||
if (!container) return null;
|
||||
|
||||
if (config.useDefaultShellClasses === true) {
|
||||
addClasses(container, DEFAULT_FILTER_CONTAINER_CLASSES);
|
||||
}
|
||||
addClasses(container, config.classes);
|
||||
|
||||
const role = Object.prototype.hasOwnProperty.call(config, 'role') ? config.role : 'region';
|
||||
if (role) container.setAttribute('role', role);
|
||||
if (config.label) container.setAttribute('aria-label', config.label);
|
||||
|
||||
container.dataset.ncFilterContainer = '1';
|
||||
|
||||
const searchInput = toElement(config.searchInput);
|
||||
normalizeSearchInputAria(searchInput, config.searchLabel || config.label);
|
||||
|
||||
let standardControlsResult = null;
|
||||
if (config.standardControls === true) {
|
||||
standardControlsResult = applyStandardControls({
|
||||
label: config.label,
|
||||
searchLabel: config.searchLabel,
|
||||
searchInput: searchInput || config.searchInput,
|
||||
searchPlaceholder: config.searchPlaceholder,
|
||||
forceSearchPlaceholder: config.forceSearchPlaceholder,
|
||||
perPageSelect: config.perPageSelect,
|
||||
perPageOptions: config.perPageOptions,
|
||||
perPageValue: config.perPageValue,
|
||||
sortSelect: config.sortSelect,
|
||||
sortOptions: config.sortOptions,
|
||||
sortValue: config.sortValue,
|
||||
});
|
||||
}
|
||||
|
||||
const resolvedSearchInput = standardControlsResult?.searchInput || searchInput;
|
||||
|
||||
if (config.hideTitle !== false) {
|
||||
hidePrimaryTitle(container);
|
||||
}
|
||||
|
||||
if (config.filtersDropdown !== false) {
|
||||
ensureFiltersDropdown({
|
||||
container,
|
||||
searchInput: resolvedSearchInput,
|
||||
filterControls: config.filterControls,
|
||||
includeStandardControls: config.includeStandardControlsInDropdown === true,
|
||||
perPageSelect:
|
||||
standardControlsResult?.perPageSelect || config.perPageSelect || config.perPageInput,
|
||||
sortSelect: standardControlsResult?.sortSelect || config.sortSelect || config.sortInput,
|
||||
filterDropdownPlacement: config.filterDropdownPlacement,
|
||||
filterDropdownLabel: config.filterDropdownLabel,
|
||||
});
|
||||
}
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
window.NCSearchFilterContainer = {
|
||||
apply: applyFilterContainer,
|
||||
applyStandardControls,
|
||||
getDefaultPerPageOptions: () => normalizePerPageOptions(DEFAULT_PER_PAGE_VALUES),
|
||||
getDefaultSortOptions: () => cloneOptions(DEFAULT_SORT_OPTIONS),
|
||||
};
|
||||
})();
|
||||
Reference in new issue
Block a user