fix: DockerSecretsResolver - don't normalize absolute paths like /var/www/html/...
Some checks failed
Deploy Application / deploy (push) Has been cancelled
Some checks failed
Deploy Application / deploy (push) Has been cancelled
This commit is contained in:
@@ -280,6 +280,214 @@ export class DomPatcher {
|
||||
// Fallback - not guaranteed to be unique
|
||||
return element.tagName.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap element content using different strategies
|
||||
*
|
||||
* Supports multiple swap strategies similar to htmx:
|
||||
* - innerHTML: Replace inner content (default)
|
||||
* - outerHTML: Replace element itself
|
||||
* - beforebegin: Insert before element
|
||||
* - afterbegin: Insert at start of element
|
||||
* - afterend: Insert after element
|
||||
* - beforeend: Insert at end of element
|
||||
* - none: No DOM update (only events/state)
|
||||
*
|
||||
* @param {HTMLElement} target - Target element to swap
|
||||
* @param {string} html - HTML content to swap
|
||||
* @param {string} strategy - Swap strategy (default: 'innerHTML')
|
||||
* @param {string} transition - Optional transition type (fade, slide, none)
|
||||
* @param {Object} scrollOptions - Optional scroll options { enabled, target, behavior }
|
||||
* @returns {boolean} - True if swap was successful
|
||||
*/
|
||||
swapElement(target, html, strategy = 'innerHTML', transition = null, scrollOptions = null) {
|
||||
if (!target || !target.parentNode) {
|
||||
console.warn('[DomPatcher] Invalid target element for swap');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Preserve focus state before swap
|
||||
const restoreFocus = this.preserveFocus(target);
|
||||
|
||||
// Apply transition if specified
|
||||
if (transition && transition !== 'none') {
|
||||
this.applyTransition(target, transition, strategy);
|
||||
}
|
||||
|
||||
// Parse HTML into document fragment
|
||||
const temp = document.createElement('div');
|
||||
temp.innerHTML = html;
|
||||
const newContent = temp.firstElementChild || temp;
|
||||
|
||||
try {
|
||||
switch (strategy) {
|
||||
case 'innerHTML':
|
||||
// Replace inner content (default behavior)
|
||||
target.innerHTML = html;
|
||||
break;
|
||||
|
||||
case 'outerHTML':
|
||||
// Replace element itself
|
||||
if (newContent.nodeType === Node.ELEMENT_NODE) {
|
||||
target.parentNode.replaceChild(newContent.cloneNode(true), target);
|
||||
} else {
|
||||
// If HTML doesn't have a single root element, wrap it
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.innerHTML = html;
|
||||
while (wrapper.firstChild) {
|
||||
target.parentNode.insertBefore(wrapper.firstChild, target);
|
||||
}
|
||||
target.parentNode.removeChild(target);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'beforebegin':
|
||||
// Insert before target element
|
||||
if (newContent.nodeType === Node.ELEMENT_NODE) {
|
||||
target.parentNode.insertBefore(newContent.cloneNode(true), target);
|
||||
} else {
|
||||
// Multiple nodes - insert all
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.innerHTML = html;
|
||||
while (wrapper.firstChild) {
|
||||
target.parentNode.insertBefore(wrapper.firstChild, target);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'afterbegin':
|
||||
// Insert at start of target element
|
||||
if (newContent.nodeType === Node.ELEMENT_NODE) {
|
||||
target.insertBefore(newContent.cloneNode(true), target.firstChild);
|
||||
} else {
|
||||
// Multiple nodes - insert all at start
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.innerHTML = html;
|
||||
while (wrapper.firstChild) {
|
||||
target.insertBefore(wrapper.firstChild, target.firstChild);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'afterend':
|
||||
// Insert after target element
|
||||
if (newContent.nodeType === Node.ELEMENT_NODE) {
|
||||
target.parentNode.insertBefore(newContent.cloneNode(true), target.nextSibling);
|
||||
} else {
|
||||
// Multiple nodes - insert all after
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.innerHTML = html;
|
||||
const nextSibling = target.nextSibling;
|
||||
while (wrapper.firstChild) {
|
||||
target.parentNode.insertBefore(wrapper.firstChild, nextSibling);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'beforeend':
|
||||
// Insert at end of target element
|
||||
if (newContent.nodeType === Node.ELEMENT_NODE) {
|
||||
target.appendChild(newContent.cloneNode(true));
|
||||
} else {
|
||||
// Multiple nodes - append all
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.innerHTML = html;
|
||||
while (wrapper.firstChild) {
|
||||
target.appendChild(wrapper.firstChild);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'none':
|
||||
// No DOM update - only events/state will be handled
|
||||
// This is handled by the caller, so we just return success
|
||||
return true;
|
||||
|
||||
default:
|
||||
console.warn(`[DomPatcher] Unknown swap strategy: ${strategy}, falling back to innerHTML`);
|
||||
target.innerHTML = html;
|
||||
break;
|
||||
}
|
||||
|
||||
// Restore focus after swap (only for strategies that don't remove the target)
|
||||
if (strategy !== 'outerHTML' && strategy !== 'none') {
|
||||
restoreFocus();
|
||||
}
|
||||
|
||||
// Handle scroll behavior if specified
|
||||
if (scrollOptions && scrollOptions.enabled) {
|
||||
this.scrollToTarget(scrollOptions.target || target, scrollOptions.behavior || 'smooth');
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('[DomPatcher] Error during swap:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply CSS transition to element
|
||||
*
|
||||
* @param {HTMLElement} element - Element to apply transition to
|
||||
* @param {string} transition - Transition type (fade, slide)
|
||||
* @param {string} strategy - Swap strategy
|
||||
*/
|
||||
applyTransition(element, transition, strategy) {
|
||||
// Add transition class
|
||||
const transitionClass = `lc-transition-${transition}`;
|
||||
|
||||
// For fade/slide transitions, we need to apply the transition class
|
||||
// and then trigger the transition by adding an active class
|
||||
element.classList.add(transitionClass);
|
||||
|
||||
// Force reflow to ensure class is applied
|
||||
void element.offsetWidth;
|
||||
|
||||
// Add active class to trigger transition
|
||||
requestAnimationFrame(() => {
|
||||
element.classList.add('lc-transition-active');
|
||||
});
|
||||
|
||||
// Remove transition classes after animation completes
|
||||
const handleTransitionEnd = (e) => {
|
||||
// Only handle transition end for this element
|
||||
if (e.target === element) {
|
||||
element.classList.remove(transitionClass);
|
||||
element.classList.remove('lc-transition-active');
|
||||
element.removeEventListener('transitionend', handleTransitionEnd);
|
||||
}
|
||||
};
|
||||
|
||||
element.addEventListener('transitionend', handleTransitionEnd, { once: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Scroll to target element
|
||||
*
|
||||
* @param {HTMLElement|string} target - Target element or selector
|
||||
* @param {string} behavior - Scroll behavior (smooth, instant)
|
||||
*/
|
||||
scrollToTarget(target, behavior = 'smooth') {
|
||||
let targetElement = target;
|
||||
|
||||
// If target is a string, try to find element
|
||||
if (typeof target === 'string') {
|
||||
targetElement = document.querySelector(target);
|
||||
}
|
||||
|
||||
if (!targetElement || !(targetElement instanceof HTMLElement)) {
|
||||
console.warn('[DomPatcher] Scroll target not found:', target);
|
||||
return;
|
||||
}
|
||||
|
||||
// Scroll to element
|
||||
targetElement.scrollIntoView({
|
||||
behavior: behavior === 'smooth' ? 'smooth' : 'auto',
|
||||
block: 'start',
|
||||
inline: 'nearest'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Create singleton instance
|
||||
|
||||
315
resources/js/modules/livecomponent/DrawerManager.js
Normal file
315
resources/js/modules/livecomponent/DrawerManager.js
Normal file
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* Drawer Manager for LiveComponents
|
||||
*
|
||||
* Manages drawer/sidebar components with:
|
||||
* - Slide-in animation (CSS Transitions)
|
||||
* - Overlay backdrop management
|
||||
* - ESC key handling
|
||||
* - Focus management (focus trapping)
|
||||
* - Stack management for multiple drawers
|
||||
*/
|
||||
|
||||
export class DrawerManager {
|
||||
constructor() {
|
||||
this.drawerStack = []; // Array of { componentId, drawerElement, overlayElement, zIndex, closeOnEscape, closeOnOverlay }
|
||||
this.baseZIndex = 1040;
|
||||
this.zIndexIncrement = 10;
|
||||
this.escapeHandler = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open drawer and add to stack
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {Object} options - Drawer options
|
||||
* @returns {Object} Drawer instance
|
||||
*/
|
||||
open(componentId, options = {}) {
|
||||
const {
|
||||
title = '',
|
||||
content = '',
|
||||
position = 'left',
|
||||
width = '400px',
|
||||
showOverlay = true,
|
||||
closeOnOverlay = true,
|
||||
closeOnEscape = true,
|
||||
animation = 'slide'
|
||||
} = options;
|
||||
|
||||
// Calculate z-index
|
||||
const zIndex = this.baseZIndex + (this.drawerStack.length * this.zIndexIncrement);
|
||||
|
||||
// Create overlay if needed
|
||||
let overlay = null;
|
||||
if (showOverlay) {
|
||||
overlay = this.createOverlay(zIndex, closeOnOverlay, componentId);
|
||||
document.body.appendChild(overlay);
|
||||
}
|
||||
|
||||
// Create drawer element
|
||||
const drawer = this.createDrawerElement(componentId, title, content, position, width, animation, zIndex + 1);
|
||||
document.body.appendChild(drawer);
|
||||
|
||||
// Track in stack
|
||||
const stackItem = {
|
||||
componentId,
|
||||
drawerElement: drawer,
|
||||
overlayElement: overlay,
|
||||
zIndex: zIndex + 1,
|
||||
closeOnEscape,
|
||||
closeOnOverlay
|
||||
};
|
||||
this.drawerStack.push(stackItem);
|
||||
|
||||
// Setup event handlers
|
||||
this.setupDrawerHandlers(drawer, overlay, componentId, closeOnOverlay, closeOnEscape);
|
||||
|
||||
// Update ESC handler
|
||||
this.updateEscapeHandler();
|
||||
|
||||
// Animate in
|
||||
requestAnimationFrame(() => {
|
||||
if (overlay) {
|
||||
overlay.classList.add('drawer-overlay--show');
|
||||
}
|
||||
drawer.classList.add('drawer--show');
|
||||
});
|
||||
|
||||
// Focus management
|
||||
this.focusDrawer(drawer);
|
||||
|
||||
return {
|
||||
drawer: drawer,
|
||||
overlay: overlay,
|
||||
close: () => this.close(componentId),
|
||||
isOpen: () => drawer.classList.contains('drawer--show')
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Close drawer and remove from stack
|
||||
* @param {string} componentId - Component ID
|
||||
*/
|
||||
close(componentId) {
|
||||
const index = this.drawerStack.findIndex(item => item.componentId === componentId);
|
||||
if (index === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { drawerElement, overlayElement } = this.drawerStack[index];
|
||||
|
||||
// Animate out
|
||||
drawerElement.classList.remove('drawer--show');
|
||||
if (overlayElement) {
|
||||
overlayElement.classList.remove('drawer-overlay--show');
|
||||
}
|
||||
|
||||
// Remove from DOM after animation
|
||||
setTimeout(() => {
|
||||
if (drawerElement.parentNode) {
|
||||
drawerElement.parentNode.removeChild(drawerElement);
|
||||
}
|
||||
if (overlayElement && overlayElement.parentNode) {
|
||||
overlayElement.parentNode.removeChild(overlayElement);
|
||||
}
|
||||
}, 300); // Match CSS transition duration
|
||||
|
||||
// Remove from stack
|
||||
this.drawerStack.splice(index, 1);
|
||||
|
||||
// Update ESC handler
|
||||
this.updateEscapeHandler();
|
||||
|
||||
// Focus previous drawer or return focus to body
|
||||
if (this.drawerStack.length > 0) {
|
||||
const previousDrawer = this.drawerStack[this.drawerStack.length - 1];
|
||||
this.focusDrawer(previousDrawer.drawerElement);
|
||||
} else {
|
||||
// Return focus to previously focused element
|
||||
const activeElement = document.activeElement;
|
||||
if (activeElement && activeElement !== document.body) {
|
||||
activeElement.blur();
|
||||
}
|
||||
document.body.focus();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close all drawers
|
||||
*/
|
||||
closeAll() {
|
||||
while (this.drawerStack.length > 0) {
|
||||
const { componentId } = this.drawerStack[this.drawerStack.length - 1];
|
||||
this.close(componentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get topmost drawer
|
||||
* @returns {Object|null}
|
||||
*/
|
||||
getTopDrawer() {
|
||||
if (this.drawerStack.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return this.drawerStack[this.drawerStack.length - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if drawer is open
|
||||
* @param {string} componentId - Component ID
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isOpen(componentId) {
|
||||
return this.drawerStack.some(item => item.componentId === componentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create overlay element
|
||||
* @param {number} zIndex - Z-index value
|
||||
* @param {boolean} closeOnOverlay - Whether to close on overlay click
|
||||
* @param {string} componentId - Component ID
|
||||
* @returns {HTMLElement}
|
||||
*/
|
||||
createOverlay(zIndex, closeOnOverlay, componentId) {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'drawer-overlay';
|
||||
overlay.style.zIndex = zIndex.toString();
|
||||
overlay.setAttribute('role', 'presentation');
|
||||
overlay.setAttribute('aria-hidden', 'true');
|
||||
|
||||
if (closeOnOverlay) {
|
||||
overlay.addEventListener('click', () => {
|
||||
this.close(componentId);
|
||||
});
|
||||
}
|
||||
|
||||
return overlay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create drawer element
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {string} title - Drawer title
|
||||
* @param {string} content - Drawer content
|
||||
* @param {string} position - Position (left/right)
|
||||
* @param {string} width - Drawer width
|
||||
* @param {string} animation - Animation type
|
||||
* @param {number} zIndex - Z-index value
|
||||
* @returns {HTMLElement}
|
||||
*/
|
||||
createDrawerElement(componentId, title, content, position, width, animation, zIndex) {
|
||||
const drawer = document.createElement('div');
|
||||
drawer.className = `drawer drawer--${position} drawer-animation-${animation}`;
|
||||
drawer.id = `drawer-${componentId}`;
|
||||
drawer.style.zIndex = zIndex.toString();
|
||||
drawer.style.width = width;
|
||||
drawer.setAttribute('role', 'dialog');
|
||||
drawer.setAttribute('aria-modal', 'true');
|
||||
drawer.setAttribute('aria-labelledby', title ? `drawer-title-${componentId}` : '');
|
||||
|
||||
drawer.innerHTML = `
|
||||
<div class="drawer-content">
|
||||
${title ? `
|
||||
<div class="drawer-header">
|
||||
<h3 class="drawer-title" id="drawer-title-${componentId}">${title}</h3>
|
||||
<button class="drawer-close" aria-label="Close drawer">×</button>
|
||||
</div>
|
||||
` : ''}
|
||||
<div class="drawer-body">${content}</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return drawer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup event handlers for drawer
|
||||
* @param {HTMLElement} drawer - Drawer element
|
||||
* @param {HTMLElement|null} overlay - Overlay element
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {boolean} closeOnOverlay - Whether to close on overlay click
|
||||
* @param {boolean} closeOnEscape - Whether to close on ESC key
|
||||
*/
|
||||
setupDrawerHandlers(drawer, overlay, componentId, closeOnOverlay, closeOnEscape) {
|
||||
// Close button
|
||||
const closeBtn = drawer.querySelector('.drawer-close');
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', () => {
|
||||
this.close(componentId);
|
||||
});
|
||||
}
|
||||
|
||||
// Overlay click (already handled in createOverlay, but ensure it's set)
|
||||
if (overlay && closeOnOverlay) {
|
||||
// Already set in createOverlay
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update ESC key handler
|
||||
*/
|
||||
updateEscapeHandler() {
|
||||
// Remove existing handler
|
||||
if (this.escapeHandler) {
|
||||
document.removeEventListener('keydown', this.escapeHandler);
|
||||
this.escapeHandler = null;
|
||||
}
|
||||
|
||||
// Add handler if there are drawers
|
||||
if (this.drawerStack.length > 0) {
|
||||
const topDrawer = this.getTopDrawer();
|
||||
if (topDrawer && topDrawer.closeOnEscape) {
|
||||
this.escapeHandler = (e) => {
|
||||
if (e.key === 'Escape' && !e.defaultPrevented) {
|
||||
e.preventDefault();
|
||||
this.close(topDrawer.componentId);
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', this.escapeHandler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Focus drawer element
|
||||
* @param {HTMLElement} drawer - Drawer element
|
||||
*/
|
||||
focusDrawer(drawer) {
|
||||
if (!drawer) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find first focusable element
|
||||
const focusableSelectors = [
|
||||
'button:not([disabled])',
|
||||
'[href]',
|
||||
'input:not([disabled])',
|
||||
'select:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])'
|
||||
].join(', ');
|
||||
|
||||
const focusableElement = drawer.querySelector(focusableSelectors);
|
||||
if (focusableElement) {
|
||||
requestAnimationFrame(() => {
|
||||
focusableElement.focus();
|
||||
});
|
||||
} else {
|
||||
requestAnimationFrame(() => {
|
||||
drawer.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup all drawers
|
||||
*/
|
||||
destroy() {
|
||||
this.closeAll();
|
||||
if (this.escapeHandler) {
|
||||
document.removeEventListener('keydown', this.escapeHandler);
|
||||
this.escapeHandler = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,11 +53,23 @@ export class LazyComponentLoader {
|
||||
* Scan DOM for lazy components
|
||||
*/
|
||||
scanLazyComponents() {
|
||||
// Scan for regular lazy components
|
||||
const lazyElements = document.querySelectorAll('[data-live-component-lazy]');
|
||||
|
||||
lazyElements.forEach(element => {
|
||||
this.registerLazyComponent(element);
|
||||
});
|
||||
|
||||
// Scan for Island components (both lazy and non-lazy)
|
||||
const islandElements = document.querySelectorAll('[data-island-component]');
|
||||
islandElements.forEach(element => {
|
||||
if (element.dataset.liveComponentLazy) {
|
||||
// Lazy Island - register for lazy loading
|
||||
this.registerLazyComponent(element);
|
||||
} else if (element.dataset.liveComponentIsland) {
|
||||
// Non-lazy Island - load immediately
|
||||
this.loadIslandComponentImmediately(element);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -193,8 +205,14 @@ export class LazyComponentLoader {
|
||||
// Show loading indicator
|
||||
this.showLoadingIndicator(config.element);
|
||||
|
||||
// Check if this is an Island component
|
||||
const isIsland = config.element.dataset.islandComponent === 'true';
|
||||
const endpoint = isIsland
|
||||
? `/live-component/${config.componentId}/island`
|
||||
: `/live-component/${config.componentId}/lazy-load`;
|
||||
|
||||
// Request component HTML from server
|
||||
const response = await fetch(`/live-component/${config.componentId}/lazy-load`, {
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
@@ -218,6 +236,11 @@ export class LazyComponentLoader {
|
||||
// Mark element as regular LiveComponent (no longer lazy)
|
||||
config.element.setAttribute('data-live-component', config.componentId);
|
||||
config.element.removeAttribute('data-live-component-lazy');
|
||||
|
||||
// Keep island-component attribute for isolated initialization
|
||||
if (isIsland) {
|
||||
config.element.setAttribute('data-island-component', 'true');
|
||||
}
|
||||
|
||||
// Copy CSRF token to element
|
||||
if (data.csrf_token) {
|
||||
@@ -231,8 +254,8 @@ export class LazyComponentLoader {
|
||||
config.element.dataset.state = stateJson;
|
||||
}
|
||||
|
||||
// Initialize as regular LiveComponent
|
||||
this.liveComponentManager.init(config.element);
|
||||
// Initialize as regular LiveComponent (or Island if isolated)
|
||||
this.liveComponentManager.init(config.element, { isolated: isIsland });
|
||||
|
||||
// Mark as loaded
|
||||
config.loaded = true;
|
||||
@@ -241,11 +264,11 @@ export class LazyComponentLoader {
|
||||
// Stop observing
|
||||
this.observer.unobserve(config.element);
|
||||
|
||||
console.log(`[LazyLoader] Loaded: ${config.componentId}`);
|
||||
console.log(`[LazyLoader] Loaded: ${config.componentId}${isIsland ? ' (Island)' : ''}`);
|
||||
|
||||
// Dispatch custom event
|
||||
config.element.dispatchEvent(new CustomEvent('livecomponent:lazy:loaded', {
|
||||
detail: { componentId: config.componentId }
|
||||
detail: { componentId: config.componentId, isIsland }
|
||||
}));
|
||||
|
||||
} catch (error) {
|
||||
@@ -266,6 +289,88 @@ export class LazyComponentLoader {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load Island component immediately (non-lazy)
|
||||
*
|
||||
* @param {HTMLElement} element - Island component element
|
||||
*/
|
||||
async loadIslandComponentImmediately(element) {
|
||||
const componentId = element.dataset.liveComponentIsland;
|
||||
if (!componentId) {
|
||||
console.warn('[LazyLoader] Island component missing componentId:', element);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`[LazyLoader] Loading Island immediately: ${componentId}`);
|
||||
|
||||
// Show loading indicator
|
||||
this.showLoadingIndicator(element);
|
||||
|
||||
// Request component HTML from Island endpoint
|
||||
const response = await fetch(`/live-component/${componentId}/island`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.success) {
|
||||
throw new Error(data.error || 'Failed to load Island component');
|
||||
}
|
||||
|
||||
// Replace placeholder with component HTML
|
||||
element.innerHTML = data.html;
|
||||
|
||||
// Mark element as Island component
|
||||
element.setAttribute('data-live-component', componentId);
|
||||
element.setAttribute('data-island-component', 'true');
|
||||
element.removeAttribute('data-live-component-island');
|
||||
|
||||
// Copy CSRF token to element
|
||||
if (data.csrf_token) {
|
||||
element.dataset.csrfToken = data.csrf_token;
|
||||
}
|
||||
|
||||
// Copy state to element
|
||||
if (data.state) {
|
||||
const stateJson = JSON.stringify(data.state);
|
||||
element.dataset.state = stateJson;
|
||||
}
|
||||
|
||||
// Initialize as isolated Island component
|
||||
this.liveComponentManager.init(element, { isolated: true });
|
||||
|
||||
console.log(`[LazyLoader] Loaded Island: ${componentId}`);
|
||||
|
||||
// Dispatch custom event
|
||||
element.dispatchEvent(new CustomEvent('livecomponent:island:loaded', {
|
||||
detail: { componentId }
|
||||
}));
|
||||
|
||||
} catch (error) {
|
||||
console.error(`[LazyLoader] Failed to load Island ${componentId}:`, error);
|
||||
|
||||
// Show error state
|
||||
this.showError(element, error.message);
|
||||
|
||||
// Dispatch error event
|
||||
element.dispatchEvent(new CustomEvent('livecomponent:island:error', {
|
||||
detail: {
|
||||
componentId,
|
||||
error: error.message
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show placeholder
|
||||
*
|
||||
@@ -415,3 +520,4 @@ export class LazyComponentLoader {
|
||||
|
||||
// Export for use in LiveComponent module
|
||||
export default LazyComponentLoader;
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
*/
|
||||
|
||||
import { UIManager } from '../ui/UIManager.js';
|
||||
import { ToastQueue } from './ToastQueue.js';
|
||||
import { ModalManager } from './ModalManager.js';
|
||||
|
||||
export class LiveComponentUIHelper {
|
||||
constructor(liveComponentManager) {
|
||||
@@ -13,6 +15,11 @@ export class LiveComponentUIHelper {
|
||||
this.uiManager = UIManager;
|
||||
this.activeDialogs = new Map(); // componentId → dialog instances
|
||||
this.activeNotifications = new Map(); // componentId → notification instances
|
||||
this.toastQueue = new ToastQueue(5); // Max 5 toasts
|
||||
|
||||
// Use ModalManager with native <dialog> element
|
||||
// Native <dialog> provides automatic backdrop, focus management, and ESC handling
|
||||
this.modalManager = new ModalManager();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -34,27 +41,29 @@ export class LiveComponentUIHelper {
|
||||
onConfirm = null
|
||||
} = options;
|
||||
|
||||
// Create dialog content
|
||||
const dialogContent = this.createDialogContent(title, content, buttons, {
|
||||
onClose,
|
||||
onConfirm
|
||||
});
|
||||
|
||||
// Show modal via UIManager
|
||||
const modal = this.uiManager.open('modal', {
|
||||
content: dialogContent,
|
||||
className: `livecomponent-dialog livecomponent-dialog--${size}`,
|
||||
onClose: () => {
|
||||
if (onClose) {
|
||||
onClose();
|
||||
}
|
||||
this.activeDialogs.delete(componentId);
|
||||
}
|
||||
// Use ModalManager for better stack management
|
||||
const modal = this.modalManager.open(componentId, {
|
||||
title: title,
|
||||
content: content,
|
||||
size: size,
|
||||
buttons: buttons,
|
||||
closeOnBackdrop: closeOnBackdrop,
|
||||
closeOnEscape: closeOnEscape
|
||||
});
|
||||
|
||||
// Store reference
|
||||
this.activeDialogs.set(componentId, modal);
|
||||
|
||||
// Setup onClose callback
|
||||
if (onClose && modal.dialog) {
|
||||
const originalClose = modal.close;
|
||||
modal.close = () => {
|
||||
originalClose.call(modal);
|
||||
onClose();
|
||||
this.activeDialogs.delete(componentId);
|
||||
};
|
||||
}
|
||||
|
||||
return modal;
|
||||
}
|
||||
|
||||
@@ -142,11 +151,9 @@ export class LiveComponentUIHelper {
|
||||
* @param {string} componentId - Component ID
|
||||
*/
|
||||
closeDialog(componentId) {
|
||||
const dialog = this.activeDialogs.get(componentId);
|
||||
if (dialog && typeof dialog.close === 'function') {
|
||||
dialog.close();
|
||||
this.activeDialogs.delete(componentId);
|
||||
}
|
||||
// Use ModalManager to close
|
||||
this.modalManager.close(componentId);
|
||||
this.activeDialogs.delete(componentId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -164,74 +171,20 @@ export class LiveComponentUIHelper {
|
||||
action = null
|
||||
} = options;
|
||||
|
||||
// Create notification element
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `livecomponent-notification livecomponent-notification--${type} livecomponent-notification--${position}`;
|
||||
notification.setAttribute('role', 'alert');
|
||||
notification.setAttribute('aria-live', 'polite');
|
||||
|
||||
notification.innerHTML = `
|
||||
<div class="notification-content">
|
||||
<span class="notification-message">${message}</span>
|
||||
${action ? `<button class="notification-action">${action.text}</button>` : ''}
|
||||
<button class="notification-close" aria-label="Close">×</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Add styles
|
||||
notification.style.cssText = `
|
||||
position: fixed;
|
||||
${position.includes('top') ? 'top' : 'bottom'}: 1rem;
|
||||
${position.includes('left') ? 'left' : 'right'}: 1rem;
|
||||
max-width: 400px;
|
||||
padding: 1rem;
|
||||
background: ${this.getNotificationColor(type)};
|
||||
color: white;
|
||||
border-radius: 0.5rem;
|
||||
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
|
||||
z-index: 10000;
|
||||
opacity: 0;
|
||||
transform: translateY(${position.includes('top') ? '-20px' : '20px'});
|
||||
transition: opacity 0.3s ease, transform 0.3s ease;
|
||||
`;
|
||||
|
||||
// Add to DOM
|
||||
document.body.appendChild(notification);
|
||||
|
||||
// Animate in
|
||||
requestAnimationFrame(() => {
|
||||
notification.style.opacity = '1';
|
||||
notification.style.transform = 'translateY(0)';
|
||||
// Use ToastQueue for better management
|
||||
const toast = this.toastQueue.add(componentId, {
|
||||
message: message,
|
||||
type: type,
|
||||
duration: duration,
|
||||
position: position
|
||||
});
|
||||
|
||||
// Setup close button
|
||||
const closeBtn = notification.querySelector('.notification-close');
|
||||
closeBtn.addEventListener('click', () => {
|
||||
this.hideNotification(notification);
|
||||
});
|
||||
|
||||
// Setup action button
|
||||
if (action) {
|
||||
const actionBtn = notification.querySelector('.notification-action');
|
||||
actionBtn.addEventListener('click', () => {
|
||||
if (action.handler) {
|
||||
action.handler();
|
||||
}
|
||||
this.hideNotification(notification);
|
||||
});
|
||||
// Store reference for compatibility
|
||||
if (toast) {
|
||||
this.activeNotifications.set(componentId, toast);
|
||||
}
|
||||
|
||||
// Auto-hide after duration
|
||||
if (duration > 0) {
|
||||
setTimeout(() => {
|
||||
this.hideNotification(notification);
|
||||
}, duration);
|
||||
}
|
||||
|
||||
// Store reference
|
||||
this.activeNotifications.set(componentId, notification);
|
||||
|
||||
return notification;
|
||||
return toast;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -240,31 +193,17 @@ export class LiveComponentUIHelper {
|
||||
* @param {HTMLElement|string} notificationOrComponentId - Notification element or component ID
|
||||
*/
|
||||
hideNotification(notificationOrComponentId) {
|
||||
const notification = typeof notificationOrComponentId === 'string'
|
||||
? this.activeNotifications.get(notificationOrComponentId)
|
||||
: notificationOrComponentId;
|
||||
const componentId = typeof notificationOrComponentId === 'string'
|
||||
? notificationOrComponentId
|
||||
: notificationOrComponentId.dataset?.componentId;
|
||||
|
||||
if (!notification) {
|
||||
if (!componentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Animate out
|
||||
notification.style.opacity = '0';
|
||||
notification.style.transform = `translateY(${notification.classList.contains('livecomponent-notification--top') ? '-20px' : '20px'})`;
|
||||
|
||||
setTimeout(() => {
|
||||
if (notification.parentNode) {
|
||||
notification.parentNode.removeChild(notification);
|
||||
}
|
||||
|
||||
// Remove from map
|
||||
for (const [componentId, notif] of this.activeNotifications.entries()) {
|
||||
if (notif === notification) {
|
||||
this.activeNotifications.delete(componentId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}, 300);
|
||||
// Use ToastQueue to remove
|
||||
this.toastQueue.remove(componentId);
|
||||
this.activeNotifications.delete(componentId);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -39,13 +39,29 @@ export class LoadingStateManager {
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {HTMLElement} element - Component element
|
||||
* @param {Object} options - Loading options
|
||||
* @param {HTMLElement} actionElement - Optional action element (for per-action indicators)
|
||||
*/
|
||||
showLoading(componentId, element, options = {}) {
|
||||
showLoading(componentId, element, options = {}, actionElement = null) {
|
||||
const config = this.loadingConfigs.get(componentId) || {
|
||||
type: this.config.defaultType,
|
||||
showDelay: this.config.showDelay
|
||||
};
|
||||
|
||||
// Check for per-action indicator (data-lc-indicator)
|
||||
if (actionElement?.dataset.lcIndicator) {
|
||||
const indicatorSelector = actionElement.dataset.lcIndicator;
|
||||
const indicators = document.querySelectorAll(indicatorSelector);
|
||||
indicators.forEach(indicator => {
|
||||
if (indicator instanceof HTMLElement) {
|
||||
indicator.style.display = '';
|
||||
indicator.setAttribute('aria-busy', 'true');
|
||||
indicator.classList.add('lc-indicator-active');
|
||||
}
|
||||
});
|
||||
// Don't show default loading if custom indicator is used
|
||||
return;
|
||||
}
|
||||
|
||||
const loadingType = options.type || config.type;
|
||||
|
||||
// Skip if type is 'none' or optimistic UI is enabled
|
||||
@@ -86,8 +102,21 @@ export class LoadingStateManager {
|
||||
* Hide loading state
|
||||
*
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {HTMLElement} actionElement - Optional action element (for per-action indicators)
|
||||
*/
|
||||
hideLoading(componentId) {
|
||||
hideLoading(componentId, actionElement = null) {
|
||||
// Hide per-action indicators if specified
|
||||
if (actionElement?.dataset.lcIndicator) {
|
||||
const indicatorSelector = actionElement.dataset.lcIndicator;
|
||||
const indicators = document.querySelectorAll(indicatorSelector);
|
||||
indicators.forEach(indicator => {
|
||||
if (indicator instanceof HTMLElement) {
|
||||
indicator.removeAttribute('aria-busy');
|
||||
indicator.classList.remove('lc-indicator-active');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Hide skeleton loading
|
||||
this.actionLoadingManager.hideLoading(componentId);
|
||||
|
||||
|
||||
270
resources/js/modules/livecomponent/ModalManager.js
Normal file
270
resources/js/modules/livecomponent/ModalManager.js
Normal file
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* Modal Manager for LiveComponents
|
||||
*
|
||||
* Manages modal stack using native <dialog> element with showModal().
|
||||
*
|
||||
* Native <dialog> Features:
|
||||
* - Automatic backdrop/overlay (::backdrop pseudo-element)
|
||||
* - Automatic focus management (focus trapping)
|
||||
* - Automatic ESC handling (cancel event)
|
||||
* - Native modal semantics (blocks background interaction)
|
||||
* - Better accessibility (ARIA attributes)
|
||||
*
|
||||
* Browser Support:
|
||||
* - Chrome 37+ (2014)
|
||||
* - Firefox 98+ (2022)
|
||||
* - Safari 15.4+ (2022)
|
||||
*/
|
||||
|
||||
export class ModalManager {
|
||||
constructor() {
|
||||
this.modalStack = []; // Array of { componentId, dialogElement, zIndex, closeOnEscape, closeOnBackdrop }
|
||||
this.baseZIndex = 1050; // Bootstrap modal default
|
||||
this.zIndexIncrement = 10;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open modal using native <dialog> element
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {Object} options - Modal options
|
||||
* @returns {Object} Modal instance with dialog element
|
||||
*/
|
||||
open(componentId, options = {}) {
|
||||
const {
|
||||
title = '',
|
||||
content = '',
|
||||
size = 'medium',
|
||||
buttons = [],
|
||||
closeOnBackdrop = true,
|
||||
closeOnEscape = true
|
||||
} = options;
|
||||
|
||||
// Calculate z-index for stacking
|
||||
const zIndex = this.baseZIndex + (this.modalStack.length * this.zIndexIncrement);
|
||||
|
||||
// Create native <dialog> element
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.className = `livecomponent-modal livecomponent-modal--${size}`;
|
||||
dialog.id = `modal-${componentId}`;
|
||||
dialog.style.zIndex = zIndex.toString();
|
||||
|
||||
// Set content
|
||||
dialog.innerHTML = this.createModalContent(title, content, buttons);
|
||||
|
||||
// Add to DOM
|
||||
document.body.appendChild(dialog);
|
||||
|
||||
// Setup event handlers BEFORE showing modal
|
||||
this.setupDialogHandlers(dialog, componentId, closeOnBackdrop, closeOnEscape, buttons);
|
||||
|
||||
// Show modal using native showModal() - this blocks background interaction
|
||||
dialog.showModal();
|
||||
|
||||
// Track in stack
|
||||
const stackItem = {
|
||||
componentId,
|
||||
dialogElement: dialog,
|
||||
zIndex,
|
||||
closeOnEscape,
|
||||
closeOnBackdrop
|
||||
};
|
||||
this.modalStack.push(stackItem);
|
||||
|
||||
// Focus management (native <dialog> handles focus trapping, but we set initial focus)
|
||||
this.focusModal(dialog);
|
||||
|
||||
// Return wrapper object for compatibility
|
||||
return {
|
||||
dialog: dialog,
|
||||
close: () => this.close(componentId),
|
||||
isOpen: () => dialog.open
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup event handlers for dialog element
|
||||
* @param {HTMLDialogElement} dialog - Dialog element
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {boolean} closeOnBackdrop - Whether to close on backdrop click
|
||||
* @param {boolean} closeOnEscape - Whether to close on ESC key
|
||||
* @param {Array} buttons - Button configurations
|
||||
*/
|
||||
setupDialogHandlers(dialog, componentId, closeOnBackdrop, closeOnEscape, buttons) {
|
||||
// Native cancel event (triggered by ESC key)
|
||||
dialog.addEventListener('cancel', (e) => {
|
||||
e.preventDefault();
|
||||
if (closeOnEscape) {
|
||||
this.close(componentId);
|
||||
}
|
||||
});
|
||||
|
||||
// Backdrop click handling
|
||||
// Note: Native <dialog> doesn't have built-in backdrop click handling
|
||||
// We need to check if click target is the dialog element itself (backdrop)
|
||||
if (closeOnBackdrop) {
|
||||
dialog.addEventListener('click', (e) => {
|
||||
// If click target is the dialog element itself (not its children), it's a backdrop click
|
||||
if (e.target === dialog) {
|
||||
this.close(componentId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Close button
|
||||
const closeBtn = dialog.querySelector('.modal-close');
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', () => {
|
||||
this.close(componentId);
|
||||
});
|
||||
}
|
||||
|
||||
// Button actions
|
||||
dialog.querySelectorAll('[data-modal-action]').forEach((btn, index) => {
|
||||
btn.addEventListener('click', () => {
|
||||
const buttonConfig = buttons[index];
|
||||
if (buttonConfig && buttonConfig.action) {
|
||||
// Trigger action if specified
|
||||
if (buttonConfig.action === 'close') {
|
||||
this.close(componentId);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Close modal and remove from stack
|
||||
* @param {string} componentId - Component ID
|
||||
*/
|
||||
close(componentId) {
|
||||
const index = this.modalStack.findIndex(item => item.componentId === componentId);
|
||||
if (index === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { dialogElement } = this.modalStack[index];
|
||||
|
||||
// Close dialog using native close() method
|
||||
if (dialogElement && dialogElement.open) {
|
||||
dialogElement.close();
|
||||
}
|
||||
|
||||
// Remove from DOM
|
||||
if (dialogElement.parentNode) {
|
||||
dialogElement.parentNode.removeChild(dialogElement);
|
||||
}
|
||||
|
||||
// Remove from stack
|
||||
this.modalStack.splice(index, 1);
|
||||
|
||||
// Focus previous modal or return focus to body
|
||||
if (this.modalStack.length > 0) {
|
||||
const previousModal = this.modalStack[this.modalStack.length - 1];
|
||||
this.focusModal(previousModal.dialogElement);
|
||||
} else {
|
||||
// Return focus to previously focused element or body
|
||||
// Native <dialog> handles this automatically, but we ensure it
|
||||
const activeElement = document.activeElement;
|
||||
if (activeElement && activeElement !== document.body) {
|
||||
activeElement.blur();
|
||||
}
|
||||
document.body.focus();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close all modals
|
||||
*/
|
||||
closeAll() {
|
||||
while (this.modalStack.length > 0) {
|
||||
const { componentId } = this.modalStack[this.modalStack.length - 1];
|
||||
this.close(componentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get topmost modal
|
||||
* @returns {Object|null}
|
||||
*/
|
||||
getTopModal() {
|
||||
if (this.modalStack.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return this.modalStack[this.modalStack.length - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if modal is open
|
||||
* @param {string} componentId - Component ID
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isOpen(componentId) {
|
||||
return this.modalStack.some(item => item.componentId === componentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Focus modal element
|
||||
* Native <dialog> handles focus trapping automatically, but we set initial focus
|
||||
* @param {HTMLDialogElement} dialog - Dialog element
|
||||
*/
|
||||
focusModal(dialog) {
|
||||
if (!dialog) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find first focusable element
|
||||
const focusableSelectors = [
|
||||
'button:not([disabled])',
|
||||
'[href]',
|
||||
'input:not([disabled])',
|
||||
'select:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])'
|
||||
].join(', ');
|
||||
|
||||
const focusableElement = dialog.querySelector(focusableSelectors);
|
||||
if (focusableElement) {
|
||||
// Small delay to ensure dialog is fully rendered
|
||||
requestAnimationFrame(() => {
|
||||
focusableElement.focus();
|
||||
});
|
||||
} else {
|
||||
// Fallback: focus dialog itself
|
||||
requestAnimationFrame(() => {
|
||||
dialog.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create modal content HTML
|
||||
* @param {string} title - Modal title
|
||||
* @param {string} content - Modal content
|
||||
* @param {Array} buttons - Button configurations
|
||||
* @returns {string}
|
||||
*/
|
||||
createModalContent(title, content, buttons) {
|
||||
const buttonsHtml = buttons.map((btn, index) => {
|
||||
const btnClass = btn.class || btn.className || 'btn-secondary';
|
||||
return `<button class="btn ${btnClass}" data-modal-action="${index}">${btn.text || 'Button'}</button>`;
|
||||
}).join('');
|
||||
|
||||
return `
|
||||
<div class="livecomponent-modal-content">
|
||||
${title ? `<div class="modal-header">
|
||||
<h3 class="modal-title">${title}</h3>
|
||||
<button class="modal-close" aria-label="Close">×</button>
|
||||
</div>` : ''}
|
||||
<div class="modal-body">${content}</div>
|
||||
${buttons.length > 0 ? `<div class="modal-footer">${buttonsHtml}</div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup all modals
|
||||
*/
|
||||
destroy() {
|
||||
this.closeAll();
|
||||
}
|
||||
}
|
||||
346
resources/js/modules/livecomponent/PopoverManager.js
Normal file
346
resources/js/modules/livecomponent/PopoverManager.js
Normal file
@@ -0,0 +1,346 @@
|
||||
/**
|
||||
* Popover Manager for LiveComponents
|
||||
*
|
||||
* Manages popover components with:
|
||||
* - Native Popover API support (Chrome 114+)
|
||||
* - Fallback for older browsers
|
||||
* - Position calculation relative to anchor
|
||||
* - Auto-repositioning on scroll/resize
|
||||
* - Light-dismiss handling
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if Popover API is supported
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function supportsPopoverAPI() {
|
||||
// Check for popover property
|
||||
if (HTMLElement.prototype.hasOwnProperty('popover')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for showPopover method
|
||||
if ('showPopover' in HTMLElement.prototype) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for CSS @supports (only in browser environment)
|
||||
if (typeof CSS !== 'undefined' && CSS.supports) {
|
||||
try {
|
||||
return CSS.supports('popover', 'auto');
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export class PopoverManager {
|
||||
constructor() {
|
||||
this.popovers = new Map(); // componentId → popover element
|
||||
this.usePopoverAPI = supportsPopoverAPI();
|
||||
this.resizeHandler = null;
|
||||
this.scrollHandler = null;
|
||||
|
||||
if (this.usePopoverAPI) {
|
||||
console.log('[PopoverManager] Using native Popover API');
|
||||
} else {
|
||||
console.log('[PopoverManager] Using fallback implementation');
|
||||
this.setupGlobalHandlers();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show popover
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {Object} options - Popover options
|
||||
* @returns {Object} Popover instance
|
||||
*/
|
||||
show(componentId, options = {}) {
|
||||
const {
|
||||
content = '',
|
||||
title = '',
|
||||
anchorId = null,
|
||||
position = 'top',
|
||||
showArrow = true,
|
||||
offset = 8,
|
||||
closeOnOutsideClick = true,
|
||||
zIndex = 1060
|
||||
} = options;
|
||||
|
||||
if (!anchorId) {
|
||||
console.warn('[PopoverManager] Popover requires anchorId');
|
||||
return null;
|
||||
}
|
||||
|
||||
const anchor = document.getElementById(anchorId);
|
||||
if (!anchor) {
|
||||
console.warn(`[PopoverManager] Anchor element not found: ${anchorId}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Remove existing popover for this component
|
||||
this.hide(componentId);
|
||||
|
||||
if (this.usePopoverAPI) {
|
||||
return this.showWithPopoverAPI(componentId, anchor, content, title, position, showArrow, offset, zIndex);
|
||||
} else {
|
||||
return this.showWithFallback(componentId, anchor, content, title, position, showArrow, offset, closeOnOutsideClick, zIndex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show popover using native Popover API
|
||||
*/
|
||||
showWithPopoverAPI(componentId, anchor, content, title, position, showArrow, offset, zIndex) {
|
||||
const popover = document.createElement('div');
|
||||
popover.setAttribute('popover', 'auto'); // 'auto' = light-dismiss enabled
|
||||
popover.className = `livecomponent-popover popover--${position}`;
|
||||
popover.id = `popover-${componentId}`;
|
||||
popover.style.zIndex = zIndex.toString();
|
||||
|
||||
popover.innerHTML = `
|
||||
${showArrow ? `<div class="popover-arrow popover-arrow--${position}"></div>` : ''}
|
||||
${title ? `<div class="popover-header"><h4>${title}</h4></div>` : ''}
|
||||
<div class="popover-body">${content}</div>
|
||||
`;
|
||||
|
||||
// Set anchor using anchor attribute (when supported)
|
||||
if (popover.setPopoverAnchor) {
|
||||
popover.setPopoverAnchor(anchor);
|
||||
} else {
|
||||
// Fallback: position manually
|
||||
this.positionPopover(popover, anchor, position, offset);
|
||||
}
|
||||
|
||||
document.body.appendChild(popover);
|
||||
popover.showPopover();
|
||||
|
||||
this.popovers.set(componentId, popover);
|
||||
|
||||
// Setup repositioning on scroll/resize
|
||||
this.setupRepositioning(popover, anchor, position, offset);
|
||||
|
||||
return {
|
||||
element: popover,
|
||||
hide: () => this.hide(componentId),
|
||||
isVisible: () => popover.matches(':popover-open')
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Show popover using fallback implementation
|
||||
*/
|
||||
showWithFallback(componentId, anchor, content, title, position, showArrow, offset, closeOnOutsideClick, zIndex) {
|
||||
const popover = document.createElement('div');
|
||||
popover.className = `livecomponent-popover popover-fallback popover--${position}`;
|
||||
popover.id = `popover-${componentId}`;
|
||||
popover.style.zIndex = zIndex.toString();
|
||||
popover.setAttribute('role', 'tooltip');
|
||||
popover.setAttribute('aria-hidden', 'false');
|
||||
|
||||
popover.innerHTML = `
|
||||
${showArrow ? `<div class="popover-arrow popover-arrow--${position}"></div>` : ''}
|
||||
${title ? `<div class="popover-header"><h4>${title}</h4></div>` : ''}
|
||||
<div class="popover-body">${content}</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(popover);
|
||||
|
||||
// Position popover
|
||||
this.positionPopover(popover, anchor, position, offset);
|
||||
|
||||
// Show popover
|
||||
popover.style.display = 'block';
|
||||
popover.classList.add('popover--show');
|
||||
|
||||
this.popovers.set(componentId, popover);
|
||||
|
||||
// Setup click-outside handling
|
||||
if (closeOnOutsideClick) {
|
||||
const clickHandler = (e) => {
|
||||
if (!popover.contains(e.target) && !anchor.contains(e.target)) {
|
||||
this.hide(componentId);
|
||||
}
|
||||
};
|
||||
setTimeout(() => {
|
||||
document.addEventListener('click', clickHandler);
|
||||
popover._clickHandler = clickHandler;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// Setup repositioning on scroll/resize
|
||||
this.setupRepositioning(popover, anchor, position, offset);
|
||||
|
||||
return {
|
||||
element: popover,
|
||||
hide: () => this.hide(componentId),
|
||||
isVisible: () => popover.classList.contains('popover--show')
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide popover
|
||||
* @param {string} componentId - Component ID
|
||||
*/
|
||||
hide(componentId) {
|
||||
const popover = this.popovers.get(componentId);
|
||||
if (!popover) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.usePopoverAPI) {
|
||||
if (popover.hidePopover) {
|
||||
popover.hidePopover();
|
||||
}
|
||||
} else {
|
||||
popover.classList.remove('popover--show');
|
||||
popover.style.display = 'none';
|
||||
|
||||
// Remove click handler
|
||||
if (popover._clickHandler) {
|
||||
document.removeEventListener('click', popover._clickHandler);
|
||||
delete popover._clickHandler;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove from DOM
|
||||
if (popover.parentNode) {
|
||||
popover.parentNode.removeChild(popover);
|
||||
}
|
||||
|
||||
this.popovers.delete(componentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Position popover relative to anchor
|
||||
* @param {HTMLElement} popover - Popover element
|
||||
* @param {HTMLElement} anchor - Anchor element
|
||||
* @param {string} position - Position (top, bottom, left, right)
|
||||
* @param {number} offset - Offset in pixels
|
||||
*/
|
||||
positionPopover(popover, anchor, position, offset) {
|
||||
const anchorRect = anchor.getBoundingClientRect();
|
||||
const popoverRect = popover.getBoundingClientRect();
|
||||
const viewportWidth = window.innerWidth;
|
||||
const viewportHeight = window.innerHeight;
|
||||
|
||||
let top = 0;
|
||||
let left = 0;
|
||||
|
||||
switch (position) {
|
||||
case 'top':
|
||||
top = anchorRect.top - popoverRect.height - offset;
|
||||
left = anchorRect.left + (anchorRect.width / 2) - (popoverRect.width / 2);
|
||||
break;
|
||||
case 'bottom':
|
||||
top = anchorRect.bottom + offset;
|
||||
left = anchorRect.left + (anchorRect.width / 2) - (popoverRect.width / 2);
|
||||
break;
|
||||
case 'left':
|
||||
top = anchorRect.top + (anchorRect.height / 2) - (popoverRect.height / 2);
|
||||
left = anchorRect.left - popoverRect.width - offset;
|
||||
break;
|
||||
case 'right':
|
||||
top = anchorRect.top + (anchorRect.height / 2) - (popoverRect.height / 2);
|
||||
left = anchorRect.right + offset;
|
||||
break;
|
||||
case 'auto':
|
||||
// Auto-position: choose best position based on viewport
|
||||
const positions = ['bottom', 'top', 'right', 'left'];
|
||||
for (const pos of positions) {
|
||||
const testPos = this.calculatePosition(anchorRect, popoverRect, pos, offset);
|
||||
if (this.isPositionValid(testPos, popoverRect, viewportWidth, viewportHeight)) {
|
||||
position = pos;
|
||||
({ top, left } = testPos);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Ensure popover stays within viewport
|
||||
left = Math.max(8, Math.min(left, viewportWidth - popoverRect.width - 8));
|
||||
top = Math.max(8, Math.min(top, viewportHeight - popoverRect.height - 8));
|
||||
|
||||
popover.style.position = 'fixed';
|
||||
popover.style.top = `${top}px`;
|
||||
popover.style.left = `${left}px`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate position for a given direction
|
||||
*/
|
||||
calculatePosition(anchorRect, popoverRect, position, offset) {
|
||||
let top = 0;
|
||||
let left = 0;
|
||||
|
||||
switch (position) {
|
||||
case 'top':
|
||||
top = anchorRect.top - popoverRect.height - offset;
|
||||
left = anchorRect.left + (anchorRect.width / 2) - (popoverRect.width / 2);
|
||||
break;
|
||||
case 'bottom':
|
||||
top = anchorRect.bottom + offset;
|
||||
left = anchorRect.left + (anchorRect.width / 2) - (popoverRect.width / 2);
|
||||
break;
|
||||
case 'left':
|
||||
top = anchorRect.top + (anchorRect.height / 2) - (popoverRect.height / 2);
|
||||
left = anchorRect.left - popoverRect.width - offset;
|
||||
break;
|
||||
case 'right':
|
||||
top = anchorRect.top + (anchorRect.height / 2) - (popoverRect.height / 2);
|
||||
left = anchorRect.right + offset;
|
||||
break;
|
||||
}
|
||||
|
||||
return { top, left };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if position is valid (within viewport)
|
||||
*/
|
||||
isPositionValid({ top, left }, popoverRect, viewportWidth, viewportHeight) {
|
||||
return top >= 0 &&
|
||||
left >= 0 &&
|
||||
top + popoverRect.height <= viewportHeight &&
|
||||
left + popoverRect.width <= viewportWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup repositioning on scroll/resize
|
||||
*/
|
||||
setupRepositioning(popover, anchor, position, offset) {
|
||||
const reposition = () => {
|
||||
if (this.popovers.has(popover.id.replace('popover-', ''))) {
|
||||
this.positionPopover(popover, anchor, position, offset);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('scroll', reposition, { passive: true });
|
||||
window.addEventListener('resize', reposition);
|
||||
|
||||
popover._repositionHandlers = {
|
||||
scroll: reposition,
|
||||
resize: reposition
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup global handlers for fallback mode
|
||||
*/
|
||||
setupGlobalHandlers() {
|
||||
// Global handlers are set up per-popover in showWithFallback
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup all popovers
|
||||
*/
|
||||
destroy() {
|
||||
for (const componentId of this.popovers.keys()) {
|
||||
this.hide(componentId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
347
resources/js/modules/livecomponent/ProgressiveEnhancement.js
Normal file
347
resources/js/modules/livecomponent/ProgressiveEnhancement.js
Normal file
@@ -0,0 +1,347 @@
|
||||
/**
|
||||
* Progressive Enhancement for LiveComponents
|
||||
*
|
||||
* Provides automatic AJAX handling for links and forms within data-lc-boost containers.
|
||||
* Falls back gracefully to normal navigation/submit when JavaScript is disabled.
|
||||
*
|
||||
* Features:
|
||||
* - Automatic AJAX for links and forms
|
||||
* - Graceful degradation (works without JS)
|
||||
* - Integration with LiveComponents system
|
||||
* - SPA Router coordination (if available)
|
||||
*/
|
||||
|
||||
export class ProgressiveEnhancement {
|
||||
constructor(liveComponentManager) {
|
||||
this.liveComponentManager = liveComponentManager;
|
||||
this.boostContainers = new Set();
|
||||
this.initialized = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize progressive enhancement
|
||||
*
|
||||
* Sets up event listeners for boost containers and their links/forms.
|
||||
*/
|
||||
init() {
|
||||
if (this.initialized) {
|
||||
console.warn('[ProgressiveEnhancement] Already initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
// Find all boost containers
|
||||
this.findBoostContainers();
|
||||
|
||||
// Setup mutation observer to handle dynamically added boost containers
|
||||
this.setupMutationObserver();
|
||||
|
||||
// Setup global click handler for links
|
||||
document.addEventListener('click', (e) => this.handleLinkClick(e), true);
|
||||
|
||||
// Setup global submit handler for forms
|
||||
document.addEventListener('submit', (e) => this.handleFormSubmit(e), true);
|
||||
|
||||
this.initialized = true;
|
||||
console.log('[ProgressiveEnhancement] Initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all boost containers and setup handlers
|
||||
*/
|
||||
findBoostContainers() {
|
||||
const containers = document.querySelectorAll('[data-lc-boost="true"]');
|
||||
containers.forEach(container => {
|
||||
this.setupBoostContainer(container);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup boost container
|
||||
*
|
||||
* @param {HTMLElement} container - Boost container element
|
||||
*/
|
||||
setupBoostContainer(container) {
|
||||
if (this.boostContainers.has(container)) {
|
||||
return; // Already setup
|
||||
}
|
||||
|
||||
this.boostContainers.add(container);
|
||||
|
||||
// Mark links and forms as boosted (for identification)
|
||||
container.querySelectorAll('a[href], form[action]').forEach(element => {
|
||||
if (!element.hasAttribute('data-lc-boost')) {
|
||||
element.setAttribute('data-lc-boost', 'true');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup mutation observer to detect new boost containers
|
||||
*/
|
||||
setupMutationObserver() {
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
mutations.forEach((mutation) => {
|
||||
mutation.addedNodes.forEach((node) => {
|
||||
if (node.nodeType === Node.ELEMENT_NODE) {
|
||||
// Check if node itself is a boost container
|
||||
if (node.hasAttribute && node.hasAttribute('data-lc-boost') &&
|
||||
node.getAttribute('data-lc-boost') === 'true') {
|
||||
this.setupBoostContainer(node);
|
||||
}
|
||||
|
||||
// Check for boost containers within added node
|
||||
const boostContainers = node.querySelectorAll?.('[data-lc-boost="true"]');
|
||||
if (boostContainers) {
|
||||
boostContainers.forEach(container => {
|
||||
this.setupBoostContainer(container);
|
||||
});
|
||||
}
|
||||
|
||||
// Check for links/forms within boost containers
|
||||
const links = node.querySelectorAll?.('a[href], form[action]');
|
||||
if (links) {
|
||||
links.forEach(element => {
|
||||
const boostContainer = element.closest('[data-lc-boost="true"]');
|
||||
if (boostContainer && !element.hasAttribute('data-lc-boost')) {
|
||||
element.setAttribute('data-lc-boost', 'true');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
observer.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle link clicks
|
||||
*
|
||||
* @param {Event} event - Click event
|
||||
*/
|
||||
handleLinkClick(event) {
|
||||
const link = event.target.closest('a[href]');
|
||||
if (!link) return;
|
||||
|
||||
// Check if link is in a boost container
|
||||
const boostContainer = link.closest('[data-lc-boost="true"]');
|
||||
if (!boostContainer) return;
|
||||
|
||||
// Check if link explicitly opts out
|
||||
if (link.hasAttribute('data-lc-boost') && link.getAttribute('data-lc-boost') === 'false') {
|
||||
return; // Let normal navigation happen
|
||||
}
|
||||
|
||||
// Check for special link types that should not be boosted
|
||||
const href = link.getAttribute('href');
|
||||
if (!href || href === '#' || href.startsWith('javascript:') || href.startsWith('mailto:') || href.startsWith('tel:')) {
|
||||
return; // Let normal behavior happen
|
||||
}
|
||||
|
||||
// Check if target is _blank (new window)
|
||||
if (link.getAttribute('target') === '_blank') {
|
||||
return; // Let normal behavior happen
|
||||
}
|
||||
|
||||
// Prevent default navigation
|
||||
event.preventDefault();
|
||||
|
||||
// Try to use SPA Router if available
|
||||
if (window.SPARouter && typeof window.SPARouter.navigate === 'function') {
|
||||
window.SPARouter.navigate(href);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback: Use fetch to load content
|
||||
this.loadContentViaAjax(href, link);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle form submissions
|
||||
*
|
||||
* @param {Event} event - Submit event
|
||||
*/
|
||||
handleFormSubmit(event) {
|
||||
const form = event.target;
|
||||
if (!form || form.tagName !== 'FORM') return;
|
||||
|
||||
// Check if form is in a boost container
|
||||
const boostContainer = form.closest('[data-lc-boost="true"]');
|
||||
if (!boostContainer) return;
|
||||
|
||||
// Check if form explicitly opts out
|
||||
if (form.hasAttribute('data-lc-boost') && form.getAttribute('data-lc-boost') === 'false') {
|
||||
return; // Let normal submit happen
|
||||
}
|
||||
|
||||
// Check if form has data-live-action (handled by LiveComponents)
|
||||
if (form.hasAttribute('data-live-action')) {
|
||||
return; // Let LiveComponents handle it
|
||||
}
|
||||
|
||||
// Prevent default submission
|
||||
event.preventDefault();
|
||||
|
||||
// Submit form via AJAX
|
||||
this.submitFormViaAjax(form);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load content via AJAX
|
||||
*
|
||||
* @param {string} url - URL to load
|
||||
* @param {HTMLElement} link - Link element that triggered the load
|
||||
*/
|
||||
async loadContentViaAjax(url, link) {
|
||||
try {
|
||||
// Show loading state
|
||||
link.setAttribute('aria-busy', 'true');
|
||||
link.classList.add('lc-loading');
|
||||
|
||||
// Fetch content
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Accept': 'text/html'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
|
||||
// Try to extract main content (look for <main> tag)
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, 'text/html');
|
||||
const mainContent = doc.querySelector('main') || doc.body;
|
||||
|
||||
// Update page content
|
||||
const currentMain = document.querySelector('main') || document.body;
|
||||
if (currentMain) {
|
||||
currentMain.innerHTML = mainContent.innerHTML;
|
||||
} else {
|
||||
document.body.innerHTML = mainContent.innerHTML;
|
||||
}
|
||||
|
||||
// Update URL without reload
|
||||
window.history.pushState({}, '', url);
|
||||
|
||||
// Reinitialize LiveComponents
|
||||
if (this.liveComponentManager) {
|
||||
const components = document.querySelectorAll('[data-live-component]');
|
||||
components.forEach(component => {
|
||||
this.liveComponentManager.init(component);
|
||||
});
|
||||
}
|
||||
|
||||
// Dispatch custom event
|
||||
window.dispatchEvent(new CustomEvent('lc:boost:navigated', {
|
||||
detail: { url, link }
|
||||
}));
|
||||
|
||||
} catch (error) {
|
||||
console.error('[ProgressiveEnhancement] Failed to load content:', error);
|
||||
|
||||
// Fallback to normal navigation on error
|
||||
window.location.href = url;
|
||||
} finally {
|
||||
// Remove loading state
|
||||
link.removeAttribute('aria-busy');
|
||||
link.classList.remove('lc-loading');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit form via AJAX
|
||||
*
|
||||
* @param {HTMLFormElement} form - Form element
|
||||
*/
|
||||
async submitFormViaAjax(form) {
|
||||
try {
|
||||
// Show loading state
|
||||
form.setAttribute('aria-busy', 'true');
|
||||
form.classList.add('lc-loading');
|
||||
|
||||
const formData = new FormData(form);
|
||||
const method = form.method.toUpperCase() || 'POST';
|
||||
const action = form.action || window.location.href;
|
||||
|
||||
// Fetch response
|
||||
const response = await fetch(action, {
|
||||
method: method,
|
||||
body: formData,
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Accept': 'text/html'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
|
||||
// Check if response is a redirect
|
||||
if (response.redirected) {
|
||||
// Follow redirect
|
||||
await this.loadContentViaAjax(response.url, form);
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to extract main content
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, 'text/html');
|
||||
const mainContent = doc.querySelector('main') || doc.body;
|
||||
|
||||
// Update page content
|
||||
const currentMain = document.querySelector('main') || document.body;
|
||||
if (currentMain) {
|
||||
currentMain.innerHTML = mainContent.innerHTML;
|
||||
} else {
|
||||
document.body.innerHTML = mainContent.innerHTML;
|
||||
}
|
||||
|
||||
// Update URL if form has action
|
||||
if (form.action && form.action !== window.location.href) {
|
||||
window.history.pushState({}, '', form.action);
|
||||
}
|
||||
|
||||
// Reinitialize LiveComponents
|
||||
if (this.liveComponentManager) {
|
||||
const components = document.querySelectorAll('[data-live-component]');
|
||||
components.forEach(component => {
|
||||
this.liveComponentManager.init(component);
|
||||
});
|
||||
}
|
||||
|
||||
// Dispatch custom event
|
||||
window.dispatchEvent(new CustomEvent('lc:boost:submitted', {
|
||||
detail: { form, action }
|
||||
}));
|
||||
|
||||
} catch (error) {
|
||||
console.error('[ProgressiveEnhancement] Failed to submit form:', error);
|
||||
|
||||
// Fallback to normal submit on error
|
||||
form.submit();
|
||||
} finally {
|
||||
// Remove loading state
|
||||
form.removeAttribute('aria-busy');
|
||||
form.classList.remove('lc-loading');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default ProgressiveEnhancement;
|
||||
|
||||
|
||||
|
||||
|
||||
288
resources/js/modules/livecomponent/ToastQueue.js
Normal file
288
resources/js/modules/livecomponent/ToastQueue.js
Normal file
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
* Toast Queue Manager
|
||||
*
|
||||
* Manages multiple toast notifications with:
|
||||
* - Queue system for multiple toasts
|
||||
* - Position management (stacking toasts)
|
||||
* - Auto-dismiss with queue management
|
||||
* - Maximum number of simultaneous toasts
|
||||
*/
|
||||
|
||||
export class ToastQueue {
|
||||
constructor(maxToasts = 5) {
|
||||
this.maxToasts = maxToasts;
|
||||
this.queue = [];
|
||||
this.activeToasts = new Map(); // componentId → toast element
|
||||
this.positionOffsets = new Map(); // position → current offset
|
||||
}
|
||||
|
||||
/**
|
||||
* Add toast to queue
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {Object} options - Toast options
|
||||
* @returns {HTMLElement|null} Toast element or null if queue full
|
||||
*/
|
||||
add(componentId, options = {}) {
|
||||
const {
|
||||
message = '',
|
||||
type = 'info',
|
||||
duration = 5000,
|
||||
position = 'top-right'
|
||||
} = options;
|
||||
|
||||
// Check if we already have a toast for this component
|
||||
if (this.activeToasts.has(componentId)) {
|
||||
// Replace existing toast
|
||||
this.remove(componentId);
|
||||
}
|
||||
|
||||
// Check if we've reached max toasts for this position
|
||||
const positionCount = this.getPositionCount(position);
|
||||
if (positionCount >= this.maxToasts) {
|
||||
// Remove oldest toast at this position
|
||||
this.removeOldestAtPosition(position);
|
||||
}
|
||||
|
||||
// Create toast element
|
||||
const toast = this.createToastElement(message, type, position, componentId);
|
||||
|
||||
// Calculate offset for stacking
|
||||
const offset = this.getNextOffset(position);
|
||||
this.setToastPosition(toast, position, offset);
|
||||
|
||||
// Add to DOM
|
||||
document.body.appendChild(toast);
|
||||
|
||||
// Animate in
|
||||
requestAnimationFrame(() => {
|
||||
toast.style.opacity = '1';
|
||||
toast.style.transform = 'translateY(0)';
|
||||
});
|
||||
|
||||
// Store reference
|
||||
this.activeToasts.set(componentId, toast);
|
||||
this.updatePositionOffset(position, offset);
|
||||
|
||||
// Setup auto-dismiss
|
||||
if (duration > 0) {
|
||||
setTimeout(() => {
|
||||
this.remove(componentId);
|
||||
}, duration);
|
||||
}
|
||||
|
||||
// Setup close button
|
||||
const closeBtn = toast.querySelector('.toast-close');
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', () => {
|
||||
this.remove(componentId);
|
||||
});
|
||||
}
|
||||
|
||||
return toast;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove toast
|
||||
* @param {string} componentId - Component ID
|
||||
*/
|
||||
remove(componentId) {
|
||||
const toast = this.activeToasts.get(componentId);
|
||||
if (!toast) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Animate out
|
||||
toast.style.opacity = '0';
|
||||
const position = this.getToastPosition(toast);
|
||||
toast.style.transform = `translateY(${position.includes('top') ? '-20px' : '20px'})`;
|
||||
|
||||
setTimeout(() => {
|
||||
if (toast.parentNode) {
|
||||
toast.parentNode.removeChild(toast);
|
||||
}
|
||||
this.activeToasts.delete(componentId);
|
||||
this.recalculateOffsets(position);
|
||||
}, 300);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all toasts
|
||||
*/
|
||||
clear() {
|
||||
for (const componentId of this.activeToasts.keys()) {
|
||||
this.remove(componentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove oldest toast at position
|
||||
* @param {string} position - Position
|
||||
*/
|
||||
removeOldestAtPosition(position) {
|
||||
let oldestToast = null;
|
||||
let oldestComponentId = null;
|
||||
let oldestTimestamp = Infinity;
|
||||
|
||||
for (const [componentId, toast] of this.activeToasts.entries()) {
|
||||
if (this.getToastPosition(toast) === position) {
|
||||
const timestamp = parseInt(toast.dataset.timestamp || '0');
|
||||
if (timestamp < oldestTimestamp) {
|
||||
oldestTimestamp = timestamp;
|
||||
oldestToast = toast;
|
||||
oldestComponentId = componentId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (oldestComponentId) {
|
||||
this.remove(oldestComponentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get count of toasts at position
|
||||
* @param {string} position - Position
|
||||
* @returns {number}
|
||||
*/
|
||||
getPositionCount(position) {
|
||||
let count = 0;
|
||||
for (const toast of this.activeToasts.values()) {
|
||||
if (this.getToastPosition(toast) === position) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get next offset for position
|
||||
* @param {string} position - Position
|
||||
* @returns {number}
|
||||
*/
|
||||
getNextOffset(position) {
|
||||
const currentOffset = this.positionOffsets.get(position) || 0;
|
||||
return currentOffset + 80; // 80px spacing between toasts
|
||||
}
|
||||
|
||||
/**
|
||||
* Update position offset
|
||||
* @param {string} position - Position
|
||||
* @param {number} offset - Offset value
|
||||
*/
|
||||
updatePositionOffset(position, offset) {
|
||||
this.positionOffsets.set(position, offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recalculate offsets for position after removal
|
||||
* @param {string} position - Position
|
||||
*/
|
||||
recalculateOffsets(position) {
|
||||
const toastsAtPosition = [];
|
||||
for (const [componentId, toast] of this.activeToasts.entries()) {
|
||||
if (this.getToastPosition(toast) === position) {
|
||||
toastsAtPosition.push({ componentId, toast });
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by DOM order
|
||||
toastsAtPosition.sort((a, b) => {
|
||||
const positionA = a.toast.compareDocumentPosition(b.toast);
|
||||
return positionA & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
|
||||
});
|
||||
|
||||
// Recalculate offsets
|
||||
let offset = 0;
|
||||
for (const { toast } of toastsAtPosition) {
|
||||
this.setToastPosition(toast, position, offset);
|
||||
offset += 80;
|
||||
}
|
||||
|
||||
this.positionOffsets.set(position, offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create toast element
|
||||
* @param {string} message - Toast message
|
||||
* @param {string} type - Toast type
|
||||
* @param {string} position - Position
|
||||
* @param {string} componentId - Component ID
|
||||
* @returns {HTMLElement}
|
||||
*/
|
||||
createToastElement(message, type, position, componentId) {
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast-queue-toast toast-queue-toast--${type} toast-queue-toast--${position}`;
|
||||
toast.setAttribute('role', 'alert');
|
||||
toast.setAttribute('aria-live', 'polite');
|
||||
toast.dataset.componentId = componentId;
|
||||
toast.dataset.timestamp = Date.now().toString();
|
||||
|
||||
const colors = {
|
||||
info: '#3b82f6',
|
||||
success: '#10b981',
|
||||
warning: '#f59e0b',
|
||||
error: '#ef4444'
|
||||
};
|
||||
|
||||
toast.innerHTML = `
|
||||
<div class="toast-content">
|
||||
<span class="toast-message">${message}</span>
|
||||
<button class="toast-close" aria-label="Close">×</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
toast.style.cssText = `
|
||||
position: fixed;
|
||||
${position.includes('top') ? 'top' : 'bottom'}: 1rem;
|
||||
${position.includes('left') ? 'left' : 'right'}: 1rem;
|
||||
max-width: 400px;
|
||||
padding: 1rem;
|
||||
background: ${colors[type] || colors.info};
|
||||
color: white;
|
||||
border-radius: 0.5rem;
|
||||
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
|
||||
z-index: 10000;
|
||||
opacity: 0;
|
||||
transform: translateY(${position.includes('top') ? '-20px' : '20px'});
|
||||
transition: opacity 0.3s ease, transform 0.3s ease;
|
||||
`;
|
||||
|
||||
return toast;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set toast position with offset
|
||||
* @param {HTMLElement} toast - Toast element
|
||||
* @param {string} position - Position
|
||||
* @param {number} offset - Offset in pixels
|
||||
*/
|
||||
setToastPosition(toast, position, offset) {
|
||||
if (position.includes('top')) {
|
||||
toast.style.top = `${1 + offset / 16}rem`; // Convert px to rem (assuming 16px base)
|
||||
} else {
|
||||
toast.style.bottom = `${1 + offset / 16}rem`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get toast position from element
|
||||
* @param {HTMLElement} toast - Toast element
|
||||
* @returns {string}
|
||||
*/
|
||||
getToastPosition(toast) {
|
||||
if (toast.classList.contains('toast-queue-toast--top-right')) {
|
||||
return 'top-right';
|
||||
}
|
||||
if (toast.classList.contains('toast-queue-toast--top-left')) {
|
||||
return 'top-left';
|
||||
}
|
||||
if (toast.classList.contains('toast-queue-toast--bottom-right')) {
|
||||
return 'bottom-right';
|
||||
}
|
||||
if (toast.classList.contains('toast-queue-toast--bottom-left')) {
|
||||
return 'bottom-left';
|
||||
}
|
||||
return 'top-right'; // default
|
||||
}
|
||||
}
|
||||
|
||||
299
resources/js/modules/livecomponent/TriggerManager.js
Normal file
299
resources/js/modules/livecomponent/TriggerManager.js
Normal file
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* Trigger Manager for LiveComponents
|
||||
*
|
||||
* Handles advanced trigger options:
|
||||
* - delay: Delay before execution
|
||||
* - throttle: Throttle instead of debounce
|
||||
* - once: Execute only once
|
||||
* - changed: Only execute on value change
|
||||
* - from: Event from another element
|
||||
* - load: Execute on element load
|
||||
*/
|
||||
|
||||
export class TriggerManager {
|
||||
constructor() {
|
||||
this.triggeredOnce = new Set(); // Track elements that have triggered once
|
||||
this.throttleTimers = new Map(); // Track throttle timers
|
||||
this.lastValues = new Map(); // Track last values for 'changed' trigger
|
||||
this.loadHandled = new Set(); // Track elements that have handled load event
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup trigger for an element
|
||||
*
|
||||
* @param {HTMLElement} element - Element to setup trigger for
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {string} action - Action name
|
||||
* @param {Function} handler - Action handler function
|
||||
* @param {string} defaultEvent - Default event type (click, input, change, etc.)
|
||||
*/
|
||||
setupTrigger(element, componentId, action, handler, defaultEvent = 'click') {
|
||||
// Parse trigger options
|
||||
const delay = this.parseDelay(element.dataset.lcTriggerDelay);
|
||||
const throttle = this.parseThrottle(element.dataset.lcTriggerThrottle);
|
||||
const once = element.dataset.lcTriggerOnce === 'true';
|
||||
const changed = element.dataset.lcTriggerChanged === 'true';
|
||||
const from = element.dataset.lcTriggerFrom;
|
||||
const load = element.dataset.lcTriggerLoad === 'true';
|
||||
|
||||
// Handle 'once' trigger - check if already triggered
|
||||
if (once) {
|
||||
const triggerKey = `${componentId}_${action}_${this.getElementKey(element)}`;
|
||||
if (this.triggeredOnce.has(triggerKey)) {
|
||||
return; // Already triggered, don't setup again
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 'load' trigger
|
||||
if (load) {
|
||||
const loadKey = `${componentId}_${action}_${this.getElementKey(element)}`;
|
||||
if (!this.loadHandled.has(loadKey)) {
|
||||
this.loadHandled.add(loadKey);
|
||||
// Execute immediately if element is already loaded
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
this.executeWithOptions(element, componentId, action, handler, delay, throttle, changed);
|
||||
} else {
|
||||
// Wait for load
|
||||
window.addEventListener('load', () => {
|
||||
this.executeWithOptions(element, componentId, action, handler, delay, throttle, changed);
|
||||
}, { once: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 'from' trigger - delegate event from another element
|
||||
if (from) {
|
||||
const sourceElement = document.querySelector(from);
|
||||
if (sourceElement) {
|
||||
this.setupDelegatedTrigger(sourceElement, element, componentId, action, handler, defaultEvent, delay, throttle, changed);
|
||||
return; // Don't setup direct trigger
|
||||
} else {
|
||||
console.warn(`[TriggerManager] Source element not found for trigger-from: ${from}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Setup direct trigger
|
||||
const eventType = this.getEventType(element, defaultEvent);
|
||||
const wrappedHandler = (e) => {
|
||||
// Check 'once' trigger
|
||||
if (once) {
|
||||
const triggerKey = `${componentId}_${action}_${this.getElementKey(element)}`;
|
||||
if (this.triggeredOnce.has(triggerKey)) {
|
||||
return; // Already triggered
|
||||
}
|
||||
this.triggeredOnce.add(triggerKey);
|
||||
}
|
||||
|
||||
this.executeWithOptions(element, componentId, action, handler, delay, throttle, changed, e);
|
||||
};
|
||||
|
||||
element.addEventListener(eventType, wrappedHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup delegated trigger (trigger-from)
|
||||
*
|
||||
* @param {HTMLElement} sourceElement - Element that triggers the event
|
||||
* @param {HTMLElement} targetElement - Element that receives the action
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {string} action - Action name
|
||||
* @param {Function} handler - Action handler
|
||||
* @param {string} eventType - Event type
|
||||
* @param {number} delay - Delay in ms
|
||||
* @param {number} throttle - Throttle in ms
|
||||
* @param {boolean} changed - Only on value change
|
||||
*/
|
||||
setupDelegatedTrigger(sourceElement, targetElement, componentId, action, handler, eventType, delay, throttle, changed) {
|
||||
const wrappedHandler = (e) => {
|
||||
this.executeWithOptions(targetElement, componentId, action, handler, delay, throttle, changed, e);
|
||||
};
|
||||
|
||||
sourceElement.addEventListener(eventType, wrappedHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute handler with trigger options
|
||||
*
|
||||
* @param {HTMLElement} element - Element
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {string} action - Action name
|
||||
* @param {Function} handler - Handler function
|
||||
* @param {number} delay - Delay in ms
|
||||
* @param {number} throttle - Throttle in ms
|
||||
* @param {boolean} changed - Only on value change
|
||||
* @param {Event} event - Original event
|
||||
*/
|
||||
executeWithOptions(element, componentId, action, handler, delay, throttle, changed, event) {
|
||||
// Check 'changed' trigger
|
||||
if (changed) {
|
||||
const currentValue = this.getElementValue(element);
|
||||
const valueKey = `${componentId}_${action}_${this.getElementKey(element)}`;
|
||||
const lastValue = this.lastValues.get(valueKey);
|
||||
|
||||
if (currentValue === lastValue) {
|
||||
return; // Value hasn't changed
|
||||
}
|
||||
|
||||
this.lastValues.set(valueKey, currentValue);
|
||||
}
|
||||
|
||||
// Apply throttle
|
||||
if (throttle > 0) {
|
||||
const throttleKey = `${componentId}_${action}_${this.getElementKey(element)}`;
|
||||
const lastExecution = this.throttleTimers.get(throttleKey);
|
||||
|
||||
if (lastExecution && Date.now() - lastExecution < throttle) {
|
||||
return; // Throttled
|
||||
}
|
||||
|
||||
this.throttleTimers.set(throttleKey, Date.now());
|
||||
}
|
||||
|
||||
// Apply delay
|
||||
if (delay > 0) {
|
||||
setTimeout(() => {
|
||||
handler(event);
|
||||
}, delay);
|
||||
} else {
|
||||
handler(event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse delay value (e.g., "500ms", "1s", "500")
|
||||
*
|
||||
* @param {string} delayStr - Delay string
|
||||
* @returns {number} - Delay in milliseconds
|
||||
*/
|
||||
parseDelay(delayStr) {
|
||||
if (!delayStr) return 0;
|
||||
|
||||
const match = delayStr.match(/^(\d+)(ms|s)?$/);
|
||||
if (!match) return 0;
|
||||
|
||||
const value = parseInt(match[1]);
|
||||
const unit = match[2] || 'ms';
|
||||
|
||||
return unit === 's' ? value * 1000 : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse throttle value (e.g., "100ms", "1s", "100")
|
||||
*
|
||||
* @param {string} throttleStr - Throttle string
|
||||
* @returns {number} - Throttle in milliseconds
|
||||
*/
|
||||
parseThrottle(throttleStr) {
|
||||
if (!throttleStr) return 0;
|
||||
|
||||
const match = throttleStr.match(/^(\d+)(ms|s)?$/);
|
||||
if (!match) return 0;
|
||||
|
||||
const value = parseInt(match[1]);
|
||||
const unit = match[2] || 'ms';
|
||||
|
||||
return unit === 's' ? value * 1000 : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get event type for element
|
||||
*
|
||||
* @param {HTMLElement} element - Element
|
||||
* @param {string} defaultEvent - Default event type
|
||||
* @returns {string} - Event type
|
||||
*/
|
||||
getEventType(element, defaultEvent) {
|
||||
// For form elements, use appropriate event
|
||||
if (element.tagName === 'FORM') {
|
||||
return 'submit';
|
||||
}
|
||||
if (element.tagName === 'SELECT') {
|
||||
return 'change';
|
||||
}
|
||||
if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
|
||||
return element.type === 'checkbox' || element.type === 'radio' ? 'change' : 'input';
|
||||
}
|
||||
|
||||
return defaultEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get element value for 'changed' trigger
|
||||
*
|
||||
* @param {HTMLElement} element - Element
|
||||
* @returns {string} - Element value
|
||||
*/
|
||||
getElementValue(element) {
|
||||
if (element.tagName === 'INPUT') {
|
||||
if (element.type === 'checkbox' || element.type === 'radio') {
|
||||
return element.checked ? 'true' : 'false';
|
||||
}
|
||||
return element.value || '';
|
||||
}
|
||||
if (element.tagName === 'TEXTAREA' || element.tagName === 'SELECT') {
|
||||
return element.value || '';
|
||||
}
|
||||
return element.textContent || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get unique key for element (for tracking)
|
||||
*
|
||||
* @param {HTMLElement} element - Element
|
||||
* @returns {string} - Unique key
|
||||
*/
|
||||
getElementKey(element) {
|
||||
return element.id || element.name || `${element.tagName}_${element.className}` || 'unknown';
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up resources for component
|
||||
*
|
||||
* @param {string} componentId - Component ID
|
||||
*/
|
||||
cleanup(componentId) {
|
||||
// Remove all entries for this component
|
||||
const keysToRemove = [];
|
||||
for (const key of this.triggeredOnce) {
|
||||
if (key.startsWith(`${componentId}_`)) {
|
||||
keysToRemove.push(key);
|
||||
}
|
||||
}
|
||||
keysToRemove.forEach(key => this.triggeredOnce.delete(key));
|
||||
|
||||
// Clean throttle timers
|
||||
const timersToRemove = [];
|
||||
for (const key of this.throttleTimers.keys()) {
|
||||
if (key.startsWith(`${componentId}_`)) {
|
||||
timersToRemove.push(key);
|
||||
}
|
||||
}
|
||||
timersToRemove.forEach(key => this.throttleTimers.delete(key));
|
||||
|
||||
// Clean last values
|
||||
const valuesToRemove = [];
|
||||
for (const key of this.lastValues.keys()) {
|
||||
if (key.startsWith(`${componentId}_`)) {
|
||||
valuesToRemove.push(key);
|
||||
}
|
||||
}
|
||||
valuesToRemove.forEach(key => this.lastValues.delete(key));
|
||||
|
||||
// Clean load handled
|
||||
const loadToRemove = [];
|
||||
for (const key of this.loadHandled) {
|
||||
if (key.startsWith(`${componentId}_`)) {
|
||||
loadToRemove.push(key);
|
||||
}
|
||||
}
|
||||
loadToRemove.forEach(key => this.loadHandled.delete(key));
|
||||
}
|
||||
}
|
||||
|
||||
// Create singleton instance
|
||||
export const triggerManager = new TriggerManager();
|
||||
export default triggerManager;
|
||||
|
||||
|
||||
|
||||
|
||||
529
resources/js/modules/livecomponent/UIEventHandler.js
Normal file
529
resources/js/modules/livecomponent/UIEventHandler.js
Normal file
@@ -0,0 +1,529 @@
|
||||
/**
|
||||
* UI Event Handler for LiveComponents
|
||||
*
|
||||
* Listens to UI-related events from LiveComponents and automatically
|
||||
* displays Toasts, Modals, and other UI components.
|
||||
*
|
||||
* Supported Events:
|
||||
* - toast:show - Show toast notification
|
||||
* - toast:hide - Hide toast notification
|
||||
* - modal:show - Show modal dialog
|
||||
* - modal:close - Close modal dialog
|
||||
* - modal:confirm - Show confirmation dialog
|
||||
* - modal:alert - Show alert dialog
|
||||
*/
|
||||
|
||||
import { LiveComponentUIHelper } from './LiveComponentUIHelper.js';
|
||||
|
||||
export class UIEventHandler {
|
||||
constructor(liveComponentManager) {
|
||||
this.manager = liveComponentManager;
|
||||
this.uiHelper = liveComponentManager.uiHelper || new LiveComponentUIHelper(liveComponentManager);
|
||||
this.eventListeners = new Map();
|
||||
this.isInitialized = false;
|
||||
this.drawerManager = null; // Lazy-loaded when needed
|
||||
this.popoverManager = null; // Lazy-loaded when needed
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize event listeners
|
||||
*/
|
||||
init() {
|
||||
if (this.isInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Toast events
|
||||
this.addEventListener('toast:show', (e) => this.handleToastShow(e));
|
||||
this.addEventListener('toast:hide', (e) => this.handleToastHide(e));
|
||||
|
||||
// Modal events
|
||||
this.addEventListener('modal:show', (e) => this.handleModalShow(e));
|
||||
this.addEventListener('modal:close', (e) => this.handleModalClose(e));
|
||||
this.addEventListener('modal:confirm', (e) => this.handleModalConfirm(e));
|
||||
this.addEventListener('modal:alert', (e) => this.handleModalAlert(e));
|
||||
|
||||
// Also listen to livecomponent: prefixed events for compatibility
|
||||
this.addEventListener('livecomponent:toast:show', (e) => this.handleToastShow(e));
|
||||
this.addEventListener('livecomponent:toast:hide', (e) => this.handleToastHide(e));
|
||||
this.addEventListener('livecomponent:modal:show', (e) => this.handleModalShow(e));
|
||||
this.addEventListener('livecomponent:modal:close', (e) => this.handleModalClose(e));
|
||||
this.addEventListener('livecomponent:modal:confirm', (e) => this.handleModalConfirm(e));
|
||||
this.addEventListener('livecomponent:modal:alert', (e) => this.handleModalAlert(e));
|
||||
|
||||
// Drawer events
|
||||
this.addEventListener('drawer:open', (e) => this.handleDrawerOpen(e));
|
||||
this.addEventListener('drawer:close', (e) => this.handleDrawerClose(e));
|
||||
this.addEventListener('drawer:toggle', (e) => this.handleDrawerToggle(e));
|
||||
this.addEventListener('livecomponent:drawer:open', (e) => this.handleDrawerOpen(e));
|
||||
this.addEventListener('livecomponent:drawer:close', (e) => this.handleDrawerClose(e));
|
||||
this.addEventListener('livecomponent:drawer:toggle', (e) => this.handleDrawerToggle(e));
|
||||
|
||||
// Popover events
|
||||
this.addEventListener('popover:show', (e) => this.handlePopoverShow(e));
|
||||
this.addEventListener('popover:hide', (e) => this.handlePopoverHide(e));
|
||||
this.addEventListener('popover:toggle', (e) => this.handlePopoverToggle(e));
|
||||
this.addEventListener('livecomponent:popover:show', (e) => this.handlePopoverShow(e));
|
||||
this.addEventListener('livecomponent:popover:hide', (e) => this.handlePopoverHide(e));
|
||||
this.addEventListener('livecomponent:popover:toggle', (e) => this.handlePopoverToggle(e));
|
||||
|
||||
this.isInitialized = true;
|
||||
console.log('[UIEventHandler] Initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Add event listener
|
||||
* @param {string} eventName - Event name
|
||||
* @param {Function} handler - Event handler
|
||||
*/
|
||||
addEventListener(eventName, handler) {
|
||||
const wrappedHandler = (e) => {
|
||||
try {
|
||||
handler(e);
|
||||
} catch (error) {
|
||||
console.error(`[UIEventHandler] Error handling event ${eventName}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener(eventName, wrappedHandler);
|
||||
this.eventListeners.set(eventName, wrappedHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove event listener
|
||||
* @param {string} eventName - Event name
|
||||
*/
|
||||
removeEventListener(eventName) {
|
||||
const handler = this.eventListeners.get(eventName);
|
||||
if (handler) {
|
||||
document.removeEventListener(eventName, handler);
|
||||
this.eventListeners.delete(eventName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle toast:show event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
handleToastShow(e) {
|
||||
const payload = e.detail || {};
|
||||
const {
|
||||
message = '',
|
||||
type = 'info',
|
||||
duration = 5000,
|
||||
position = 'top-right',
|
||||
componentId = 'global'
|
||||
} = payload;
|
||||
|
||||
if (!message) {
|
||||
console.warn('[UIEventHandler] toast:show event missing message');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Showing toast: ${message} (${type})`);
|
||||
|
||||
this.uiHelper.showNotification(componentId, {
|
||||
message: message,
|
||||
type: type,
|
||||
duration: duration,
|
||||
position: position
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle toast:hide event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
handleToastHide(e) {
|
||||
const payload = e.detail || {};
|
||||
const { componentId = 'global' } = payload;
|
||||
|
||||
console.log(`[UIEventHandler] Hiding toast for component: ${componentId}`);
|
||||
|
||||
this.uiHelper.hideNotification(componentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle modal:show event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
handleModalShow(e) {
|
||||
const payload = e.detail || {};
|
||||
const {
|
||||
componentId,
|
||||
title = '',
|
||||
content = '',
|
||||
size = 'medium',
|
||||
buttons = [],
|
||||
closeOnBackdrop = true,
|
||||
closeOnEscape = true,
|
||||
onClose = null,
|
||||
onConfirm = null
|
||||
} = payload;
|
||||
|
||||
if (!componentId) {
|
||||
console.warn('[UIEventHandler] modal:show event missing componentId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Showing modal for component: ${componentId}`);
|
||||
|
||||
this.uiHelper.showDialog(componentId, {
|
||||
title: title,
|
||||
content: content,
|
||||
size: size,
|
||||
buttons: buttons,
|
||||
closeOnBackdrop: closeOnBackdrop,
|
||||
closeOnEscape: closeOnEscape,
|
||||
onClose: onClose,
|
||||
onConfirm: onConfirm
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle modal:close event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
handleModalClose(e) {
|
||||
const payload = e.detail || {};
|
||||
const { componentId } = payload;
|
||||
|
||||
if (!componentId) {
|
||||
console.warn('[UIEventHandler] modal:close event missing componentId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Closing modal for component: ${componentId}`);
|
||||
|
||||
this.uiHelper.closeDialog(componentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle modal:confirm event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
async handleModalConfirm(e) {
|
||||
const payload = e.detail || {};
|
||||
const {
|
||||
componentId,
|
||||
title = 'Confirm',
|
||||
message = 'Are you sure?',
|
||||
confirmText = 'Confirm',
|
||||
cancelText = 'Cancel',
|
||||
confirmClass = 'btn-primary',
|
||||
cancelClass = 'btn-secondary',
|
||||
confirmAction = null,
|
||||
confirmParams = null,
|
||||
onConfirm = null,
|
||||
onCancel = null
|
||||
} = payload;
|
||||
|
||||
if (!componentId) {
|
||||
console.warn('[UIEventHandler] modal:confirm event missing componentId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Showing confirmation dialog for component: ${componentId}`);
|
||||
|
||||
try {
|
||||
const confirmed = await this.uiHelper.showConfirm(componentId, {
|
||||
title: title,
|
||||
message: message,
|
||||
confirmText: confirmText,
|
||||
cancelText: cancelText,
|
||||
confirmClass: confirmClass,
|
||||
cancelClass: cancelClass
|
||||
});
|
||||
|
||||
// If user confirmed and confirmAction is provided, call the LiveComponent action
|
||||
if (confirmed && confirmAction) {
|
||||
console.log(`[UIEventHandler] User confirmed, calling action: ${confirmAction}`, confirmParams);
|
||||
|
||||
// Call LiveComponent action via manager
|
||||
if (this.manager && typeof this.manager.callAction === 'function') {
|
||||
await this.manager.callAction(componentId, confirmAction, confirmParams || {});
|
||||
} else if (this.manager && typeof this.manager.executeAction === 'function') {
|
||||
// Fallback to executeAction for backward compatibility
|
||||
await this.manager.executeAction(componentId, confirmAction, confirmParams || {});
|
||||
} else {
|
||||
console.warn('[UIEventHandler] Cannot execute confirmAction: manager.callAction/executeAction not available');
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy callback support
|
||||
if (confirmed && onConfirm) {
|
||||
onConfirm();
|
||||
} else if (!confirmed && onCancel) {
|
||||
onCancel();
|
||||
}
|
||||
|
||||
// Dispatch result event
|
||||
document.dispatchEvent(new CustomEvent('modal:confirm:result', {
|
||||
detail: {
|
||||
componentId: componentId,
|
||||
confirmed: confirmed
|
||||
}
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('[UIEventHandler] Error showing confirmation dialog:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle modal:alert event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
handleModalAlert(e) {
|
||||
const payload = e.detail || {};
|
||||
const {
|
||||
componentId,
|
||||
title = 'Alert',
|
||||
message = '',
|
||||
buttonText = 'OK',
|
||||
type = 'info',
|
||||
onClose = null
|
||||
} = payload;
|
||||
|
||||
if (!componentId) {
|
||||
console.warn('[UIEventHandler] modal:alert event missing componentId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Showing alert dialog for component: ${componentId}`);
|
||||
|
||||
this.uiHelper.showAlert(componentId, {
|
||||
title: title,
|
||||
message: message,
|
||||
buttonText: buttonText,
|
||||
type: type
|
||||
});
|
||||
|
||||
if (onClose) {
|
||||
// Note: showAlert doesn't return a promise, so we'll call onClose after a delay
|
||||
// This is a limitation - ideally showAlert would return a promise
|
||||
setTimeout(() => {
|
||||
onClose();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drawer:open event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
async handleDrawerOpen(e) {
|
||||
const payload = e.detail || {};
|
||||
const {
|
||||
componentId,
|
||||
title = '',
|
||||
content = '',
|
||||
position = 'left',
|
||||
width = '400px',
|
||||
showOverlay = true,
|
||||
closeOnOverlay = true,
|
||||
closeOnEscape = true,
|
||||
animation = 'slide'
|
||||
} = payload;
|
||||
|
||||
if (!componentId) {
|
||||
console.warn('[UIEventHandler] drawer:open event missing componentId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Opening drawer for component: ${componentId}`);
|
||||
|
||||
// Initialize DrawerManager if not already done
|
||||
if (!this.drawerManager) {
|
||||
const { DrawerManager } = await import('./DrawerManager.js');
|
||||
this.drawerManager = new DrawerManager();
|
||||
}
|
||||
|
||||
this.drawerManager.open(componentId, {
|
||||
title: title,
|
||||
content: content,
|
||||
position: position,
|
||||
width: width,
|
||||
showOverlay: showOverlay,
|
||||
closeOnOverlay: closeOnOverlay,
|
||||
closeOnEscape: closeOnEscape,
|
||||
animation: animation
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drawer:close event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
handleDrawerClose(e) {
|
||||
const payload = e.detail || {};
|
||||
const { componentId } = payload;
|
||||
|
||||
if (!componentId) {
|
||||
console.warn('[UIEventHandler] drawer:close event missing componentId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Closing drawer for component: ${componentId}`);
|
||||
|
||||
if (this.drawerManager) {
|
||||
this.drawerManager.close(componentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drawer:toggle event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
handleDrawerToggle(e) {
|
||||
const payload = e.detail || {};
|
||||
const { componentId } = payload;
|
||||
|
||||
if (!componentId) {
|
||||
console.warn('[UIEventHandler] drawer:toggle event missing componentId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Toggling drawer for component: ${componentId}`);
|
||||
|
||||
if (this.drawerManager) {
|
||||
const isOpen = this.drawerManager.isOpen(componentId);
|
||||
if (isOpen) {
|
||||
this.drawerManager.close(componentId);
|
||||
} else {
|
||||
// For toggle, we need the full options - this is a limitation
|
||||
// In practice, components should use open/close explicitly
|
||||
console.warn('[UIEventHandler] drawer:toggle requires full options - use drawer:open/close instead');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle popover:show event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
async handlePopoverShow(e) {
|
||||
const payload = e.detail || {};
|
||||
const {
|
||||
componentId,
|
||||
anchorId,
|
||||
content = '',
|
||||
title = '',
|
||||
position = 'top',
|
||||
showArrow = true,
|
||||
offset = 8,
|
||||
closeOnOutsideClick = true
|
||||
} = payload;
|
||||
|
||||
if (!componentId || !anchorId) {
|
||||
console.warn('[UIEventHandler] popover:show event missing componentId or anchorId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Showing popover for component: ${componentId}`);
|
||||
|
||||
// Initialize PopoverManager if not already done
|
||||
if (!this.popoverManager) {
|
||||
const { PopoverManager } = await import('./PopoverManager.js');
|
||||
this.popoverManager = new PopoverManager();
|
||||
}
|
||||
|
||||
this.popoverManager.show(componentId, {
|
||||
anchorId: anchorId,
|
||||
content: content,
|
||||
title: title,
|
||||
position: position,
|
||||
showArrow: showArrow,
|
||||
offset: offset,
|
||||
closeOnOutsideClick: closeOnOutsideClick
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle popover:hide event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
handlePopoverHide(e) {
|
||||
const payload = e.detail || {};
|
||||
const { componentId } = payload;
|
||||
|
||||
if (!componentId) {
|
||||
console.warn('[UIEventHandler] popover:hide event missing componentId');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[UIEventHandler] Hiding popover for component: ${componentId}`);
|
||||
|
||||
if (this.popoverManager) {
|
||||
this.popoverManager.hide(componentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle popover:toggle event
|
||||
* @param {CustomEvent} e - Event object
|
||||
*/
|
||||
async handlePopoverToggle(e) {
|
||||
const payload = e.detail || {};
|
||||
const {
|
||||
componentId,
|
||||
anchorId,
|
||||
content = '',
|
||||
title = '',
|
||||
position = 'top',
|
||||
showArrow = true,
|
||||
offset = 8,
|
||||
closeOnOutsideClick = true
|
||||
} = payload;
|
||||
|
||||
if (!componentId || !anchorId) {
|
||||
console.warn('[UIEventHandler] popover:toggle event missing componentId or anchorId');
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize PopoverManager if not already done
|
||||
if (!this.popoverManager) {
|
||||
const { PopoverManager } = await import('./PopoverManager.js');
|
||||
this.popoverManager = new PopoverManager();
|
||||
}
|
||||
|
||||
// Check if popover is visible
|
||||
const isVisible = this.popoverManager.popovers.has(componentId);
|
||||
|
||||
if (isVisible) {
|
||||
this.popoverManager.hide(componentId);
|
||||
} else {
|
||||
this.popoverManager.show(componentId, {
|
||||
anchorId: anchorId,
|
||||
content: content,
|
||||
title: title,
|
||||
position: position,
|
||||
showArrow: showArrow,
|
||||
offset: offset,
|
||||
closeOnOutsideClick: closeOnOutsideClick
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup all event listeners
|
||||
*/
|
||||
destroy() {
|
||||
for (const [eventName, handler] of this.eventListeners.entries()) {
|
||||
document.removeEventListener(eventName, handler);
|
||||
}
|
||||
this.eventListeners.clear();
|
||||
|
||||
// Cleanup managers
|
||||
if (this.drawerManager) {
|
||||
this.drawerManager.destroy();
|
||||
}
|
||||
|
||||
if (this.popoverManager) {
|
||||
this.popoverManager.destroy();
|
||||
}
|
||||
|
||||
this.isInitialized = false;
|
||||
console.log('[UIEventHandler] Destroyed');
|
||||
}
|
||||
}
|
||||
|
||||
150
resources/js/modules/livecomponent/UrlManager.js
Normal file
150
resources/js/modules/livecomponent/UrlManager.js
Normal file
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* URL Manager for LiveComponents
|
||||
*
|
||||
* Handles URL updates without page reload:
|
||||
* - data-lc-push-url: Push URL to browser history
|
||||
* - data-lc-replace-url: Replace URL without history entry
|
||||
* - Browser Back/Forward support
|
||||
* - SPA Router coordination
|
||||
*/
|
||||
|
||||
export class UrlManager {
|
||||
constructor() {
|
||||
this.initialized = false;
|
||||
this.popStateHandler = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize URL manager
|
||||
*/
|
||||
init() {
|
||||
if (this.initialized) {
|
||||
console.warn('[UrlManager] Already initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
// Setup popstate handler for browser back/forward
|
||||
this.popStateHandler = (event) => {
|
||||
this.handlePopState(event);
|
||||
};
|
||||
window.addEventListener('popstate', this.popStateHandler);
|
||||
|
||||
this.initialized = true;
|
||||
console.log('[UrlManager] Initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Push URL to browser history
|
||||
*
|
||||
* @param {string} url - URL to push
|
||||
* @param {string} title - Optional page title
|
||||
*/
|
||||
pushUrl(url, title = '') {
|
||||
try {
|
||||
window.history.pushState({ url, title }, title || document.title, url);
|
||||
|
||||
// Update document title if provided
|
||||
if (title) {
|
||||
document.title = title;
|
||||
}
|
||||
|
||||
// Dispatch custom event
|
||||
window.dispatchEvent(new CustomEvent('lc:url:pushed', {
|
||||
detail: { url, title }
|
||||
}));
|
||||
|
||||
console.log(`[UrlManager] Pushed URL: ${url}`);
|
||||
} catch (error) {
|
||||
console.error('[UrlManager] Failed to push URL:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace URL without history entry
|
||||
*
|
||||
* @param {string} url - URL to replace
|
||||
* @param {string} title - Optional page title
|
||||
*/
|
||||
replaceUrl(url, title = '') {
|
||||
try {
|
||||
window.history.replaceState({ url, title }, title || document.title, url);
|
||||
|
||||
// Update document title if provided
|
||||
if (title) {
|
||||
document.title = title;
|
||||
}
|
||||
|
||||
// Dispatch custom event
|
||||
window.dispatchEvent(new CustomEvent('lc:url:replaced', {
|
||||
detail: { url, title }
|
||||
}));
|
||||
|
||||
console.log(`[UrlManager] Replaced URL: ${url}`);
|
||||
} catch (error) {
|
||||
console.error('[UrlManager] Failed to replace URL:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle browser back/forward navigation
|
||||
*
|
||||
* @param {PopStateEvent} event - PopState event
|
||||
*/
|
||||
handlePopState(event) {
|
||||
const state = event.state;
|
||||
|
||||
if (state && state.url) {
|
||||
// Dispatch custom event for popstate
|
||||
window.dispatchEvent(new CustomEvent('lc:url:popstate', {
|
||||
detail: { url: state.url, state }
|
||||
}));
|
||||
|
||||
// If SPA Router is available, let it handle navigation
|
||||
if (window.SPARouter && typeof window.SPARouter.navigate === 'function') {
|
||||
window.SPARouter.navigate(state.url);
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, trigger a page reload or custom handling
|
||||
// This is a fallback - in most cases, SPA Router should handle it
|
||||
console.log('[UrlManager] PopState detected, URL:', state.url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current URL
|
||||
*
|
||||
* @returns {string} - Current URL
|
||||
*/
|
||||
getCurrentUrl() {
|
||||
return window.location.href;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current path
|
||||
*
|
||||
* @returns {string} - Current path
|
||||
*/
|
||||
getCurrentPath() {
|
||||
return window.location.pathname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup URL manager
|
||||
*/
|
||||
cleanup() {
|
||||
if (this.popStateHandler) {
|
||||
window.removeEventListener('popstate', this.popStateHandler);
|
||||
this.popStateHandler = null;
|
||||
}
|
||||
this.initialized = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Create singleton instance
|
||||
export const urlManager = new UrlManager();
|
||||
export default urlManager;
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -23,6 +23,16 @@ import { accessibilityManager } from './AccessibilityManager.js';
|
||||
import { ErrorBoundary } from './ErrorBoundary.js';
|
||||
import { RequestDeduplicator } from './RequestDeduplicator.js';
|
||||
import * as StateSerializer from './StateSerializer.js';
|
||||
import { UIEventHandler } from './UIEventHandler.js';
|
||||
import { triggerManager } from './TriggerManager.js';
|
||||
import { sharedConfig } from './SharedConfig.js';
|
||||
import { tooltipManager } from './TooltipManager.js';
|
||||
import { actionLoadingManager } from './ActionLoadingManager.js';
|
||||
import { LiveComponentUIHelper } from './LiveComponentUIHelper.js';
|
||||
import { LoadingStateManager } from './LoadingStateManager.js';
|
||||
import { ProgressiveEnhancement } from './ProgressiveEnhancement.js';
|
||||
import { urlManager } from './UrlManager.js';
|
||||
import { LiveComponentCoreAttributes, LiveComponentFeatureAttributes, LiveComponentLazyAttributes, toDatasetKey } from '../../core/DataAttributes.js';
|
||||
|
||||
class LiveComponentManager {
|
||||
constructor() {
|
||||
@@ -64,11 +74,21 @@ class LiveComponentManager {
|
||||
// UI Helper
|
||||
this.uiHelper = new LiveComponentUIHelper(this);
|
||||
|
||||
// UI Event Handler
|
||||
this.uiEventHandler = new UIEventHandler(this);
|
||||
this.uiEventHandler.init();
|
||||
|
||||
// Loading State Manager
|
||||
this.loadingStateManager = new LoadingStateManager(
|
||||
this.actionLoadingManager,
|
||||
optimisticStateManager
|
||||
);
|
||||
|
||||
// Progressive Enhancement
|
||||
this.progressiveEnhancement = new ProgressiveEnhancement(this);
|
||||
|
||||
// URL Manager
|
||||
urlManager.init();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,17 +152,24 @@ class LiveComponentManager {
|
||||
|
||||
/**
|
||||
* Initialize LiveComponent
|
||||
*
|
||||
* @param {HTMLElement} element - Component element
|
||||
* @param {Object} options - Initialization options
|
||||
* @param {boolean} options.isolated - If true, component is isolated (Island) and won't receive parent events
|
||||
*/
|
||||
init(element) {
|
||||
const componentId = element.dataset.liveComponent;
|
||||
init(element, options = {}) {
|
||||
const componentId = element.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_COMPONENT)];
|
||||
if (!componentId) return;
|
||||
|
||||
const isIsland = options.isolated === true || element.dataset[toDatasetKey(LiveComponentLazyAttributes.ISLAND_COMPONENT)] === 'true';
|
||||
|
||||
const config = {
|
||||
id: componentId,
|
||||
element,
|
||||
pollInterval: parseInt(element.dataset.pollInterval) || null,
|
||||
pollInterval: parseInt(element.dataset[toDatasetKey(LiveComponentCoreAttributes.POLL_INTERVAL)]) || null,
|
||||
pollTimer: null,
|
||||
observer: null
|
||||
observer: null,
|
||||
isolated: isIsland
|
||||
};
|
||||
|
||||
this.components.set(componentId, config);
|
||||
@@ -162,7 +189,8 @@ class LiveComponentManager {
|
||||
this.setupLifecycleObserver(element, componentId);
|
||||
|
||||
// Setup SSE connection if component has a channel
|
||||
this.setupSseConnection(element, componentId);
|
||||
// Islands have isolated SSE channels (no parent events)
|
||||
this.setupSseConnection(element, componentId, { isolated: isIsland });
|
||||
|
||||
// Setup accessibility features
|
||||
this.setupAccessibility(componentId, element);
|
||||
@@ -170,7 +198,12 @@ class LiveComponentManager {
|
||||
// Initialize tooltips for component
|
||||
this.tooltipManager.initComponent(element);
|
||||
|
||||
console.log(`[LiveComponent] Initialized: ${componentId}`);
|
||||
// Initialize progressive enhancement if not already done
|
||||
if (!this.progressiveEnhancement.initialized) {
|
||||
this.progressiveEnhancement.init();
|
||||
}
|
||||
|
||||
console.log(`[LiveComponent] Initialized: ${componentId}${isIsland ? ' (Island)' : ''}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -178,7 +211,7 @@ class LiveComponentManager {
|
||||
*/
|
||||
setupAccessibility(componentId, element) {
|
||||
// Create component-specific ARIA live region
|
||||
const politeness = element.dataset.livePolite === 'assertive' ? 'assertive' : 'polite';
|
||||
const politeness = element.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_POLITE)] === 'assertive' ? 'assertive' : 'polite';
|
||||
this.accessibilityManager.createComponentLiveRegion(componentId, element, politeness);
|
||||
|
||||
console.log(`[LiveComponent] Accessibility features enabled for ${componentId}`);
|
||||
@@ -217,9 +250,9 @@ class LiveComponentManager {
|
||||
* Setup SSE connection for component
|
||||
* Automatically connects to SSE if component has data-sse-channel attribute
|
||||
*/
|
||||
setupSseConnection(element, componentId) {
|
||||
setupSseConnection(element, componentId, options = {}) {
|
||||
// Check if component has SSE channel
|
||||
const sseChannel = element.dataset.sseChannel;
|
||||
const sseChannel = element.dataset[toDatasetKey(LiveComponentCoreAttributes.SSE_CHANNEL)];
|
||||
if (!sseChannel) {
|
||||
return; // No SSE channel, skip
|
||||
}
|
||||
@@ -433,14 +466,112 @@ class LiveComponentManager {
|
||||
* Setup action click handlers
|
||||
*/
|
||||
setupActionHandlers(element) {
|
||||
element.querySelectorAll('[data-live-action]').forEach(actionEl => {
|
||||
// Handle form submissions
|
||||
if (actionEl.tagName === 'FORM') {
|
||||
element.querySelectorAll(`[${LiveComponentCoreAttributes.LIVE_ACTION}]`).forEach(actionEl => {
|
||||
// Find the component ID: check if action element has explicit component ID,
|
||||
// otherwise find closest parent component
|
||||
let componentId = actionEl.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_COMPONENT)];
|
||||
|
||||
if (!componentId) {
|
||||
// Find the innermost (most nested) component element
|
||||
// We need to collect all ancestor elements with data-live-component
|
||||
// and use the first one (which is the innermost/closest one)
|
||||
let current = actionEl.parentElement;
|
||||
const componentElements = [];
|
||||
|
||||
// Collect all ancestor elements with data-live-component
|
||||
while (current && current !== document.body) {
|
||||
if (current.hasAttribute && current.hasAttribute(LiveComponentCoreAttributes.LIVE_COMPONENT)) {
|
||||
componentElements.push(current);
|
||||
}
|
||||
current = current.parentElement;
|
||||
}
|
||||
|
||||
// Use the first element (innermost/closest component)
|
||||
if (componentElements.length > 0) {
|
||||
componentId = componentElements[0].dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_COMPONENT)];
|
||||
} else {
|
||||
// Fallback to closest() if manual traversal didn't work
|
||||
const fallbackElement = actionEl.closest(`[${LiveComponentCoreAttributes.LIVE_COMPONENT}]`);
|
||||
if (fallbackElement) {
|
||||
componentId = fallbackElement.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_COMPONENT)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!componentId) {
|
||||
console.warn('[LiveComponent] No component found for action:', actionEl, actionEl.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_ACTION)]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Debug logging to help diagnose issues
|
||||
if (import.meta.env.DEV && actionEl.dataset.liveAction === 'togglePreview') {
|
||||
const closestComp = actionEl.closest('[data-live-component]');
|
||||
let current = actionEl.parentElement;
|
||||
const allComponents = [];
|
||||
while (current && current !== document.body) {
|
||||
if (current.hasAttribute && current.hasAttribute(LiveComponentCoreAttributes.LIVE_COMPONENT)) {
|
||||
allComponents.push(current.dataset.liveComponent);
|
||||
}
|
||||
current = current.parentElement;
|
||||
}
|
||||
console.log('[LiveComponent] Action setup:', {
|
||||
action: actionEl.dataset.liveAction,
|
||||
componentId: componentId,
|
||||
closestComponentId: closestComp?.dataset.liveComponent,
|
||||
allAncestorComponents: allComponents,
|
||||
actionElement: actionEl,
|
||||
});
|
||||
}
|
||||
|
||||
// Check if advanced trigger options are used
|
||||
const hasAdvancedTriggers = actionEl.dataset[toDatasetKey(LiveComponentFeatureAttributes.LC_TRIGGER_DELAY)] ||
|
||||
actionEl.dataset[toDatasetKey(LiveComponentFeatureAttributes.LC_TRIGGER_THROTTLE)] ||
|
||||
actionEl.dataset[toDatasetKey(LiveComponentFeatureAttributes.LC_TRIGGER_ONCE)] === 'true' ||
|
||||
actionEl.dataset[toDatasetKey(LiveComponentFeatureAttributes.LC_TRIGGER_CHANGED)] === 'true' ||
|
||||
actionEl.dataset[toDatasetKey(LiveComponentFeatureAttributes.LC_TRIGGER_FROM)] ||
|
||||
actionEl.dataset[toDatasetKey(LiveComponentFeatureAttributes.LC_TRIGGER_LOAD)] === 'true';
|
||||
|
||||
// Create action handler function
|
||||
const createActionHandler = async (e, paramsOverride = {}) => {
|
||||
const action = actionEl.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_ACTION)];
|
||||
let params = { ...this.extractParams(actionEl), ...paramsOverride };
|
||||
|
||||
// For submit/navigation actions, collect all form values
|
||||
if (action === 'submit' || action === 'nextStep' || action === 'previousStep') {
|
||||
const formValues = this.collectFormValues(element);
|
||||
params = { ...formValues, ...params };
|
||||
}
|
||||
|
||||
// Extract fragments for partial rendering
|
||||
const fragments = this.extractFragments(actionEl);
|
||||
|
||||
await this.executeAction(componentId, action, params, fragments, actionEl);
|
||||
};
|
||||
|
||||
// Use TriggerManager if advanced triggers are present
|
||||
if (hasAdvancedTriggers) {
|
||||
triggerManager.setupTrigger(actionEl, componentId, actionEl.dataset.liveAction, async (e) => {
|
||||
if (actionEl.tagName === 'FORM' && e) {
|
||||
e.preventDefault();
|
||||
const formValues = {};
|
||||
const formData = new FormData(actionEl);
|
||||
for (const [key, value] of formData.entries()) {
|
||||
formValues[key] = value;
|
||||
}
|
||||
await createActionHandler(e, formValues);
|
||||
} else {
|
||||
if (e) e.preventDefault();
|
||||
await createActionHandler(e);
|
||||
}
|
||||
}, actionEl.tagName === 'FORM' ? 'submit' : 'click');
|
||||
// Skip default handler setup - TriggerManager handles it
|
||||
} else {
|
||||
// Handle form submissions (default behavior)
|
||||
if (actionEl.tagName === 'FORM') {
|
||||
actionEl.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const componentId = element.dataset.liveComponent;
|
||||
const action = actionEl.dataset.liveAction;
|
||||
const action = actionEl.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_ACTION)];
|
||||
|
||||
// Collect all form values
|
||||
const formValues = {};
|
||||
@@ -452,44 +583,77 @@ class LiveComponentManager {
|
||||
// Extract fragments for partial rendering
|
||||
const fragments = this.extractFragments(actionEl);
|
||||
|
||||
await this.executeAction(componentId, action, formValues, fragments);
|
||||
await this.executeAction(componentId, action, formValues, fragments, actionEl);
|
||||
});
|
||||
}
|
||||
// Handle input elements with debouncing
|
||||
else if (actionEl.tagName === 'INPUT' || actionEl.tagName === 'TEXTAREA' || actionEl.tagName === 'SELECT') {
|
||||
}
|
||||
// Handle input elements with debouncing
|
||||
else if (actionEl.tagName === 'INPUT' || actionEl.tagName === 'TEXTAREA' || actionEl.tagName === 'SELECT') {
|
||||
// Default debounce for text inputs: 300ms, others: 0ms
|
||||
const defaultDebounce = (actionEl.type === 'text' || actionEl.type === 'email' || actionEl.type === 'url' || actionEl.type === 'tel' || actionEl.tagName === 'TEXTAREA') ? 300 : 0;
|
||||
const debounceMs = parseInt(actionEl.dataset.liveDebounce) ?? defaultDebounce;
|
||||
|
||||
actionEl.addEventListener('input', async (e) => {
|
||||
const componentId = element.dataset.liveComponent;
|
||||
const action = actionEl.dataset.liveAction;
|
||||
const params = this.extractParams(actionEl);
|
||||
// For SELECT elements, use 'change' event (SELECT doesn't fire 'input' event)
|
||||
if (actionEl.tagName === 'SELECT') {
|
||||
actionEl.addEventListener('change', async (e) => {
|
||||
const action = actionEl.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_ACTION)];
|
||||
const params = this.extractParams(actionEl);
|
||||
|
||||
// Add input value to params
|
||||
if (actionEl.type === 'checkbox') {
|
||||
params[actionEl.name || 'value'] = actionEl.checked ? 'yes' : 'no';
|
||||
} else if (actionEl.type === 'radio') {
|
||||
params[actionEl.name || 'value'] = actionEl.value;
|
||||
} else {
|
||||
params[actionEl.name || 'value'] = actionEl.value;
|
||||
}
|
||||
// Add select value to params
|
||||
// Convert snake_case name to camelCase for PHP method parameter binding
|
||||
const name = actionEl.name || 'content_type_id';
|
||||
const camelCaseName = name.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
|
||||
|
||||
// Use camelCase for parameter name to match PHP method signature
|
||||
params[camelCaseName] = actionEl.value;
|
||||
|
||||
// Also keep original name for backwards compatibility
|
||||
if (name !== camelCaseName) {
|
||||
params[name] = actionEl.value;
|
||||
}
|
||||
|
||||
// Extract fragments for partial rendering
|
||||
const fragments = this.extractFragments(actionEl);
|
||||
console.log('[LiveComponent] SELECT change:', {
|
||||
action,
|
||||
name,
|
||||
camelCaseName,
|
||||
value: actionEl.value,
|
||||
params
|
||||
});
|
||||
|
||||
if (debounceMs > 0) {
|
||||
this.debouncedAction(componentId, action, params, debounceMs, fragments);
|
||||
} else {
|
||||
await this.executeAction(componentId, action, params, fragments);
|
||||
}
|
||||
});
|
||||
// Extract fragments for partial rendering
|
||||
const fragments = this.extractFragments(actionEl);
|
||||
|
||||
await this.executeAction(componentId, action, params, fragments, actionEl);
|
||||
});
|
||||
} else {
|
||||
// For INPUT and TEXTAREA, use 'input' event
|
||||
actionEl.addEventListener('input', async (e) => {
|
||||
const action = actionEl.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_ACTION)];
|
||||
const params = this.extractParams(actionEl);
|
||||
|
||||
// Add input value to params
|
||||
if (actionEl.type === 'checkbox') {
|
||||
params[actionEl.name || 'value'] = actionEl.checked ? 'yes' : 'no';
|
||||
} else if (actionEl.type === 'radio') {
|
||||
params[actionEl.name || 'value'] = actionEl.value;
|
||||
} else {
|
||||
params[actionEl.name || 'value'] = actionEl.value;
|
||||
}
|
||||
|
||||
// Extract fragments for partial rendering
|
||||
const fragments = this.extractFragments(actionEl);
|
||||
|
||||
if (debounceMs > 0) {
|
||||
this.debouncedAction(componentId, action, params, debounceMs, fragments, actionEl);
|
||||
} else {
|
||||
await this.executeAction(componentId, action, params, fragments, actionEl);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// For radio buttons and checkboxes, also listen to 'change' event
|
||||
if (actionEl.type === 'radio' || actionEl.type === 'checkbox') {
|
||||
actionEl.addEventListener('change', async (e) => {
|
||||
const componentId = element.dataset.liveComponent;
|
||||
const action = actionEl.dataset.liveAction;
|
||||
const action = actionEl.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_ACTION)];
|
||||
const params = this.extractParams(actionEl);
|
||||
|
||||
if (actionEl.type === 'checkbox') {
|
||||
@@ -498,31 +662,31 @@ class LiveComponentManager {
|
||||
params[actionEl.name || 'value'] = actionEl.value;
|
||||
}
|
||||
|
||||
await this.executeAction(componentId, action, params);
|
||||
await this.executeAction(componentId, action, params, null, actionEl);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Handle button clicks
|
||||
actionEl.addEventListener('click', async (e) => {
|
||||
e.preventDefault();
|
||||
} else {
|
||||
// Handle button clicks (default behavior)
|
||||
actionEl.addEventListener('click', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const componentId = element.dataset.liveComponent;
|
||||
const action = actionEl.dataset.liveAction;
|
||||
let params = this.extractParams(actionEl);
|
||||
const action = actionEl.dataset[toDatasetKey(LiveComponentCoreAttributes.LIVE_ACTION)];
|
||||
let params = this.extractParams(actionEl);
|
||||
|
||||
// For submit/navigation actions, collect all form values
|
||||
if (action === 'submit' || action === 'nextStep' || action === 'previousStep') {
|
||||
const formValues = this.collectFormValues(element);
|
||||
console.log('[LiveComponent] Collected form values:', formValues);
|
||||
params = { ...formValues, ...params };
|
||||
console.log('[LiveComponent] Final params:', params);
|
||||
}
|
||||
// For submit/navigation actions, collect all form values
|
||||
if (action === 'submit' || action === 'nextStep' || action === 'previousStep') {
|
||||
const formValues = this.collectFormValues(element);
|
||||
console.log('[LiveComponent] Collected form values:', formValues);
|
||||
params = { ...formValues, ...params };
|
||||
console.log('[LiveComponent] Final params:', params);
|
||||
}
|
||||
|
||||
// Extract fragments for partial rendering
|
||||
const fragments = this.extractFragments(actionEl);
|
||||
// Extract fragments for partial rendering
|
||||
const fragments = this.extractFragments(actionEl);
|
||||
|
||||
await this.executeAction(componentId, action, params, fragments);
|
||||
});
|
||||
await this.executeAction(componentId, action, params, fragments, actionEl);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -530,7 +694,7 @@ class LiveComponentManager {
|
||||
/**
|
||||
* Debounced action execution
|
||||
*/
|
||||
debouncedAction(componentId, action, params, delay, fragments = null) {
|
||||
debouncedAction(componentId, action, params, delay, fragments = null, actionElement = null) {
|
||||
const timerKey = `${componentId}_${action}`;
|
||||
|
||||
// Clear existing timer
|
||||
@@ -540,7 +704,7 @@ class LiveComponentManager {
|
||||
|
||||
// Set new timer
|
||||
const timer = setTimeout(async () => {
|
||||
await this.executeAction(componentId, action, params, fragments);
|
||||
await this.executeAction(componentId, action, params, fragments, actionElement);
|
||||
this.debounceTimers.delete(timerKey);
|
||||
}, delay);
|
||||
|
||||
@@ -636,8 +800,9 @@ class LiveComponentManager {
|
||||
* @param {string} method - Action method name
|
||||
* @param {Object} params - Action parameters
|
||||
* @param {Array<string>} fragments - Optional fragment names for partial rendering
|
||||
* @param {HTMLElement} actionElement - Optional element that triggered the action (for target/swap support)
|
||||
*/
|
||||
async executeAction(componentId, method, params = {}, fragments = null) {
|
||||
async executeAction(componentId, method, params = {}, fragments = null, actionElement = null) {
|
||||
const config = this.components.get(componentId);
|
||||
if (!config) {
|
||||
console.error(`[LiveComponent] Unknown component: ${componentId}`);
|
||||
@@ -661,19 +826,39 @@ class LiveComponentManager {
|
||||
let operationId = null;
|
||||
const startTime = performance.now();
|
||||
|
||||
// Find the correct component element (may differ from config.element for nested components)
|
||||
let componentElement = config.element;
|
||||
if (componentElement.dataset.liveComponent !== componentId) {
|
||||
// If config.element doesn't match, find the correct element
|
||||
componentElement = document.querySelector(`[data-live-component="${componentId}"]`);
|
||||
if (!componentElement) {
|
||||
console.error(`[LiveComponent] Component element not found: ${componentId}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Show loading state (uses LoadingStateManager for configurable indicators)
|
||||
const loadingConfig = this.loadingStateManager.getConfig(componentId);
|
||||
this.loadingStateManager.showLoading(componentId, config.element, {
|
||||
this.loadingStateManager.showLoading(componentId, componentElement, {
|
||||
fragments,
|
||||
type: loadingConfig.type,
|
||||
optimistic: true // Check optimistic UI first
|
||||
});
|
||||
}, actionElement);
|
||||
|
||||
// Create request promise
|
||||
const requestPromise = (async () => {
|
||||
try {
|
||||
if (componentElement.dataset.liveComponent !== componentId) {
|
||||
// If config.element doesn't match, find the correct element
|
||||
componentElement = document.querySelector(`[data-live-component="${componentId}"]`);
|
||||
if (!componentElement) {
|
||||
console.error(`[LiveComponent] Component element not found: ${componentId}`);
|
||||
throw new Error(`Component element ${componentId} not found in DOM`);
|
||||
}
|
||||
}
|
||||
|
||||
// Get current state from element using StateSerializer
|
||||
const stateWrapper = StateSerializer.getStateFromElement(config.element) || {
|
||||
const stateWrapper = StateSerializer.getStateFromElement(componentElement) || {
|
||||
id: componentId,
|
||||
component: '',
|
||||
data: {},
|
||||
@@ -683,6 +868,45 @@ class LiveComponentManager {
|
||||
// Extract actual state data from wrapper format
|
||||
// Wrapper format: {id, component, data, version}
|
||||
// Server expects just the data object
|
||||
|
||||
// Check if there are pending operations - if so, use the optimistic version
|
||||
const pendingOps = optimisticStateManager.getPendingOperations(componentId);
|
||||
|
||||
// CRITICAL: Always read version from stateWrapper first
|
||||
let currentVersion = 1;
|
||||
if (stateWrapper && typeof stateWrapper.version === 'number') {
|
||||
currentVersion = stateWrapper.version;
|
||||
}
|
||||
|
||||
// If there are pending operations, use the version from the latest optimistic state
|
||||
if (pendingOps.length > 0) {
|
||||
const latestOp = pendingOps[pendingOps.length - 1];
|
||||
if (latestOp.optimisticState && typeof latestOp.optimisticState.version === 'number') {
|
||||
currentVersion = latestOp.optimisticState.version;
|
||||
}
|
||||
}
|
||||
|
||||
// CRITICAL DEBUG: Always log, even in production
|
||||
console.error('[LiveComponent] VERSION DEBUG START', {
|
||||
stateWrapperVersion: stateWrapper?.version,
|
||||
stateWrapperVersionType: typeof stateWrapper?.version,
|
||||
currentVersion,
|
||||
pendingOpsCount: pendingOps.length,
|
||||
hasStateWrapper: !!stateWrapper,
|
||||
stateWrapperKeys: stateWrapper ? Object.keys(stateWrapper) : []
|
||||
});
|
||||
|
||||
// If there are pending operations, use the version from the latest optimistic state
|
||||
// This ensures we always send the most recent version, even with optimistic updates
|
||||
if (pendingOps.length > 0) {
|
||||
// Get the latest optimistic state version
|
||||
// The optimistic state has version = currentVersion + 1, so we use that
|
||||
const latestOp = pendingOps[pendingOps.length - 1];
|
||||
if (latestOp.optimisticState && latestOp.optimisticState.version) {
|
||||
currentVersion = latestOp.optimisticState.version;
|
||||
}
|
||||
}
|
||||
|
||||
const state = stateWrapper.data || {};
|
||||
|
||||
// Apply optimistic update for immediate UI feedback
|
||||
@@ -706,36 +930,123 @@ class LiveComponentManager {
|
||||
);
|
||||
|
||||
operationId = optimisticStateManager.getPendingOperations(componentId)[0]?.id;
|
||||
|
||||
// Debug logging for version management
|
||||
if (import.meta.env.DEV) {
|
||||
console.log(`[LiveComponent] Executing ${method} for ${componentId}`, {
|
||||
currentVersion,
|
||||
pendingOpsCount: pendingOps.length,
|
||||
operationId
|
||||
});
|
||||
}
|
||||
|
||||
// Get component-specific CSRF token from element
|
||||
const csrfToken = config.element.dataset.csrfToken;
|
||||
// Get component-specific CSRF token from the component element
|
||||
const csrfToken = componentElement.dataset.csrfToken;
|
||||
if (!csrfToken) {
|
||||
console.error(`[LiveComponent] Missing CSRF token for component: ${componentId}`);
|
||||
console.error('[LiveComponent] Component element:', componentElement);
|
||||
console.error('[LiveComponent] Component element dataset:', componentElement?.dataset);
|
||||
console.error('[LiveComponent] Component element HTML:', componentElement?.outerHTML?.substring(0, 500));
|
||||
throw new Error('CSRF token is required for component actions');
|
||||
}
|
||||
|
||||
// Debug logging for CSRF token
|
||||
if (import.meta.env.DEV) {
|
||||
console.log(`[LiveComponent] CSRF token for ${componentId}:`, csrfToken?.substring(0, 20) + '...');
|
||||
}
|
||||
|
||||
// Build request body
|
||||
const requestBody = {
|
||||
method,
|
||||
params,
|
||||
state,
|
||||
_csrf_token: csrfToken
|
||||
};
|
||||
|
||||
// CRITICAL: Always ensure version is a valid number
|
||||
// Read version from stateWrapper first, then check pending ops
|
||||
let versionToSend = 1;
|
||||
|
||||
// Try to get version from stateWrapper
|
||||
if (stateWrapper && typeof stateWrapper.version === 'number') {
|
||||
versionToSend = stateWrapper.version;
|
||||
}
|
||||
|
||||
// If there are pending operations, use the version from the latest optimistic state
|
||||
if (pendingOps.length > 0) {
|
||||
const latestOp = pendingOps[pendingOps.length - 1];
|
||||
if (latestOp.optimisticState && typeof latestOp.optimisticState.version === 'number') {
|
||||
versionToSend = latestOp.optimisticState.version;
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure versionToSend is always a valid number
|
||||
if (typeof versionToSend !== 'number' || isNaN(versionToSend)) {
|
||||
versionToSend = 1;
|
||||
}
|
||||
|
||||
// CRITICAL DEBUG: Always log, even in production
|
||||
console.error('[LiveComponent] VERSION DEBUG', {
|
||||
stateWrapperVersion: stateWrapper?.version,
|
||||
currentVersion,
|
||||
versionToSend,
|
||||
pendingOpsCount: pendingOps.length,
|
||||
hasStateWrapper: !!stateWrapper
|
||||
});
|
||||
|
||||
// CRITICAL: Build request body with version ALWAYS included as explicit property
|
||||
// Use object literal with explicit version to ensure it's never undefined
|
||||
const requestBody = {};
|
||||
requestBody.method = method;
|
||||
requestBody.params = params;
|
||||
requestBody.state = state;
|
||||
requestBody.version = versionToSend; // CRITICAL: Always send version (never undefined)
|
||||
requestBody._csrf_token = csrfToken;
|
||||
|
||||
// Add fragments parameter if specified
|
||||
if (fragments && Array.isArray(fragments) && fragments.length > 0) {
|
||||
requestBody.fragments = fragments;
|
||||
}
|
||||
|
||||
// CRITICAL: Double-check version is still present after adding fragments
|
||||
if (typeof requestBody.version !== 'number' || isNaN(requestBody.version)) {
|
||||
requestBody.version = versionToSend || 1;
|
||||
}
|
||||
|
||||
// Send AJAX request with CSRF token in body
|
||||
// Component ID is in the URL, not in the body
|
||||
|
||||
// CRITICAL DEBUG: Log the exact request body before sending
|
||||
const requestBodyString = JSON.stringify(requestBody);
|
||||
|
||||
// CRITICAL: Verify version is in JSON string - if not, force add it
|
||||
let finalRequestBody = requestBodyString;
|
||||
if (!requestBodyString.includes('"version"')) {
|
||||
console.error('[LiveComponent] ERROR: Version missing in JSON! Forcing version...', {
|
||||
jsonPreview: requestBodyString.substring(0, 300),
|
||||
versionToSend,
|
||||
requestBodyKeys: Object.keys(requestBody)
|
||||
});
|
||||
// Parse and re-add version
|
||||
try {
|
||||
const parsed = JSON.parse(requestBodyString);
|
||||
parsed.version = versionToSend || 1;
|
||||
finalRequestBody = JSON.stringify(parsed);
|
||||
console.error('[LiveComponent] Corrected JSON preview:', finalRequestBody.substring(0, 300));
|
||||
} catch (e) {
|
||||
console.error('[LiveComponent] Failed to parse/correct JSON:', e);
|
||||
// Last resort: manually add version to JSON string
|
||||
const jsonObj = JSON.parse(requestBodyString);
|
||||
jsonObj.version = versionToSend || 1;
|
||||
finalRequestBody = JSON.stringify(jsonObj);
|
||||
}
|
||||
}
|
||||
|
||||
// CRITICAL: Final verification
|
||||
if (!finalRequestBody.includes('"version"')) {
|
||||
console.error('[LiveComponent] CRITICAL ERROR: Version still missing after correction!');
|
||||
}
|
||||
|
||||
const response = await fetch(`/live-component/${componentId}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
},
|
||||
body: JSON.stringify(requestBody)
|
||||
body: finalRequestBody
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -758,7 +1069,6 @@ class LiveComponentManager {
|
||||
|
||||
// Check for version conflict
|
||||
const serverState = data.state || {};
|
||||
const currentVersion = stateWrapper.version || 1;
|
||||
const serverVersion = serverState.version || 1;
|
||||
|
||||
if (serverVersion !== currentVersion + 1) {
|
||||
@@ -789,18 +1099,54 @@ class LiveComponentManager {
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve target element (supports data-lc-target)
|
||||
const targetElement = this.resolveTarget(actionElement, componentId);
|
||||
if (!targetElement) {
|
||||
throw new Error(`[LiveComponent] Could not resolve target element for component: ${componentId}`);
|
||||
}
|
||||
|
||||
// Get swap strategy from action element or use default
|
||||
const swapStrategy = actionElement?.dataset.lcSwap || 'innerHTML';
|
||||
|
||||
// Handle fragment-based response (partial rendering)
|
||||
if (data.fragments) {
|
||||
// For fragments, always use the component element as container
|
||||
this.updateFragments(config.element, data.fragments);
|
||||
}
|
||||
// Handle full HTML response (fallback or no fragments requested)
|
||||
else if (data.html) {
|
||||
config.element.innerHTML = data.html;
|
||||
this.setupActionHandlers(config.element);
|
||||
// Use swap strategy if specified, otherwise default to innerHTML
|
||||
if (swapStrategy === 'innerHTML') {
|
||||
// Default behavior - maintain backwards compatibility
|
||||
targetElement.innerHTML = data.html;
|
||||
} else {
|
||||
// Use swapElement for other strategies with transitions and scroll
|
||||
const success = this.domPatcher.swapElement(targetElement, data.html, swapStrategy, transition, scrollOptions);
|
||||
if (!success) {
|
||||
console.warn(`[LiveComponent] Swap failed, falling back to innerHTML`);
|
||||
targetElement.innerHTML = data.html;
|
||||
}
|
||||
}
|
||||
|
||||
// Re-setup action handlers on the updated element
|
||||
// For outerHTML swap, targetElement might be replaced, so we need to find it again
|
||||
if (swapStrategy === 'outerHTML') {
|
||||
// Find the new element if it was replaced
|
||||
const newElement = document.querySelector(`[data-live-component="${componentId}"]`);
|
||||
if (newElement) {
|
||||
this.setupActionHandlers(newElement);
|
||||
} else {
|
||||
// Fallback: setup handlers on parent or document
|
||||
this.setupActionHandlers(targetElement.parentElement || document.body);
|
||||
}
|
||||
} else {
|
||||
this.setupActionHandlers(targetElement);
|
||||
}
|
||||
}
|
||||
|
||||
// Re-initialize tooltips after DOM update
|
||||
this.tooltipManager.initComponent(config.element);
|
||||
// Use targetElement for tooltips (might differ from config.element if target was used)
|
||||
this.tooltipManager.initComponent(targetElement);
|
||||
|
||||
// Update component state using StateSerializer
|
||||
if (data.state) {
|
||||
@@ -812,6 +1158,16 @@ class LiveComponentManager {
|
||||
this.handleServerEvents(data.events);
|
||||
}
|
||||
|
||||
// Handle URL updates (data-lc-push-url or data-lc-replace-url)
|
||||
const pushUrl = actionElement?.dataset.lcPushUrl;
|
||||
const replaceUrl = actionElement?.dataset.lcReplaceUrl;
|
||||
|
||||
if (pushUrl) {
|
||||
urlManager.pushUrl(pushUrl, data.title);
|
||||
} else if (replaceUrl) {
|
||||
urlManager.replaceUrl(replaceUrl, data.title);
|
||||
}
|
||||
|
||||
console.log(`[LiveComponent] Action executed: ${componentId}.${method}`, data);
|
||||
|
||||
// Log successful action to DevTools
|
||||
@@ -822,7 +1178,7 @@ class LiveComponentManager {
|
||||
this.requestDeduplicator.cacheResult(componentId, method, params, data);
|
||||
|
||||
// Hide loading state
|
||||
this.loadingStateManager.hideLoading(componentId);
|
||||
this.loadingStateManager.hideLoading(componentId, actionElement);
|
||||
|
||||
return data;
|
||||
|
||||
@@ -844,7 +1200,7 @@ class LiveComponentManager {
|
||||
}
|
||||
|
||||
// Hide loading state on error
|
||||
this.loadingStateManager.hideLoading(componentId);
|
||||
this.loadingStateManager.hideLoading(componentId, null);
|
||||
|
||||
// Handle error via ErrorBoundary
|
||||
await this.errorBoundary.handleError(componentId, method, error, {
|
||||
@@ -860,6 +1216,49 @@ class LiveComponentManager {
|
||||
return this.requestDeduplicator.registerPendingRequest(componentId, method, params, requestPromise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve target element for action updates
|
||||
*
|
||||
* Supports data-lc-target attribute to specify where updates should be applied.
|
||||
* Falls back to component element if no target is specified or target not found.
|
||||
*
|
||||
* @param {HTMLElement} actionElement - Element that triggered the action
|
||||
* @param {string} componentId - Component ID
|
||||
* @returns {HTMLElement|null} - Target element or null if not found
|
||||
*/
|
||||
resolveTarget(actionElement, componentId) {
|
||||
const targetSelector = actionElement?.dataset.lcTarget;
|
||||
|
||||
// If no target specified, use component element
|
||||
if (!targetSelector) {
|
||||
const config = this.components.get(componentId);
|
||||
return config?.element || null;
|
||||
}
|
||||
|
||||
// Try to find target element
|
||||
let targetElement = null;
|
||||
|
||||
// First try: querySelector from document
|
||||
targetElement = document.querySelector(targetSelector);
|
||||
|
||||
// Second try: querySelector from action element's closest component
|
||||
if (!targetElement && actionElement) {
|
||||
const componentElement = actionElement.closest(`[${LiveComponentCoreAttributes.LIVE_COMPONENT}]`);
|
||||
if (componentElement) {
|
||||
targetElement = componentElement.querySelector(targetSelector);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: use component element if target not found
|
||||
if (!targetElement) {
|
||||
console.warn(`[LiveComponent] Target element not found: ${targetSelector}, falling back to component element`);
|
||||
const config = this.components.get(componentId);
|
||||
return config?.element || null;
|
||||
}
|
||||
|
||||
return targetElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update specific fragments using DOM patching
|
||||
*
|
||||
@@ -922,12 +1321,15 @@ class LiveComponentManager {
|
||||
// Log event to DevTools
|
||||
this.logEventToDevTools(name, { payload, target }, 'server');
|
||||
|
||||
// Convert payload to object if it's an array (from EventPayload)
|
||||
const eventPayload = Array.isArray(payload) ? payload : (payload || {});
|
||||
|
||||
if (target) {
|
||||
// Targeted event - only for specific component
|
||||
this.dispatchToComponent(target, name, payload);
|
||||
this.dispatchToComponent(target, name, eventPayload);
|
||||
} else {
|
||||
// Broadcast event - to all listening components
|
||||
this.broadcast(name, payload);
|
||||
this.broadcast(name, eventPayload);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -943,6 +1345,37 @@ class LiveComponentManager {
|
||||
handler.callback(payload);
|
||||
}
|
||||
});
|
||||
|
||||
// Also dispatch as custom DOM event
|
||||
document.dispatchEvent(new CustomEvent(`livecomponent:${eventName}`, {
|
||||
detail: payload
|
||||
}));
|
||||
|
||||
// Dispatch direct event for UI events
|
||||
if (this.isUIEvent(eventName)) {
|
||||
document.dispatchEvent(new CustomEvent(eventName, {
|
||||
detail: payload
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch component event (used for batch operations)
|
||||
* @param {string} componentId - Component ID
|
||||
* @param {string} eventName - Event name
|
||||
* @param {Object} payload - Event payload
|
||||
*/
|
||||
dispatchComponentEvent(componentId, eventName, payload) {
|
||||
// Convert payload to object if needed
|
||||
const eventPayload = Array.isArray(payload) ? payload : (payload || {});
|
||||
|
||||
// Dispatch to component-specific handlers
|
||||
this.dispatchToComponent(componentId, eventName, eventPayload);
|
||||
|
||||
// Also broadcast if no target specified (for UI events)
|
||||
if (this.isUIEvent(eventName)) {
|
||||
this.broadcast(eventName, eventPayload);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -955,10 +1388,28 @@ class LiveComponentManager {
|
||||
handler.callback(payload);
|
||||
});
|
||||
|
||||
// Also dispatch as custom DOM event
|
||||
// Dispatch as custom DOM event with livecomponent: prefix for compatibility
|
||||
document.dispatchEvent(new CustomEvent(`livecomponent:${eventName}`, {
|
||||
detail: payload
|
||||
}));
|
||||
|
||||
// Also dispatch direct event (without prefix) for UI events
|
||||
// This allows UIEventHandler to listen to toast:show, modal:show, etc.
|
||||
if (this.isUIEvent(eventName)) {
|
||||
document.dispatchEvent(new CustomEvent(eventName, {
|
||||
detail: payload
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if event name is a UI event
|
||||
* @param {string} eventName - Event name
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isUIEvent(eventName) {
|
||||
const uiEventPrefixes = ['toast:', 'modal:'];
|
||||
return uiEventPrefixes.some(prefix => eventName.startsWith(prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1352,7 +1803,7 @@ class LiveComponentManager {
|
||||
this.tooltipManager.cleanupComponent(config.element);
|
||||
|
||||
// Hide any active loading states
|
||||
this.loadingStateManager.hideLoading(componentId);
|
||||
this.loadingStateManager.hideLoading(componentId, null);
|
||||
this.loadingStateManager.clearConfig(componentId);
|
||||
|
||||
// Cleanup UI components
|
||||
@@ -1599,7 +2050,7 @@ window.LiveComponent = LiveComponent;
|
||||
// Auto-initialize on DOM ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.querySelectorAll('[data-live-component]').forEach(el => {
|
||||
document.querySelectorAll(`[${LiveComponentCoreAttributes.LIVE_COMPONENT}]`).forEach(el => {
|
||||
LiveComponent.init(el);
|
||||
});
|
||||
});
|
||||
@@ -1629,7 +2080,7 @@ export async function init(config = {}, state = {}) {
|
||||
|
||||
// Initialize all regular LiveComponents in the page
|
||||
// This is needed when loaded as a core module (not via data-module attributes)
|
||||
const components = document.querySelectorAll('[data-live-component]');
|
||||
const components = document.querySelectorAll(`[${LiveComponentCoreAttributes.LIVE_COMPONENT}]`);
|
||||
console.log(`[LiveComponent] Found ${components.length} regular components to initialize`);
|
||||
|
||||
components.forEach(el => {
|
||||
@@ -1637,7 +2088,7 @@ export async function init(config = {}, state = {}) {
|
||||
});
|
||||
|
||||
// Lazy components are automatically initialized by LazyComponentLoader
|
||||
const lazyComponents = document.querySelectorAll('[data-live-component-lazy]');
|
||||
const lazyComponents = document.querySelectorAll(`[${LiveComponentLazyAttributes.LIVE_COMPONENT_LAZY}]`);
|
||||
console.log(`[LiveComponent] Found ${lazyComponents.length} lazy components (will load on demand)`);
|
||||
|
||||
// Log nested component stats
|
||||
@@ -1663,7 +2114,7 @@ export function initElement(element, options = {}) {
|
||||
console.log('[LiveComponent] Initializing element with data-module:', element);
|
||||
|
||||
// Find all LiveComponents within this element (or the element itself)
|
||||
const components = element.querySelectorAll('[data-live-component]');
|
||||
const components = element.querySelectorAll(`[${LiveComponentCoreAttributes.LIVE_COMPONENT}]`);
|
||||
|
||||
if (components.length === 0 && element.hasAttribute('data-live-component')) {
|
||||
// Element itself is a LiveComponent
|
||||
@@ -1687,6 +2138,7 @@ export { ChunkedUploader } from './ChunkedUploader.js';
|
||||
export { tooltipManager } from './TooltipManager.js';
|
||||
export { actionLoadingManager } from './ActionLoadingManager.js';
|
||||
export { LiveComponentUIHelper } from './LiveComponentUIHelper.js';
|
||||
export { UIEventHandler } from './UIEventHandler.js';
|
||||
export { LoadingStateManager } from './LoadingStateManager.js';
|
||||
|
||||
export default LiveComponent;
|
||||
|
||||
Reference in New Issue
Block a user