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:
175
resources/js/modules/admin/asset-filters.js
Normal file
175
resources/js/modules/admin/asset-filters.js
Normal file
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Asset Filters Module
|
||||
*
|
||||
* Handles advanced filtering for asset list
|
||||
*/
|
||||
|
||||
export class AssetFilters {
|
||||
constructor(resource) {
|
||||
this.resource = resource;
|
||||
this.filters = {
|
||||
mime: [],
|
||||
bucket: [],
|
||||
date_from: null,
|
||||
date_to: null,
|
||||
tags: [],
|
||||
};
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.setupToggle();
|
||||
this.setupFilters();
|
||||
this.setupApply();
|
||||
this.setupClear();
|
||||
}
|
||||
|
||||
setupToggle() {
|
||||
const toggleBtn = document.querySelector(`[data-toggle-filters]`);
|
||||
const panel = document.querySelector(`[data-filters-panel="${this.resource}"]`);
|
||||
|
||||
if (!toggleBtn || !panel) return;
|
||||
|
||||
toggleBtn.addEventListener('click', () => {
|
||||
const isVisible = panel.style.display !== 'none';
|
||||
panel.style.display = isVisible ? 'none' : 'block';
|
||||
toggleBtn.classList.toggle('active', !isVisible);
|
||||
});
|
||||
}
|
||||
|
||||
setupFilters() {
|
||||
// MIME type filter
|
||||
const mimeSelect = document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="mime"]`);
|
||||
if (mimeSelect) {
|
||||
mimeSelect.addEventListener('change', (e) => {
|
||||
this.filters.mime = Array.from(e.target.selectedOptions).map(opt => opt.value);
|
||||
});
|
||||
}
|
||||
|
||||
// Bucket filter
|
||||
const bucketSelect = document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="bucket"]`);
|
||||
if (bucketSelect) {
|
||||
bucketSelect.addEventListener('change', (e) => {
|
||||
this.filters.bucket = Array.from(e.target.selectedOptions).map(opt => opt.value);
|
||||
});
|
||||
}
|
||||
|
||||
// Date range filters
|
||||
const dateFrom = document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="date_from"]`);
|
||||
if (dateFrom) {
|
||||
dateFrom.addEventListener('change', (e) => {
|
||||
this.filters.date_from = e.target.value || null;
|
||||
});
|
||||
}
|
||||
|
||||
const dateTo = document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="date_to"]`);
|
||||
if (dateTo) {
|
||||
dateTo.addEventListener('change', (e) => {
|
||||
this.filters.date_to = e.target.value || null;
|
||||
});
|
||||
}
|
||||
|
||||
// Tags filter
|
||||
const tagsInput = document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="tags"]`);
|
||||
if (tagsInput) {
|
||||
tagsInput.addEventListener('input', (e) => {
|
||||
const value = e.target.value.trim();
|
||||
this.filters.tags = value ? value.split(',').map(t => t.trim()).filter(Boolean) : [];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
setupApply() {
|
||||
const applyBtn = document.querySelector(`[data-filters-panel="${this.resource}"] [data-apply-filters]`);
|
||||
if (!applyBtn) return;
|
||||
|
||||
applyBtn.addEventListener('click', () => {
|
||||
this.applyFilters();
|
||||
});
|
||||
}
|
||||
|
||||
setupClear() {
|
||||
const clearBtn = document.querySelector(`[data-filters-panel="${this.resource}"] [data-clear-filters]`);
|
||||
if (!clearBtn) return;
|
||||
|
||||
clearBtn.addEventListener('click', () => {
|
||||
this.clearFilters();
|
||||
});
|
||||
}
|
||||
|
||||
applyFilters() {
|
||||
// Build filter query
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (this.filters.mime.length > 0) {
|
||||
params.append('mime', this.filters.mime.join(','));
|
||||
}
|
||||
if (this.filters.bucket.length > 0) {
|
||||
params.append('bucket', this.filters.bucket.join(','));
|
||||
}
|
||||
if (this.filters.date_from) {
|
||||
params.append('date_from', this.filters.date_from);
|
||||
}
|
||||
if (this.filters.date_to) {
|
||||
params.append('date_to', this.filters.date_to);
|
||||
}
|
||||
if (this.filters.tags.length > 0) {
|
||||
params.append('tags', this.filters.tags.join(','));
|
||||
}
|
||||
|
||||
// Reload table with filters
|
||||
const table = document.querySelector(`[data-resource="${this.resource}"]`);
|
||||
if (table && window.adminDataTables && window.adminDataTables.get(this.resource)) {
|
||||
const dataTable = window.adminDataTables.get(this.resource);
|
||||
if (typeof dataTable.loadData === 'function') {
|
||||
dataTable.loadData(params.toString());
|
||||
}
|
||||
} else {
|
||||
// Fallback: Reload page with filters
|
||||
const url = new URL(window.location.href);
|
||||
params.forEach((value, key) => {
|
||||
url.searchParams.set(key, value);
|
||||
});
|
||||
window.location.href = url.toString();
|
||||
}
|
||||
}
|
||||
|
||||
clearFilters() {
|
||||
// Reset filter values
|
||||
this.filters = {
|
||||
mime: [],
|
||||
bucket: [],
|
||||
date_from: null,
|
||||
date_to: null,
|
||||
tags: [],
|
||||
};
|
||||
|
||||
// Reset UI
|
||||
const panel = document.querySelector(`[data-filters-panel="${this.resource}"]`);
|
||||
if (panel) {
|
||||
panel.querySelectorAll('select, input').forEach(el => {
|
||||
if (el.tagName === 'SELECT') {
|
||||
el.selectedIndex = -1;
|
||||
} else {
|
||||
el.value = '';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Reload without filters
|
||||
const url = new URL(window.location.href);
|
||||
['mime', 'bucket', 'date_from', 'date_to', 'tags'].forEach(key => {
|
||||
url.searchParams.delete(key);
|
||||
});
|
||||
window.location.href = url.toString();
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize for assets
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const assetsTable = document.querySelector('[data-resource="assets"]');
|
||||
if (assetsTable) {
|
||||
window.assetFilters = new AssetFilters('assets');
|
||||
}
|
||||
});
|
||||
|
||||
190
resources/js/modules/admin/asset-preview.js
Normal file
190
resources/js/modules/admin/asset-preview.js
Normal file
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* Asset Preview Module
|
||||
*
|
||||
* Handles asset preview thumbnails, lightbox, and detail views
|
||||
*/
|
||||
|
||||
export class AssetPreview {
|
||||
constructor() {
|
||||
this.lightbox = null;
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.setupThumbnailClicks();
|
||||
this.setupLightbox();
|
||||
this.setupCopyUrl();
|
||||
this.setupVariantDeletion();
|
||||
}
|
||||
|
||||
setupThumbnailClicks() {
|
||||
document.addEventListener('click', (e) => {
|
||||
const thumbnail = e.target.closest('.asset-preview-thumbnail');
|
||||
if (!thumbnail) return;
|
||||
|
||||
const assetId = thumbnail.dataset.assetId;
|
||||
if (!assetId) return;
|
||||
|
||||
// Navigate to detail view
|
||||
window.location.href = `/admin/assets/${assetId}`;
|
||||
});
|
||||
}
|
||||
|
||||
setupLightbox() {
|
||||
// Create lightbox HTML
|
||||
const lightboxHTML = `
|
||||
<div class="asset-lightbox" id="asset-lightbox" style="display: none;">
|
||||
<div class="asset-lightbox__content">
|
||||
<img class="asset-lightbox__image" src="" alt="Asset Preview" />
|
||||
<button class="asset-lightbox__close" data-close-lightbox>×</button>
|
||||
<div class="asset-lightbox__info">
|
||||
<p class="asset-lightbox__filename"></p>
|
||||
<p class="asset-lightbox__size"></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Add lightbox to body if not exists
|
||||
if (!document.getElementById('asset-lightbox')) {
|
||||
document.body.insertAdjacentHTML('beforeend', lightboxHTML);
|
||||
this.lightbox = document.getElementById('asset-lightbox');
|
||||
} else {
|
||||
this.lightbox = document.getElementById('asset-lightbox');
|
||||
}
|
||||
|
||||
// Setup image clicks for lightbox
|
||||
document.addEventListener('click', (e) => {
|
||||
const img = e.target.closest('img[data-lightbox]');
|
||||
if (!img) return;
|
||||
|
||||
e.preventDefault();
|
||||
this.openLightbox(img.src, img.alt, img.dataset.filename, img.dataset.size);
|
||||
});
|
||||
|
||||
// Close lightbox
|
||||
document.addEventListener('click', (e) => {
|
||||
if (e.target.closest('[data-close-lightbox]') || e.target === this.lightbox) {
|
||||
this.closeLightbox();
|
||||
}
|
||||
});
|
||||
|
||||
// Close on Escape key
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && this.lightbox && this.lightbox.style.display !== 'none') {
|
||||
this.closeLightbox();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
openLightbox(imageUrl, alt, filename, size) {
|
||||
if (!this.lightbox) return;
|
||||
|
||||
const img = this.lightbox.querySelector('.asset-lightbox__image');
|
||||
const filenameEl = this.lightbox.querySelector('.asset-lightbox__filename');
|
||||
const sizeEl = this.lightbox.querySelector('.asset-lightbox__size');
|
||||
|
||||
img.src = imageUrl;
|
||||
img.alt = alt;
|
||||
if (filenameEl) filenameEl.textContent = filename || alt;
|
||||
if (sizeEl) sizeEl.textContent = size || '';
|
||||
|
||||
this.lightbox.style.display = 'flex';
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
closeLightbox() {
|
||||
if (!this.lightbox) return;
|
||||
|
||||
this.lightbox.style.display = 'none';
|
||||
document.body.style.overflow = '';
|
||||
}
|
||||
|
||||
setupCopyUrl() {
|
||||
document.addEventListener('click', async (e) => {
|
||||
const copyButton = e.target.closest('[data-copy-url]');
|
||||
if (!copyButton) return;
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
try {
|
||||
const url = copyButton.href;
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
const assetUrl = data.url || url;
|
||||
|
||||
await navigator.clipboard.writeText(assetUrl);
|
||||
|
||||
// Show success feedback
|
||||
const originalText = copyButton.textContent;
|
||||
copyButton.textContent = 'Copied!';
|
||||
copyButton.classList.add('copied');
|
||||
|
||||
setTimeout(() => {
|
||||
copyButton.textContent = originalText;
|
||||
copyButton.classList.remove('copied');
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy URL:', error);
|
||||
alert('Failed to copy URL');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setupVariantDeletion() {
|
||||
document.addEventListener('click', async (e) => {
|
||||
const deleteButton = e.target.closest('[data-delete-variant]');
|
||||
if (!deleteButton) return;
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
const variant = deleteButton.dataset.variant;
|
||||
const assetId = deleteButton.closest('[data-asset-id]')?.dataset.assetId ||
|
||||
window.location.pathname.split('/').pop();
|
||||
|
||||
if (!confirm(`Are you sure you want to delete variant "${variant}"?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
deleteButton.disabled = true;
|
||||
deleteButton.textContent = 'Deleting...';
|
||||
|
||||
const response = await fetch(`/api/v1/assets/${assetId}/variants/${variant}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
// Remove variant item from DOM
|
||||
deleteButton.closest('.variant-item')?.remove();
|
||||
|
||||
// Show success message
|
||||
if (window.Toast) {
|
||||
window.Toast.success(`Variant "${variant}" deleted successfully`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to delete variant:', error);
|
||||
deleteButton.disabled = false;
|
||||
deleteButton.textContent = 'Delete';
|
||||
|
||||
if (window.Toast) {
|
||||
window.Toast.error(`Failed to delete variant: ${error.message}`);
|
||||
} else {
|
||||
alert(`Failed to delete variant: ${error.message}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
new AssetPreview();
|
||||
});
|
||||
|
||||
132
resources/js/modules/admin/block-editor-asset-picker.js
Normal file
132
resources/js/modules/admin/block-editor-asset-picker.js
Normal file
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Block Editor Asset Picker Integration
|
||||
*
|
||||
* Handles asset selection from AssetPickerComponent and updates block fields
|
||||
*/
|
||||
|
||||
export class BlockEditorAssetPicker {
|
||||
constructor(blockEditorElement, blockEditorComponentId) {
|
||||
this.blockEditorElement = blockEditorElement;
|
||||
this.blockEditorComponentId = blockEditorComponentId;
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// Listen for asset selection events from AssetPickerComponent
|
||||
document.addEventListener('livecomponent:event', (e) => {
|
||||
const eventData = e.detail;
|
||||
if (eventData && eventData.event_name === 'asset:selected') {
|
||||
// Find the asset picker component that triggered this
|
||||
const assetPickerElement = e.target.closest('[data-live-component^="admin-asset-picker:"]');
|
||||
if (assetPickerElement) {
|
||||
this.handleAssetSelected(eventData, assetPickerElement);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Also listen for direct asset selection from AssetPickerComponent
|
||||
this.blockEditorElement.addEventListener('click', (e) => {
|
||||
const pickerItem = e.target.closest('[data-live-action="selectAsset"]');
|
||||
if (pickerItem) {
|
||||
const assetId = pickerItem.dataset.assetId;
|
||||
if (assetId) {
|
||||
// Find which block field this picker is for
|
||||
const fieldWrapper = pickerItem.closest('.admin-asset-picker-wrapper');
|
||||
if (fieldWrapper) {
|
||||
const fieldInput = fieldWrapper.querySelector('input[data-param-field-path]');
|
||||
if (fieldInput) {
|
||||
const blockId = fieldInput.dataset.paramBlockId;
|
||||
const fieldPath = fieldInput.dataset.paramFieldPath;
|
||||
|
||||
if (blockId && fieldPath) {
|
||||
this.selectAssetForBlock(blockId, fieldPath, assetId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle asset selected event
|
||||
*/
|
||||
handleAssetSelected(eventData, assetPickerElement) {
|
||||
// Find the block field this picker is associated with
|
||||
const fieldWrapper = assetPickerElement.closest('.admin-asset-picker-wrapper');
|
||||
if (!fieldWrapper) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fieldInput = fieldWrapper.querySelector('input[data-param-field-path]');
|
||||
if (!fieldInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
const blockId = fieldInput.dataset.paramBlockId;
|
||||
const fieldPath = fieldInput.dataset.paramFieldPath;
|
||||
const assetId = eventData.asset_id || eventData.selected_asset_id;
|
||||
|
||||
if (blockId && fieldPath && assetId) {
|
||||
this.selectAssetForBlock(blockId, fieldPath, assetId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Select asset for a block field
|
||||
*/
|
||||
async selectAssetForBlock(blockId, fieldPath, assetId) {
|
||||
const liveComponent = window.LiveComponents?.getComponent?.(this.blockEditorComponentId);
|
||||
|
||||
if (!liveComponent) {
|
||||
console.warn('BlockEditorAssetPicker: LiveComponent instance not found');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await liveComponent.action('selectAssetForBlock', {
|
||||
blockId,
|
||||
fieldPath,
|
||||
assetId
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('BlockEditorAssetPicker: Failed to select asset', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all asset pickers in block editor
|
||||
*/
|
||||
static initializeAll() {
|
||||
const instances = [];
|
||||
|
||||
// Find all BlockEditorComponents
|
||||
const blockEditorElements = document.querySelectorAll(
|
||||
'[data-live-component^="admin-block-editor:"]'
|
||||
);
|
||||
|
||||
blockEditorElements.forEach(blockEditorElement => {
|
||||
const componentId = blockEditorElement.dataset.liveComponent;
|
||||
if (componentId) {
|
||||
instances.push(new BlockEditorAssetPicker(blockEditorElement, componentId));
|
||||
}
|
||||
});
|
||||
|
||||
return instances;
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize when DOM is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
BlockEditorAssetPicker.initializeAll();
|
||||
});
|
||||
} else {
|
||||
BlockEditorAssetPicker.initializeAll();
|
||||
}
|
||||
|
||||
// Re-initialize when LiveComponents are loaded dynamically
|
||||
document.addEventListener('livecomponent:loaded', () => {
|
||||
BlockEditorAssetPicker.initializeAll();
|
||||
});
|
||||
|
||||
317
resources/js/modules/admin/block-editor-dnd.js
Normal file
317
resources/js/modules/admin/block-editor-dnd.js
Normal file
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* Block Editor Drag & Drop
|
||||
*
|
||||
* Native HTML5 Drag & Drop API implementation for reordering CMS blocks
|
||||
*/
|
||||
|
||||
export class BlockEditorDnD {
|
||||
constructor(container) {
|
||||
this.container = container;
|
||||
this.blocksContainer = container.querySelector('[data-sortable="blocks"]');
|
||||
this.draggedElement = null;
|
||||
this.dragOverIndex = null;
|
||||
this.componentId = null;
|
||||
|
||||
// Find component ID from parent LiveComponent
|
||||
const liveComponent = container.closest('[data-live-component]');
|
||||
if (liveComponent) {
|
||||
this.componentId = liveComponent.dataset.liveComponent;
|
||||
}
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
if (!this.blocksContainer) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make all block cards draggable
|
||||
this.updateDraggableElements();
|
||||
|
||||
// Listen for dynamically added blocks (LiveComponent updates)
|
||||
this.observeBlockChanges();
|
||||
}
|
||||
|
||||
/**
|
||||
* Make all block cards draggable and add event listeners
|
||||
*/
|
||||
updateDraggableElements() {
|
||||
const blockCards = this.blocksContainer.querySelectorAll('.admin-block-card');
|
||||
|
||||
blockCards.forEach((card, index) => {
|
||||
// Set draggable attribute
|
||||
card.draggable = true;
|
||||
card.dataset.blockIndex = index;
|
||||
|
||||
// Remove existing listeners to avoid duplicates
|
||||
const newCard = card.cloneNode(true);
|
||||
card.parentNode.replaceChild(newCard, card);
|
||||
|
||||
// Add drag event listeners to card
|
||||
newCard.addEventListener('dragstart', (e) => this.handleDragStart(e, newCard));
|
||||
newCard.addEventListener('dragend', (e) => this.handleDragEnd(e, newCard));
|
||||
newCard.addEventListener('dragover', (e) => this.handleDragOver(e, newCard));
|
||||
newCard.addEventListener('dragenter', (e) => this.handleDragEnter(e, newCard));
|
||||
newCard.addEventListener('dragleave', (e) => this.handleDragLeave(e, newCard));
|
||||
newCard.addEventListener('drop', (e) => this.handleDrop(e, newCard));
|
||||
|
||||
// Prevent drag start on interactive elements, but allow it on drag handle
|
||||
const interactiveElements = newCard.querySelectorAll('button, input, textarea, select, a');
|
||||
interactiveElements.forEach(el => {
|
||||
// Allow drag handle to start drag
|
||||
if (el.closest('[data-drag-handle="true"]')) {
|
||||
return;
|
||||
}
|
||||
|
||||
el.addEventListener('mousedown', (e) => {
|
||||
// Prevent drag when clicking on interactive elements
|
||||
e.stopPropagation();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe DOM changes to update draggable elements when blocks are added/removed
|
||||
*/
|
||||
observeBlockChanges() {
|
||||
const observer = new MutationObserver(() => {
|
||||
this.updateDraggableElements();
|
||||
});
|
||||
|
||||
observer.observe(this.blocksContainer, {
|
||||
childList: true,
|
||||
subtree: false
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drag start
|
||||
*/
|
||||
handleDragStart(e, card) {
|
||||
// Don't start drag if clicking on buttons or inputs
|
||||
if (e.target.closest('button, input, textarea, select')) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
this.draggedElement = card;
|
||||
card.classList.add('admin-block-card--dragging');
|
||||
|
||||
// Set drag data
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
e.dataTransfer.setData('text/html', card.outerHTML);
|
||||
e.dataTransfer.setData('text/plain', card.dataset.blockId);
|
||||
|
||||
// Add visual feedback
|
||||
e.dataTransfer.setDragImage(card, 0, 0);
|
||||
|
||||
// Add placeholder styling
|
||||
this.blocksContainer.classList.add('admin-block-editor__blocks--dragging');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drag end
|
||||
*/
|
||||
handleDragEnd(e, card) {
|
||||
card.classList.remove('admin-block-card--dragging');
|
||||
this.blocksContainer.classList.remove('admin-block-editor__blocks--dragging');
|
||||
|
||||
// Remove all drag-over classes
|
||||
const allCards = this.blocksContainer.querySelectorAll('.admin-block-card');
|
||||
allCards.forEach(c => {
|
||||
c.classList.remove('admin-block-card--drag-over');
|
||||
c.classList.remove('admin-block-card--drag-over-before');
|
||||
c.classList.remove('admin-block-card--drag-over-after');
|
||||
});
|
||||
|
||||
this.draggedElement = null;
|
||||
this.dragOverIndex = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drag over
|
||||
*/
|
||||
handleDragOver(e, card) {
|
||||
if (this.draggedElement === card) {
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
|
||||
// Calculate drop position
|
||||
const cardRect = card.getBoundingClientRect();
|
||||
const mouseY = e.clientY;
|
||||
const cardMiddleY = cardRect.top + cardRect.height / 2;
|
||||
|
||||
// Determine if we're dropping before or after this card
|
||||
const isBefore = mouseY < cardMiddleY;
|
||||
|
||||
// Remove all drag-over classes
|
||||
const allCards = this.blocksContainer.querySelectorAll('.admin-block-card');
|
||||
allCards.forEach(c => {
|
||||
c.classList.remove('admin-block-card--drag-over');
|
||||
c.classList.remove('admin-block-card--drag-over-before');
|
||||
c.classList.remove('admin-block-card--drag-over-after');
|
||||
});
|
||||
|
||||
// Add appropriate class
|
||||
if (isBefore) {
|
||||
card.classList.add('admin-block-card--drag-over-before');
|
||||
} else {
|
||||
card.classList.add('admin-block-card--drag-over-after');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drag enter
|
||||
*/
|
||||
handleDragEnter(e, card) {
|
||||
if (this.draggedElement === card) {
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drag leave
|
||||
*/
|
||||
handleDragLeave(e, card) {
|
||||
// Only remove classes if we're actually leaving the card
|
||||
if (!card.contains(e.relatedTarget)) {
|
||||
card.classList.remove('admin-block-card--drag-over');
|
||||
card.classList.remove('admin-block-card--drag-over-before');
|
||||
card.classList.remove('admin-block-card--drag-over-after');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drop
|
||||
*/
|
||||
handleDrop(e, targetCard) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
if (this.draggedElement === targetCard || !this.draggedElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all block cards in current order
|
||||
const allCards = Array.from(this.blocksContainer.querySelectorAll('.admin-block-card'));
|
||||
const draggedIndex = allCards.indexOf(this.draggedElement);
|
||||
const targetIndex = allCards.indexOf(targetCard);
|
||||
|
||||
// Calculate final position based on drop zone
|
||||
const cardRect = targetCard.getBoundingClientRect();
|
||||
const mouseY = e.clientY;
|
||||
const cardMiddleY = cardRect.top + cardRect.height / 2;
|
||||
const isBefore = mouseY < cardMiddleY;
|
||||
|
||||
let finalIndex = targetIndex;
|
||||
if (isBefore && draggedIndex > targetIndex) {
|
||||
finalIndex = targetIndex;
|
||||
} else if (!isBefore && draggedIndex < targetIndex) {
|
||||
finalIndex = targetIndex + 1;
|
||||
} else if (isBefore && draggedIndex < targetIndex) {
|
||||
finalIndex = targetIndex;
|
||||
} else {
|
||||
finalIndex = targetIndex + 1;
|
||||
}
|
||||
|
||||
// Extract block IDs in new order
|
||||
const blockIds = allCards.map(card => card.dataset.blockId);
|
||||
|
||||
// Remove dragged element from array
|
||||
blockIds.splice(draggedIndex, 1);
|
||||
|
||||
// Insert at new position
|
||||
blockIds.splice(finalIndex, 0, this.draggedElement.dataset.blockId);
|
||||
|
||||
// Call LiveComponent action to reorder blocks
|
||||
this.reorderBlocks(blockIds);
|
||||
|
||||
// Clean up
|
||||
this.handleDragEnd(e, targetCard);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call LiveComponent action to reorder blocks
|
||||
*/
|
||||
reorderBlocks(blockIds) {
|
||||
if (!this.componentId) {
|
||||
console.error('BlockEditorDnD: No component ID found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the LiveComponent instance
|
||||
const liveComponentElement = document.querySelector(`[data-live-component="${this.componentId}"]`);
|
||||
if (!liveComponentElement) {
|
||||
console.error('BlockEditorDnD: LiveComponent element not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Use the LiveComponent API if available
|
||||
if (window.liveComponentManager) {
|
||||
const manager = window.liveComponentManager;
|
||||
const component = manager.getComponent(this.componentId);
|
||||
|
||||
if (component) {
|
||||
// Call action directly
|
||||
component.executeAction('reorderBlocks', { blockIds: blockIds });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Create a temporary button to trigger the action
|
||||
const actionButton = document.createElement('button');
|
||||
actionButton.type = 'button';
|
||||
actionButton.dataset.liveAction = 'reorderBlocks';
|
||||
actionButton.dataset.liveComponent = this.componentId;
|
||||
actionButton.style.display = 'none';
|
||||
|
||||
// Set block IDs as JSON string in data attribute
|
||||
// The parameter binder will convert data-param-block-ids to blockIds
|
||||
actionButton.dataset.paramBlockIds = JSON.stringify(blockIds);
|
||||
|
||||
liveComponentElement.appendChild(actionButton);
|
||||
|
||||
// Trigger click event (LiveComponent handler will pick it up)
|
||||
actionButton.click();
|
||||
|
||||
// Remove temporary button after a short delay
|
||||
setTimeout(() => {
|
||||
actionButton.remove();
|
||||
}, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all block editors on the page
|
||||
*/
|
||||
static initializeAll() {
|
||||
const containers = document.querySelectorAll('.admin-block-editor');
|
||||
const instances = [];
|
||||
|
||||
containers.forEach(container => {
|
||||
instances.push(new BlockEditorDnD(container));
|
||||
});
|
||||
|
||||
return instances;
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize when DOM is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
BlockEditorDnD.initializeAll();
|
||||
});
|
||||
} else {
|
||||
BlockEditorDnD.initializeAll();
|
||||
}
|
||||
|
||||
// Re-initialize when LiveComponents are loaded dynamically
|
||||
document.addEventListener('livecomponent:loaded', () => {
|
||||
BlockEditorDnD.initializeAll();
|
||||
});
|
||||
|
||||
138
resources/js/modules/admin/block-editor-sync.js
Normal file
138
resources/js/modules/admin/block-editor-sync.js
Normal file
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Block Editor Auto-Sync
|
||||
*
|
||||
* Automatically syncs blocks from BlockEditorComponent to ContentFormComponent
|
||||
* when blocks are added, removed, updated, or reordered.
|
||||
*/
|
||||
|
||||
export class BlockEditorSync {
|
||||
constructor(blockEditorElement, contentFormComponentId) {
|
||||
this.blockEditorElement = blockEditorElement;
|
||||
this.contentFormComponentId = contentFormComponentId;
|
||||
this.syncDebounceTimer = null;
|
||||
this.SYNC_DEBOUNCE_MS = 500; // Debounce sync calls by 500ms
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// Listen for LiveComponent update events
|
||||
this.blockEditorElement.addEventListener('livecomponent:updated', (e) => {
|
||||
this.handleBlockEditorUpdate(e);
|
||||
});
|
||||
|
||||
// Also listen for custom block events
|
||||
document.addEventListener('livecomponent:event', (e) => {
|
||||
const eventData = e.detail;
|
||||
if (eventData && eventData.component_id) {
|
||||
const blockEditorId = this.blockEditorElement.dataset.liveComponent;
|
||||
if (eventData.component_id === blockEditorId) {
|
||||
// Check if it's a block-related event
|
||||
if (eventData.event_name && (
|
||||
eventData.event_name.includes('block:') ||
|
||||
eventData.event_name.includes('blocks:')
|
||||
)) {
|
||||
this.scheduleSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle BlockEditorComponent update
|
||||
*/
|
||||
handleBlockEditorUpdate(e) {
|
||||
// Debounce sync to avoid too many requests
|
||||
this.scheduleSync();
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule sync with debouncing
|
||||
*/
|
||||
scheduleSync() {
|
||||
if (this.syncDebounceTimer) {
|
||||
clearTimeout(this.syncDebounceTimer);
|
||||
}
|
||||
|
||||
this.syncDebounceTimer = setTimeout(() => {
|
||||
this.syncBlocks();
|
||||
}, this.SYNC_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync blocks from BlockEditorComponent to ContentFormComponent
|
||||
*/
|
||||
async syncBlocks() {
|
||||
if (!this.contentFormComponentId) {
|
||||
console.warn('BlockEditorSync: No content form component ID');
|
||||
return;
|
||||
}
|
||||
|
||||
// Find ContentFormComponent element
|
||||
const contentFormElement = document.querySelector(
|
||||
`[data-live-component="${this.contentFormComponentId}"]`
|
||||
);
|
||||
|
||||
if (!contentFormElement) {
|
||||
console.warn('BlockEditorSync: ContentFormComponent not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get LiveComponent instance
|
||||
const liveComponent = window.LiveComponents?.getComponent?.(this.contentFormComponentId);
|
||||
|
||||
if (!liveComponent) {
|
||||
console.warn('BlockEditorSync: LiveComponent instance not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Call syncBlocksFromBlockEditor action on ContentFormComponent
|
||||
try {
|
||||
await liveComponent.action('syncBlocksFromBlockEditor');
|
||||
} catch (error) {
|
||||
console.error('BlockEditorSync: Failed to sync blocks', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all block editor syncs on the page
|
||||
*/
|
||||
static initializeAll() {
|
||||
const instances = [];
|
||||
|
||||
// Find all BlockEditorComponents
|
||||
const blockEditorElements = document.querySelectorAll(
|
||||
'[data-live-component^="admin-block-editor:"]'
|
||||
);
|
||||
|
||||
blockEditorElements.forEach(blockEditorElement => {
|
||||
// Find parent ContentFormComponent
|
||||
const contentFormElement = blockEditorElement.closest(
|
||||
'[data-live-component^="admin-content-form:"]'
|
||||
);
|
||||
|
||||
if (contentFormElement) {
|
||||
const contentFormComponentId = contentFormElement.dataset.liveComponent;
|
||||
instances.push(new BlockEditorSync(blockEditorElement, contentFormComponentId));
|
||||
}
|
||||
});
|
||||
|
||||
return instances;
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize when DOM is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
BlockEditorSync.initializeAll();
|
||||
});
|
||||
} else {
|
||||
BlockEditorSync.initializeAll();
|
||||
}
|
||||
|
||||
// Re-initialize when LiveComponents are loaded dynamically
|
||||
document.addEventListener('livecomponent:loaded', () => {
|
||||
BlockEditorSync.initializeAll();
|
||||
});
|
||||
|
||||
468
resources/js/modules/admin/bulk-operations.js
Normal file
468
resources/js/modules/admin/bulk-operations.js
Normal file
@@ -0,0 +1,468 @@
|
||||
/**
|
||||
* Bulk Operations Module for Admin Tables
|
||||
*
|
||||
* Handles bulk selection and actions for admin data tables
|
||||
*/
|
||||
|
||||
export class BulkOperations {
|
||||
constructor(tableElement) {
|
||||
this.table = tableElement;
|
||||
this.resource = tableElement.dataset.resource;
|
||||
this.bulkActions = JSON.parse(tableElement.dataset.bulkActions || '[]');
|
||||
this.selectedIds = new Set();
|
||||
this.toolbar = document.querySelector(`[data-bulk-toolbar="${this.resource}"]`);
|
||||
this.countElement = this.toolbar?.querySelector('[data-bulk-count]');
|
||||
this.buttonsContainer = this.toolbar?.querySelector('[data-bulk-buttons]');
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
if (!this.table.dataset.bulkOperations || this.table.dataset.bulkOperations !== 'true') {
|
||||
return; // Bulk operations not enabled for this table
|
||||
}
|
||||
|
||||
this.setupCheckboxes();
|
||||
this.setupSelectAll();
|
||||
this.setupBulkActions();
|
||||
this.updateToolbar();
|
||||
}
|
||||
|
||||
setupCheckboxes() {
|
||||
const checkboxes = this.table.querySelectorAll('.bulk-select-item');
|
||||
checkboxes.forEach(checkbox => {
|
||||
checkbox.addEventListener('change', (e) => {
|
||||
const id = e.target.dataset.bulkItemId;
|
||||
if (e.target.checked) {
|
||||
this.selectedIds.add(id);
|
||||
} else {
|
||||
this.selectedIds.delete(id);
|
||||
}
|
||||
this.updateToolbar();
|
||||
this.updateSelectAllState();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
setupSelectAll() {
|
||||
const selectAllCheckbox = this.table.querySelector('[data-bulk-select-all]');
|
||||
if (!selectAllCheckbox) return;
|
||||
|
||||
selectAllCheckbox.addEventListener('change', (e) => {
|
||||
const checked = e.target.checked;
|
||||
const checkboxes = this.table.querySelectorAll('.bulk-select-item');
|
||||
|
||||
checkboxes.forEach(checkbox => {
|
||||
checkbox.checked = checked;
|
||||
const id = checkbox.dataset.bulkItemId;
|
||||
if (checked) {
|
||||
this.selectedIds.add(id);
|
||||
} else {
|
||||
this.selectedIds.delete(id);
|
||||
}
|
||||
});
|
||||
|
||||
this.updateToolbar();
|
||||
});
|
||||
}
|
||||
|
||||
setupBulkActions() {
|
||||
if (!this.buttonsContainer || this.bulkActions.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear existing buttons
|
||||
this.buttonsContainer.innerHTML = '';
|
||||
|
||||
// Add buttons for each bulk action
|
||||
this.bulkActions.forEach(action => {
|
||||
const button = document.createElement('button');
|
||||
button.className = `btn btn--${action.style || 'secondary'} btn--sm`;
|
||||
button.textContent = action.label;
|
||||
button.dataset.bulkAction = action.action;
|
||||
button.dataset.bulkMethod = action.method || 'POST';
|
||||
if (action.confirm) {
|
||||
button.dataset.bulkConfirm = action.confirm;
|
||||
}
|
||||
|
||||
button.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
this.executeBulkAction(action);
|
||||
});
|
||||
|
||||
this.buttonsContainer.appendChild(button);
|
||||
});
|
||||
}
|
||||
|
||||
async executeBulkAction(action) {
|
||||
if (this.selectedIds.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle special actions that need custom modals
|
||||
if (action.action === 'tag' && action.confirm === false) {
|
||||
return this.showBulkTagModal(action);
|
||||
}
|
||||
|
||||
// Show confirmation dialog if needed
|
||||
if (action.confirm) {
|
||||
const confirmed = await this.showConfirmationDialog(
|
||||
action.confirm,
|
||||
`This will affect ${this.selectedIds.size} item(s).`
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Show loading state
|
||||
this.setLoadingState(true);
|
||||
|
||||
// Optimistic update: hide selected rows immediately
|
||||
const selectedRows = Array.from(this.selectedIds).map(id => {
|
||||
return this.table.querySelector(`tr[data-id="${id}"]`);
|
||||
}).filter(Boolean);
|
||||
|
||||
const rollbackRows = selectedRows.map(row => {
|
||||
const originalDisplay = row.style.display;
|
||||
row.style.display = 'none';
|
||||
row.classList.add('optimistic-delete');
|
||||
return () => {
|
||||
row.style.display = originalDisplay;
|
||||
row.classList.remove('optimistic-delete');
|
||||
};
|
||||
});
|
||||
|
||||
const ids = Array.from(this.selectedIds);
|
||||
const method = action.method || 'POST';
|
||||
|
||||
// Map action names to endpoints
|
||||
const endpointMap = {
|
||||
'assets': {
|
||||
'delete': '/api/v1/assets/bulk/delete',
|
||||
'tag': '/api/v1/assets/bulk/tags',
|
||||
},
|
||||
'contents': {
|
||||
'delete': '/admin/api/contents/bulk/delete',
|
||||
'publish': '/admin/api/contents/bulk/publish',
|
||||
},
|
||||
};
|
||||
|
||||
const endpoint = action.endpoint || endpointMap[this.resource]?.[action.action] || `/admin/api/${this.resource}/bulk/${action.action}`;
|
||||
|
||||
// Use safeFetch if available, otherwise regular fetch
|
||||
const fetchFn = window.safeFetch || (async (url, options) => {
|
||||
const response = await fetch(url, options);
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(errorData.error || `HTTP ${response.status}`);
|
||||
}
|
||||
return await response.json();
|
||||
});
|
||||
|
||||
// Prepare request body
|
||||
let requestBody = { ids: Array.from(this.selectedIds) };
|
||||
|
||||
// Add tags if this is a tag action
|
||||
if (action.action === 'tag' && action.tags) {
|
||||
requestBody.tags = action.tags;
|
||||
}
|
||||
|
||||
const result = await fetchFn(endpoint, {
|
||||
method: method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
// Show success message
|
||||
const successCount = result.total_deleted || result.total_published || result.total_tagged || ids.length;
|
||||
const actionLabel = action.action === 'tag' ? 'tagged' : action.label.toLowerCase();
|
||||
this.showToast(`Successfully ${actionLabel} ${successCount} item(s)`, 'success');
|
||||
|
||||
// Clear selection
|
||||
this.clearSelection();
|
||||
|
||||
// Reload table data if table has reload method
|
||||
const tableInstance = this.table.adminDataTable;
|
||||
if (tableInstance && typeof tableInstance.loadData === 'function') {
|
||||
tableInstance.loadData();
|
||||
} else {
|
||||
// Fallback: reload page
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Bulk action failed:', error);
|
||||
|
||||
// Rollback optimistic updates
|
||||
if (window.rollbackRows) {
|
||||
window.rollbackRows.forEach(rollback => rollback());
|
||||
}
|
||||
|
||||
// Show error with retry option
|
||||
const errorMessage = error.message || 'Unknown error occurred';
|
||||
this.showToast(`Failed to ${action.label.toLowerCase()}: ${errorMessage}`, 'error');
|
||||
|
||||
// Show retry button
|
||||
if (this.toolbar) {
|
||||
const retryButton = document.createElement('button');
|
||||
retryButton.className = 'retry-button';
|
||||
retryButton.textContent = 'Retry';
|
||||
retryButton.onclick = () => {
|
||||
retryButton.remove();
|
||||
this.executeBulkAction(action);
|
||||
};
|
||||
this.buttonsContainer?.appendChild(retryButton);
|
||||
}
|
||||
} finally {
|
||||
this.setLoadingState(false);
|
||||
}
|
||||
}
|
||||
|
||||
updateToolbar() {
|
||||
if (!this.toolbar) return;
|
||||
|
||||
const count = this.selectedIds.size;
|
||||
|
||||
if (count > 0) {
|
||||
this.toolbar.style.display = 'flex';
|
||||
if (this.countElement) {
|
||||
this.countElement.textContent = count;
|
||||
}
|
||||
} else {
|
||||
this.toolbar.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
updateSelectAllState() {
|
||||
const selectAllCheckbox = this.table.querySelector('[data-bulk-select-all]');
|
||||
if (!selectAllCheckbox) return;
|
||||
|
||||
const checkboxes = this.table.querySelectorAll('.bulk-select-item');
|
||||
const checkedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
|
||||
|
||||
if (checkedCount === 0) {
|
||||
selectAllCheckbox.checked = false;
|
||||
selectAllCheckbox.indeterminate = false;
|
||||
} else if (checkedCount === checkboxes.length) {
|
||||
selectAllCheckbox.checked = true;
|
||||
selectAllCheckbox.indeterminate = false;
|
||||
} else {
|
||||
selectAllCheckbox.checked = false;
|
||||
selectAllCheckbox.indeterminate = true;
|
||||
}
|
||||
}
|
||||
|
||||
clearSelection() {
|
||||
this.selectedIds.clear();
|
||||
const checkboxes = this.table.querySelectorAll('.bulk-select-item');
|
||||
checkboxes.forEach(checkbox => {
|
||||
checkbox.checked = false;
|
||||
});
|
||||
const selectAllCheckbox = this.table.querySelector('[data-bulk-select-all]');
|
||||
if (selectAllCheckbox) {
|
||||
selectAllCheckbox.checked = false;
|
||||
selectAllCheckbox.indeterminate = false;
|
||||
}
|
||||
this.updateToolbar();
|
||||
}
|
||||
|
||||
setLoadingState(loading) {
|
||||
const buttons = this.buttonsContainer?.querySelectorAll('button');
|
||||
if (buttons) {
|
||||
buttons.forEach(button => {
|
||||
button.disabled = loading;
|
||||
if (loading) {
|
||||
button.dataset.originalText = button.textContent;
|
||||
button.textContent = 'Processing...';
|
||||
} else {
|
||||
button.textContent = button.dataset.originalText || button.textContent;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async showConfirmationDialog(title, message) {
|
||||
return new Promise((resolve) => {
|
||||
const dialog = document.createElement('div');
|
||||
dialog.className = 'bulk-confirm-dialog';
|
||||
dialog.innerHTML = `
|
||||
<div class="bulk-confirm-dialog__overlay"></div>
|
||||
<div class="bulk-confirm-dialog__content">
|
||||
<h3>${title}</h3>
|
||||
<p>${message}</p>
|
||||
<div class="bulk-confirm-dialog__actions">
|
||||
<button class="btn btn--secondary" data-confirm-cancel>Cancel</button>
|
||||
<button class="btn btn--danger" data-confirm-ok>Confirm</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(dialog);
|
||||
|
||||
const cleanup = () => {
|
||||
document.body.removeChild(dialog);
|
||||
};
|
||||
|
||||
dialog.querySelector('[data-confirm-ok]').addEventListener('click', () => {
|
||||
cleanup();
|
||||
resolve(true);
|
||||
});
|
||||
|
||||
dialog.querySelector('[data-confirm-cancel]').addEventListener('click', () => {
|
||||
cleanup();
|
||||
resolve(false);
|
||||
});
|
||||
|
||||
dialog.querySelector('.bulk-confirm-dialog__overlay').addEventListener('click', () => {
|
||||
cleanup();
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
showToast(message, type = 'info') {
|
||||
// Use existing toast system if available
|
||||
if (window.Toast) {
|
||||
window.Toast[type](message);
|
||||
} else {
|
||||
// Fallback: simple alert
|
||||
alert(message);
|
||||
}
|
||||
}
|
||||
|
||||
async showBulkTagModal(action) {
|
||||
// Create or get modal
|
||||
let modal = document.getElementById('bulk-tag-modal');
|
||||
if (!modal) {
|
||||
// Load modal HTML (should be included in page)
|
||||
modal = document.createElement('div');
|
||||
modal.id = 'bulk-tag-modal';
|
||||
modal.innerHTML = await fetch('/admin/templates/bulk-tag-modal').then(r => r.text()).catch(() => '');
|
||||
document.body.appendChild(modal);
|
||||
}
|
||||
|
||||
// Update count
|
||||
const countElement = modal.querySelector('#bulk-tag-count');
|
||||
if (countElement) {
|
||||
countElement.textContent = this.selectedIds.size;
|
||||
}
|
||||
|
||||
// Show modal
|
||||
modal.style.display = 'block';
|
||||
|
||||
// Setup tag input with autocomplete
|
||||
const tagInput = modal.querySelector('#bulk-tag-input');
|
||||
const suggestionsContainer = modal.querySelector('#bulk-tag-suggestions');
|
||||
const suggestionsList = modal.querySelector('.bulk-tag-suggestions-list');
|
||||
let tagSuggestions = [];
|
||||
|
||||
// Load tag suggestions
|
||||
const loadSuggestions = async (search = '') => {
|
||||
try {
|
||||
const response = await fetch(`/api/v1/tags/suggestions${search ? '?search=' + encodeURIComponent(search) : ''}`);
|
||||
const data = await response.json();
|
||||
tagSuggestions = data.tags || [];
|
||||
|
||||
if (tagSuggestions.length > 0) {
|
||||
suggestionsContainer.style.display = 'block';
|
||||
suggestionsList.innerHTML = tagSuggestions.slice(0, 10).map(tag =>
|
||||
`<button type="button" class="bulk-tag-suggestion" data-tag="${tag}">${tag}</button>`
|
||||
).join('');
|
||||
|
||||
// Add click handlers to suggestions
|
||||
suggestionsList.querySelectorAll('.bulk-tag-suggestion').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const tag = btn.dataset.tag;
|
||||
const currentTags = tagInput.value.split(',').map(t => t.trim()).filter(Boolean);
|
||||
if (!currentTags.includes(tag)) {
|
||||
currentTags.push(tag);
|
||||
tagInput.value = currentTags.join(', ');
|
||||
}
|
||||
});
|
||||
});
|
||||
} else {
|
||||
suggestionsContainer.style.display = 'none';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load tag suggestions:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Load initial suggestions
|
||||
await loadSuggestions();
|
||||
|
||||
// Setup input listener for suggestions
|
||||
if (tagInput) {
|
||||
let debounceTimer;
|
||||
tagInput.addEventListener('input', (e) => {
|
||||
clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(() => {
|
||||
const search = e.target.value.split(',').pop().trim();
|
||||
if (search.length > 1) {
|
||||
loadSuggestions(search);
|
||||
} else {
|
||||
loadSuggestions();
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
}
|
||||
|
||||
// Setup submit handler
|
||||
const submitButton = modal.querySelector('#bulk-tag-submit');
|
||||
const closeModal = () => {
|
||||
modal.style.display = 'none';
|
||||
if (tagInput) tagInput.value = '';
|
||||
suggestionsContainer.style.display = 'none';
|
||||
};
|
||||
|
||||
submitButton?.addEventListener('click', async () => {
|
||||
const tagsInput = tagInput?.value.trim();
|
||||
if (!tagsInput) {
|
||||
this.showToast('Please enter at least one tag', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const tags = tagsInput.split(',').map(t => t.trim()).filter(Boolean);
|
||||
|
||||
// Execute tag action with tags
|
||||
const tagAction = { ...action, tags };
|
||||
closeModal();
|
||||
await this.executeBulkAction(tagAction);
|
||||
});
|
||||
|
||||
// Setup close handlers
|
||||
modal.querySelectorAll('[data-close-modal]').forEach(el => {
|
||||
el.addEventListener('click', closeModal);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize bulk operations for tables with bulk operations enabled
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Initialize immediately
|
||||
document.querySelectorAll('[data-bulk-operations="true"]').forEach(table => {
|
||||
new BulkOperations(table);
|
||||
});
|
||||
|
||||
// Also initialize after a short delay to catch dynamically loaded tables
|
||||
setTimeout(() => {
|
||||
document.querySelectorAll('[data-bulk-operations="true"]').forEach(table => {
|
||||
// Check if already initialized
|
||||
if (!table.dataset.bulkInitialized) {
|
||||
table.dataset.bulkInitialized = 'true';
|
||||
new BulkOperations(table);
|
||||
}
|
||||
});
|
||||
}, 100);
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { Module } from '../core/module.js';
|
||||
|
||||
/**
|
||||
* Admin Data Table Module
|
||||
*
|
||||
@@ -9,9 +7,9 @@ import { Module } from '../core/module.js';
|
||||
* - Search/filtering
|
||||
* - Auto-refresh
|
||||
*/
|
||||
export class AdminDataTable extends Module {
|
||||
export class AdminDataTable {
|
||||
constructor(element) {
|
||||
super(element);
|
||||
this.element = element;
|
||||
|
||||
this.resource = element.dataset.resource;
|
||||
this.apiEndpoint = element.dataset.apiEndpoint;
|
||||
@@ -26,11 +24,6 @@ export class AdminDataTable extends Module {
|
||||
}
|
||||
|
||||
async init() {
|
||||
if (!this.apiEndpoint) {
|
||||
console.warn('AdminDataTable: No API endpoint configured');
|
||||
return;
|
||||
}
|
||||
|
||||
this.tbody = this.element.querySelector('tbody');
|
||||
this.thead = this.element.querySelector('thead');
|
||||
|
||||
@@ -39,27 +32,38 @@ export class AdminDataTable extends Module {
|
||||
return;
|
||||
}
|
||||
|
||||
// Always setup event listeners for sorting, even if data is already loaded
|
||||
this.setupEventListeners();
|
||||
|
||||
// Only load data if table is initially empty
|
||||
if (this.tbody.children.length === 0) {
|
||||
// Only load data via AJAX if API endpoint is configured and table is empty
|
||||
if (this.apiEndpoint && this.tbody.children.length === 0) {
|
||||
await this.loadData();
|
||||
}
|
||||
}
|
||||
|
||||
setupEventListeners() {
|
||||
// Sortable columns
|
||||
if (this.sortable && this.thead) {
|
||||
this.thead.querySelectorAll('th').forEach((th, index) => {
|
||||
const columnKey = th.dataset.column || this.getColumnKeyFromIndex(index);
|
||||
// Sortable columns - only for columns with data-column attribute
|
||||
// Check both table-level sortable flag and individual column sortable attribute
|
||||
if (this.thead) {
|
||||
this.thead.querySelectorAll('th[data-column]').forEach((th) => {
|
||||
const columnKey = th.dataset.column;
|
||||
|
||||
if (columnKey) {
|
||||
th.style.cursor = 'pointer';
|
||||
th.classList.add('sortable');
|
||||
// Only make sortable if table-level sortable is enabled OR column has data-column
|
||||
if (this.sortable || th.hasAttribute('data-column')) {
|
||||
th.style.cursor = 'pointer';
|
||||
th.classList.add('sortable');
|
||||
|
||||
th.addEventListener('click', () => {
|
||||
this.sortByColumn(columnKey, th);
|
||||
});
|
||||
th.addEventListener('click', () => {
|
||||
// If API endpoint is available, use AJAX sorting
|
||||
if (this.apiEndpoint) {
|
||||
this.sortByColumn(columnKey, th);
|
||||
} else {
|
||||
// Otherwise, do client-side sorting
|
||||
this.sortByColumnClientSide(columnKey, th);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -114,8 +118,49 @@ export class AdminDataTable extends Module {
|
||||
th.dataset.sortDir = newDir;
|
||||
th.classList.add(`sort-${newDir}`);
|
||||
|
||||
// Reload data
|
||||
await this.loadData();
|
||||
// Reload data if API endpoint is available
|
||||
if (this.apiEndpoint) {
|
||||
await this.loadData();
|
||||
}
|
||||
}
|
||||
|
||||
sortByColumnClientSide(columnKey, th) {
|
||||
// Client-side sorting for tables without API endpoint
|
||||
const currentDir = th.dataset.sortDir;
|
||||
const newDir = currentDir === 'asc' ? 'desc' : 'asc';
|
||||
|
||||
// Update UI
|
||||
this.thead.querySelectorAll('th').forEach(header => {
|
||||
header.removeAttribute('data-sort-dir');
|
||||
header.classList.remove('sort-asc', 'sort-desc');
|
||||
});
|
||||
|
||||
th.dataset.sortDir = newDir;
|
||||
th.classList.add(`sort-${newDir}`);
|
||||
|
||||
// Get all rows
|
||||
const rows = Array.from(this.tbody.querySelectorAll('tr'));
|
||||
const columnIndex = Array.from(this.thead.querySelectorAll('th')).indexOf(th);
|
||||
|
||||
// Sort rows
|
||||
rows.sort((a, b) => {
|
||||
const aValue = a.cells[columnIndex]?.textContent?.trim() || '';
|
||||
const bValue = b.cells[columnIndex]?.textContent?.trim() || '';
|
||||
|
||||
// Try numeric comparison first
|
||||
const aNum = parseFloat(aValue);
|
||||
const bNum = parseFloat(bValue);
|
||||
if (!isNaN(aNum) && !isNaN(bNum)) {
|
||||
return newDir === 'asc' ? aNum - bNum : bNum - aNum;
|
||||
}
|
||||
|
||||
// String comparison
|
||||
const comparison = aValue.localeCompare(bValue);
|
||||
return newDir === 'asc' ? comparison : -comparison;
|
||||
});
|
||||
|
||||
// Re-append sorted rows
|
||||
rows.forEach(row => this.tbody.appendChild(row));
|
||||
}
|
||||
|
||||
async loadData() {
|
||||
@@ -138,7 +183,17 @@ export class AdminDataTable extends Module {
|
||||
try {
|
||||
this.setLoadingState(true);
|
||||
|
||||
const response = await fetch(url);
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
@@ -152,7 +207,20 @@ export class AdminDataTable extends Module {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('AdminDataTable: Failed to load data', error);
|
||||
this.showError('Failed to load data');
|
||||
console.error('AdminDataTable: URL was', url);
|
||||
|
||||
// Fallback to client-side sorting if API fails
|
||||
if (this.currentSort && this.tbody.children.length > 0) {
|
||||
console.warn('AdminDataTable: API failed, falling back to client-side sorting');
|
||||
const th = this.thead.querySelector(`th[data-column="${this.currentSort.column}"]`);
|
||||
if (th) {
|
||||
this.sortByColumnClientSide(this.currentSort.column, th);
|
||||
} else {
|
||||
this.showError('Failed to load data. Please refresh the page.');
|
||||
}
|
||||
} else {
|
||||
this.showError('Failed to load data');
|
||||
}
|
||||
} finally {
|
||||
this.setLoadingState(false);
|
||||
}
|
||||
@@ -288,8 +356,19 @@ export class AdminDataTable extends Module {
|
||||
}
|
||||
|
||||
// Auto-initialize all admin data tables
|
||||
// Initialize tables with API endpoints (AJAX loading)
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.querySelectorAll('[data-resource][data-api-endpoint]').forEach(table => {
|
||||
new AdminDataTable(table).init();
|
||||
});
|
||||
|
||||
// Also initialize tables with sortable attribute but without API endpoint (client-side sorting)
|
||||
document.querySelectorAll('table.admin-table[data-sortable="true"]').forEach(table => {
|
||||
if (!table.dataset.apiEndpoint) {
|
||||
// Create a minimal AdminDataTable instance for client-side sorting
|
||||
const dataTable = new AdminDataTable(table);
|
||||
dataTable.sortable = true;
|
||||
dataTable.init();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
299
resources/js/modules/admin/duplicate-management.js
Normal file
299
resources/js/modules/admin/duplicate-management.js
Normal file
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* Duplicate Management Module
|
||||
*
|
||||
* Handles duplicate asset management (merge, delete)
|
||||
*/
|
||||
|
||||
export class DuplicateManagement {
|
||||
constructor() {
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.setupDeleteDuplicate();
|
||||
this.setupDeleteGroup();
|
||||
this.setupMergeGroup();
|
||||
this.setupRefresh();
|
||||
}
|
||||
|
||||
setupDeleteDuplicate() {
|
||||
document.addEventListener('click', async (e) => {
|
||||
const button = e.target.closest('[data-delete-duplicate]');
|
||||
if (!button) return;
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
const assetId = button.dataset.assetId;
|
||||
if (!confirm(`Are you sure you want to delete this duplicate asset?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.deleteAsset(assetId, button);
|
||||
});
|
||||
}
|
||||
|
||||
setupDeleteGroup() {
|
||||
document.addEventListener('click', async (e) => {
|
||||
const button = e.target.closest('[data-delete-group]');
|
||||
if (!button) return;
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
const sha256 = button.dataset.sha256;
|
||||
const groupCard = button.closest('.duplicate-group');
|
||||
const assetCount = groupCard?.querySelectorAll('.duplicate-asset-card').length || 0;
|
||||
|
||||
if (!confirm(`Are you sure you want to delete all ${assetCount} duplicate assets in this group?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.deleteGroup(sha256, button);
|
||||
});
|
||||
}
|
||||
|
||||
setupMergeGroup() {
|
||||
document.addEventListener('click', async (e) => {
|
||||
const button = e.target.closest('[data-merge-group]');
|
||||
if (!button) return;
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
const sha256 = button.dataset.sha256;
|
||||
const groupCard = button.closest('.duplicate-group');
|
||||
const assets = Array.from(groupCard?.querySelectorAll('[data-asset-id]') || [])
|
||||
.map(el => el.dataset.assetId);
|
||||
|
||||
if (assets.length < 2) {
|
||||
if (window.Toast) {
|
||||
window.Toast.warning('Need at least 2 assets to merge');
|
||||
} else {
|
||||
alert('Need at least 2 assets to merge');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Show merge dialog
|
||||
const keepAssetId = await this.showMergeDialog(assets);
|
||||
if (!keepAssetId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.mergeGroup(sha256, assets, keepAssetId, button);
|
||||
});
|
||||
}
|
||||
|
||||
setupRefresh() {
|
||||
document.addEventListener('click', (e) => {
|
||||
const button = e.target.closest('[data-refresh-duplicates]');
|
||||
if (!button) return;
|
||||
|
||||
e.preventDefault();
|
||||
window.location.reload();
|
||||
});
|
||||
}
|
||||
|
||||
async deleteAsset(assetId, button) {
|
||||
const originalText = button.textContent;
|
||||
button.disabled = true;
|
||||
button.textContent = 'Deleting...';
|
||||
|
||||
try {
|
||||
const response = await fetch(`/admin/api/assets/${assetId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
if (window.Toast) {
|
||||
window.Toast.success('Duplicate asset deleted');
|
||||
}
|
||||
|
||||
// Remove asset card
|
||||
button.closest('.duplicate-asset-card')?.remove();
|
||||
|
||||
// Check if group is now empty or has only one asset
|
||||
const groupCard = button.closest('.duplicate-group');
|
||||
const remainingAssets = groupCard?.querySelectorAll('.duplicate-asset-card').length || 0;
|
||||
if (remainingAssets <= 1) {
|
||||
groupCard?.remove();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to delete asset:', error);
|
||||
if (window.Toast) {
|
||||
window.Toast.error(`Failed to delete asset: ${error.message}`);
|
||||
} else {
|
||||
alert(`Failed to delete asset: ${error.message}`);
|
||||
}
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = originalText;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteGroup(sha256, button) {
|
||||
const groupCard = button.closest('.duplicate-group');
|
||||
const assetCards = groupCard?.querySelectorAll('.duplicate-asset-card') || [];
|
||||
const assetIds = Array.from(assetCards).map(card =>
|
||||
card.querySelector('[data-asset-id]')?.dataset.assetId
|
||||
).filter(Boolean);
|
||||
|
||||
button.disabled = true;
|
||||
button.textContent = 'Deleting...';
|
||||
|
||||
try {
|
||||
// Delete all assets in parallel
|
||||
const deletePromises = assetIds.map(id =>
|
||||
fetch(`/admin/api/assets/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.all(deletePromises);
|
||||
|
||||
if (window.Toast) {
|
||||
window.Toast.success(`Deleted ${assetIds.length} duplicate assets`);
|
||||
}
|
||||
|
||||
// Remove group card
|
||||
groupCard?.remove();
|
||||
} catch (error) {
|
||||
console.error('Failed to delete group:', error);
|
||||
if (window.Toast) {
|
||||
window.Toast.error(`Failed to delete group: ${error.message}`);
|
||||
} else {
|
||||
alert(`Failed to delete group: ${error.message}`);
|
||||
}
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = 'Delete All';
|
||||
}
|
||||
}
|
||||
|
||||
async showMergeDialog(assetIds) {
|
||||
return new Promise((resolve) => {
|
||||
const dialog = document.createElement('div');
|
||||
dialog.className = 'merge-dialog';
|
||||
dialog.innerHTML = `
|
||||
<div class="merge-dialog__overlay"></div>
|
||||
<div class="merge-dialog__content">
|
||||
<h3>Merge Duplicate Assets</h3>
|
||||
<p>Select which asset to keep. All other duplicates will be deleted.</p>
|
||||
<div class="merge-dialog__assets" id="merge-assets-list"></div>
|
||||
<div class="merge-dialog__actions">
|
||||
<button class="btn btn--secondary" data-merge-cancel>Cancel</button>
|
||||
<button class="btn btn--primary" data-merge-confirm disabled>Merge</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(dialog);
|
||||
|
||||
const assetsList = dialog.querySelector('#merge-assets-list');
|
||||
let selectedAssetId = null;
|
||||
|
||||
// Load asset details and create radio buttons
|
||||
assetIds.forEach(assetId => {
|
||||
const assetCard = document.querySelector(`[data-asset-id="${assetId}"]`)?.closest('.duplicate-asset-card');
|
||||
if (!assetCard) return;
|
||||
|
||||
const assetIdEl = assetCard.querySelector('.asset-id code');
|
||||
const assetBucket = assetCard.querySelector('.asset-bucket');
|
||||
const assetPreview = assetCard.querySelector('.asset-preview-small')?.innerHTML;
|
||||
|
||||
const radio = document.createElement('div');
|
||||
radio.className = 'merge-asset-option';
|
||||
radio.innerHTML = `
|
||||
<input type="radio" name="keep-asset" value="${assetId}" id="asset-${assetId}">
|
||||
<label for="asset-${assetId}">
|
||||
<div class="merge-asset-preview">${assetPreview || ''}</div>
|
||||
<div class="merge-asset-info">
|
||||
<strong>${assetIdEl?.textContent || assetId}</strong>
|
||||
<small>${assetBucket?.textContent || ''}</small>
|
||||
</div>
|
||||
</label>
|
||||
`;
|
||||
|
||||
radio.querySelector('input').addEventListener('change', (e) => {
|
||||
if (e.target.checked) {
|
||||
selectedAssetId = e.target.value;
|
||||
dialog.querySelector('[data-merge-confirm]').disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
assetsList.appendChild(radio);
|
||||
});
|
||||
|
||||
const cleanup = () => {
|
||||
document.body.removeChild(dialog);
|
||||
};
|
||||
|
||||
dialog.querySelector('[data-merge-confirm]').addEventListener('click', () => {
|
||||
cleanup();
|
||||
resolve(selectedAssetId);
|
||||
});
|
||||
|
||||
dialog.querySelector('[data-merge-cancel]').addEventListener('click', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
dialog.querySelector('.merge-dialog__overlay').addEventListener('click', () => {
|
||||
cleanup();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async mergeGroup(sha256, assetIds, keepAssetId, button) {
|
||||
button.disabled = true;
|
||||
button.textContent = 'Merging...';
|
||||
|
||||
try {
|
||||
// Delete all assets except the one to keep
|
||||
const deleteIds = assetIds.filter(id => id !== keepAssetId);
|
||||
const deletePromises = deleteIds.map(id =>
|
||||
fetch(`/admin/api/assets/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.all(deletePromises);
|
||||
|
||||
if (window.Toast) {
|
||||
window.Toast.success(`Merged ${deleteIds.length} duplicates into one asset`);
|
||||
}
|
||||
|
||||
// Remove group card
|
||||
button.closest('.duplicate-group')?.remove();
|
||||
} catch (error) {
|
||||
console.error('Failed to merge group:', error);
|
||||
if (window.Toast) {
|
||||
window.Toast.error(`Failed to merge group: ${error.message}`);
|
||||
} else {
|
||||
alert(`Failed to merge group: ${error.message}`);
|
||||
}
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = 'Merge Group';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (document.querySelector('.duplicates-list')) {
|
||||
new DuplicateManagement();
|
||||
}
|
||||
});
|
||||
|
||||
135
resources/js/modules/admin/metadata-form-sync.js
Normal file
135
resources/js/modules/admin/metadata-form-sync.js
Normal file
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* MetaData Form Auto-Sync
|
||||
*
|
||||
* Automatically syncs metadata from MetaDataFormComponent to ContentFormComponent
|
||||
* when metadata fields are updated.
|
||||
*/
|
||||
|
||||
export class MetaDataFormSync {
|
||||
constructor(metaDataFormElement, contentFormComponentId) {
|
||||
this.metaDataFormElement = metaDataFormElement;
|
||||
this.contentFormComponentId = contentFormComponentId;
|
||||
this.syncDebounceTimer = null;
|
||||
this.SYNC_DEBOUNCE_MS = 500; // Debounce sync calls by 500ms
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// Listen for LiveComponent update events
|
||||
this.metaDataFormElement.addEventListener('livecomponent:updated', (e) => {
|
||||
this.handleMetaDataFormUpdate(e);
|
||||
});
|
||||
|
||||
// Also listen for custom metadata events
|
||||
document.addEventListener('livecomponent:event', (e) => {
|
||||
const eventData = e.detail;
|
||||
if (eventData && eventData.component_id) {
|
||||
const metaDataFormId = this.metaDataFormElement.dataset.liveComponent;
|
||||
if (eventData.component_id === metaDataFormId) {
|
||||
// Check if it's a metadata-related event
|
||||
if (eventData.event_name && eventData.event_name.includes('metadata:')) {
|
||||
this.scheduleSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle MetaDataFormComponent update
|
||||
*/
|
||||
handleMetaDataFormUpdate(e) {
|
||||
// Debounce sync to avoid too many requests
|
||||
this.scheduleSync();
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule sync with debouncing
|
||||
*/
|
||||
scheduleSync() {
|
||||
if (this.syncDebounceTimer) {
|
||||
clearTimeout(this.syncDebounceTimer);
|
||||
}
|
||||
|
||||
this.syncDebounceTimer = setTimeout(() => {
|
||||
this.syncMetaData();
|
||||
}, this.SYNC_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync metadata from MetaDataFormComponent to ContentFormComponent
|
||||
*/
|
||||
async syncMetaData() {
|
||||
if (!this.contentFormComponentId) {
|
||||
console.warn('MetaDataFormSync: No content form component ID');
|
||||
return;
|
||||
}
|
||||
|
||||
// Find ContentFormComponent element
|
||||
const contentFormElement = document.querySelector(
|
||||
`[data-live-component="${this.contentFormComponentId}"]`
|
||||
);
|
||||
|
||||
if (!contentFormElement) {
|
||||
console.warn('MetaDataFormSync: ContentFormComponent not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get LiveComponent instance
|
||||
const liveComponent = window.LiveComponents?.getComponent?.(this.contentFormComponentId);
|
||||
|
||||
if (!liveComponent) {
|
||||
console.warn('MetaDataFormSync: LiveComponent instance not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Call syncMetaDataFromForm action on ContentFormComponent
|
||||
try {
|
||||
await liveComponent.action('syncMetaDataFromForm');
|
||||
} catch (error) {
|
||||
console.error('MetaDataFormSync: Failed to sync metadata', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all metadata form syncs on the page
|
||||
*/
|
||||
static initializeAll() {
|
||||
const instances = [];
|
||||
|
||||
// Find all MetaDataFormComponents
|
||||
const metaDataFormElements = document.querySelectorAll(
|
||||
'[data-live-component^="admin-metadata-form:"]'
|
||||
);
|
||||
|
||||
metaDataFormElements.forEach(metaDataFormElement => {
|
||||
// Find parent ContentFormComponent
|
||||
const contentFormElement = metaDataFormElement.closest(
|
||||
'[data-live-component^="admin-content-form:"]'
|
||||
);
|
||||
|
||||
if (contentFormElement) {
|
||||
const contentFormComponentId = contentFormElement.dataset.liveComponent;
|
||||
instances.push(new MetaDataFormSync(metaDataFormElement, contentFormComponentId));
|
||||
}
|
||||
});
|
||||
|
||||
return instances;
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize when DOM is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
MetaDataFormSync.initializeAll();
|
||||
});
|
||||
} else {
|
||||
MetaDataFormSync.initializeAll();
|
||||
}
|
||||
|
||||
// Re-initialize when LiveComponents are loaded dynamically
|
||||
document.addEventListener('livecomponent:loaded', () => {
|
||||
MetaDataFormSync.initializeAll();
|
||||
});
|
||||
|
||||
253
resources/js/modules/admin/ui-enhancements.js
Normal file
253
resources/js/modules/admin/ui-enhancements.js
Normal file
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* UI Enhancements Module
|
||||
*
|
||||
* Provides loading states, optimistic updates, and better error handling
|
||||
*/
|
||||
|
||||
export class UIEnhancements {
|
||||
constructor() {
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.setupLoadingStates();
|
||||
this.setupOptimisticUpdates();
|
||||
this.setupErrorHandling();
|
||||
this.setupFormEnhancements();
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup loading states for async operations
|
||||
*/
|
||||
setupLoadingStates() {
|
||||
// Add loading state to buttons
|
||||
document.addEventListener('click', (e) => {
|
||||
const button = e.target.closest('button[data-loading]');
|
||||
if (button && !button.disabled) {
|
||||
const originalText = button.textContent;
|
||||
button.dataset.originalText = originalText;
|
||||
button.disabled = true;
|
||||
button.classList.add('loading');
|
||||
|
||||
// Add spinner
|
||||
const spinner = document.createElement('span');
|
||||
spinner.className = 'button-spinner';
|
||||
spinner.innerHTML = '⏳';
|
||||
button.prepend(spinner);
|
||||
button.textContent = button.dataset.loadingText || 'Loading...';
|
||||
|
||||
// Auto-reset after 10 seconds (safety)
|
||||
setTimeout(() => {
|
||||
this.resetButton(button);
|
||||
}, 10000);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
resetButton(button) {
|
||||
if (button.dataset.originalText) {
|
||||
button.textContent = button.dataset.originalText;
|
||||
delete button.dataset.originalText;
|
||||
}
|
||||
button.disabled = false;
|
||||
button.classList.remove('loading');
|
||||
const spinner = button.querySelector('.button-spinner');
|
||||
if (spinner) {
|
||||
spinner.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup optimistic updates for better UX
|
||||
*/
|
||||
setupOptimisticUpdates() {
|
||||
// Optimistic update helper
|
||||
window.optimisticUpdate = (element, updateFn, rollbackFn) => {
|
||||
const originalState = this.captureState(element);
|
||||
|
||||
try {
|
||||
updateFn(element);
|
||||
return () => {
|
||||
// Rollback function
|
||||
this.restoreState(element, originalState);
|
||||
if (rollbackFn) rollbackFn();
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Optimistic update failed:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Apply optimistic updates to table rows
|
||||
document.addEventListener('click', (e) => {
|
||||
const row = e.target.closest('tr[data-id]');
|
||||
if (!row) return;
|
||||
|
||||
const action = e.target.closest('[data-optimistic]');
|
||||
if (!action) return;
|
||||
|
||||
const actionType = action.dataset.optimistic;
|
||||
const rollback = this.optimisticTableUpdate(row, actionType);
|
||||
|
||||
// Store rollback function
|
||||
action.dataset.rollback = 'true';
|
||||
action.addEventListener('error', () => {
|
||||
if (rollback) rollback();
|
||||
}, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
optimisticTableUpdate(row, actionType) {
|
||||
const originalClass = row.className;
|
||||
const originalOpacity = row.style.opacity;
|
||||
|
||||
switch (actionType) {
|
||||
case 'delete':
|
||||
row.style.opacity = '0.5';
|
||||
row.style.textDecoration = 'line-through';
|
||||
row.classList.add('optimistic-delete');
|
||||
return () => {
|
||||
row.className = originalClass;
|
||||
row.style.opacity = originalOpacity;
|
||||
row.style.textDecoration = '';
|
||||
row.classList.remove('optimistic-delete');
|
||||
};
|
||||
case 'update':
|
||||
row.classList.add('optimistic-update');
|
||||
return () => {
|
||||
row.classList.remove('optimistic-update');
|
||||
};
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
captureState(element) {
|
||||
return {
|
||||
className: element.className,
|
||||
style: element.style.cssText,
|
||||
innerHTML: element.innerHTML,
|
||||
};
|
||||
}
|
||||
|
||||
restoreState(element, state) {
|
||||
element.className = state.className;
|
||||
element.style.cssText = state.style;
|
||||
element.innerHTML = state.innerHTML;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup better error handling
|
||||
*/
|
||||
setupErrorHandling() {
|
||||
// Global error handler
|
||||
window.addEventListener('error', (e) => {
|
||||
this.showErrorNotification('An unexpected error occurred', e.error);
|
||||
});
|
||||
|
||||
// Unhandled promise rejection handler
|
||||
window.addEventListener('unhandledrejection', (e) => {
|
||||
this.showErrorNotification('Request failed', e.reason);
|
||||
});
|
||||
|
||||
// Enhanced fetch wrapper with error handling
|
||||
window.safeFetch = async (url, options = {}) => {
|
||||
try {
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
this.showErrorNotification('Request failed', error.message);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
showErrorNotification(title, message) {
|
||||
// Use existing toast system if available
|
||||
if (window.Toast) {
|
||||
window.Toast.error(`${title}: ${message}`);
|
||||
} else {
|
||||
// Fallback: console error
|
||||
console.error(title, message);
|
||||
|
||||
// Show simple alert as last resort
|
||||
const errorDiv = document.createElement('div');
|
||||
errorDiv.className = 'error-notification';
|
||||
errorDiv.innerHTML = `
|
||||
<strong>${title}</strong>
|
||||
<p>${message}</p>
|
||||
<button onclick="this.parentElement.remove()">Close</button>
|
||||
`;
|
||||
document.body.appendChild(errorDiv);
|
||||
|
||||
setTimeout(() => {
|
||||
if (errorDiv.parentNode) {
|
||||
errorDiv.remove();
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup form enhancements
|
||||
*/
|
||||
setupFormEnhancements() {
|
||||
// Add loading state to forms
|
||||
document.addEventListener('submit', (e) => {
|
||||
const form = e.target;
|
||||
if (form.tagName !== 'FORM') return;
|
||||
|
||||
const submitButton = form.querySelector('button[type="submit"], input[type="submit"]');
|
||||
if (submitButton) {
|
||||
submitButton.disabled = true;
|
||||
submitButton.classList.add('loading');
|
||||
|
||||
// Add loading text
|
||||
const originalText = submitButton.value || submitButton.textContent;
|
||||
submitButton.dataset.originalText = originalText;
|
||||
submitButton.value = submitButton.value ? 'Submitting...' : submitButton.value;
|
||||
submitButton.textContent = submitButton.textContent ? 'Submitting...' : submitButton.textContent;
|
||||
}
|
||||
|
||||
// Reset on error
|
||||
form.addEventListener('error', () => {
|
||||
if (submitButton) {
|
||||
submitButton.disabled = false;
|
||||
submitButton.classList.remove('loading');
|
||||
submitButton.value = submitButton.dataset.originalText || submitButton.value;
|
||||
submitButton.textContent = submitButton.dataset.originalText || submitButton.textContent;
|
||||
}
|
||||
}, { once: true });
|
||||
});
|
||||
|
||||
// Add retry functionality for failed requests
|
||||
window.retryRequest = async (requestFn, maxRetries = 3, delay = 1000) => {
|
||||
let lastError;
|
||||
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
try {
|
||||
return await requestFn();
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (i < maxRetries - 1) {
|
||||
await new Promise(resolve => setTimeout(resolve, delay * (i + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
new UIEnhancements();
|
||||
});
|
||||
|
||||
186
resources/js/modules/admin/variant-creation.js
Normal file
186
resources/js/modules/admin/variant-creation.js
Normal file
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* Variant Creation Module
|
||||
*
|
||||
* Handles variant creation UI and API calls
|
||||
*/
|
||||
|
||||
export class VariantCreation {
|
||||
constructor() {
|
||||
this.modal = null;
|
||||
this.assetId = null;
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.setupCreateButtons();
|
||||
this.setupModal();
|
||||
this.setupPresets();
|
||||
this.setupSubmit();
|
||||
}
|
||||
|
||||
setupCreateButtons() {
|
||||
document.addEventListener('click', (e) => {
|
||||
const button = e.target.closest('[data-create-variant]');
|
||||
if (!button) return;
|
||||
|
||||
e.preventDefault();
|
||||
this.assetId = button.closest('[data-asset-id]')?.dataset.assetId ||
|
||||
window.location.pathname.split('/').pop();
|
||||
this.showModal();
|
||||
});
|
||||
}
|
||||
|
||||
setupModal() {
|
||||
// Create or get modal
|
||||
this.modal = document.getElementById('variant-create-modal');
|
||||
if (!this.modal) {
|
||||
console.warn('Variant creation modal not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Setup close handlers
|
||||
this.modal.querySelectorAll('[data-close-variant-modal]').forEach(el => {
|
||||
el.addEventListener('click', () => this.closeModal());
|
||||
});
|
||||
|
||||
// Setup quality slider
|
||||
const qualitySlider = this.modal.querySelector('#variant-quality');
|
||||
const qualityValue = this.modal.querySelector('#quality-value');
|
||||
if (qualitySlider && qualityValue) {
|
||||
qualitySlider.addEventListener('input', (e) => {
|
||||
qualityValue.textContent = e.target.value;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
setupPresets() {
|
||||
const presets = {
|
||||
'1200w': { variant: '1200w', width: 1200, quality: 85 },
|
||||
'800w': { variant: '800w', width: 800, quality: 85 },
|
||||
'thumb@1x': { variant: 'thumb@1x', width: 200, quality: 80 },
|
||||
'thumb@2x': { variant: 'thumb@2x', width: 400, quality: 80 },
|
||||
};
|
||||
|
||||
this.modal?.querySelectorAll('[data-preset]').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
const preset = presets[button.dataset.preset];
|
||||
if (preset) {
|
||||
this.modal.querySelector('#variant-name').value = preset.variant;
|
||||
this.modal.querySelector('#variant-width').value = preset.width;
|
||||
this.modal.querySelector('#variant-quality').value = preset.quality;
|
||||
this.modal.querySelector('#quality-value').textContent = preset.quality;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
setupSubmit() {
|
||||
const submitButton = this.modal?.querySelector('#variant-create-submit');
|
||||
if (!submitButton) return;
|
||||
|
||||
submitButton.addEventListener('click', async () => {
|
||||
await this.createVariant();
|
||||
});
|
||||
}
|
||||
|
||||
showModal() {
|
||||
if (!this.modal) return;
|
||||
|
||||
// Reset form
|
||||
const form = this.modal.querySelector('#variant-create-form');
|
||||
if (form) {
|
||||
form.reset();
|
||||
this.modal.querySelector('#variant-quality').value = 85;
|
||||
this.modal.querySelector('#quality-value').textContent = '85';
|
||||
}
|
||||
|
||||
this.modal.style.display = 'block';
|
||||
}
|
||||
|
||||
closeModal() {
|
||||
if (this.modal) {
|
||||
this.modal.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
async createVariant() {
|
||||
if (!this.assetId) {
|
||||
console.error('Asset ID not set');
|
||||
return;
|
||||
}
|
||||
|
||||
const form = this.modal.querySelector('#variant-create-form');
|
||||
if (!form) return;
|
||||
|
||||
const formData = new FormData(form);
|
||||
const data = {
|
||||
variant: formData.get('variant'),
|
||||
width: formData.get('width') ? parseInt(formData.get('width')) : null,
|
||||
height: formData.get('height') ? parseInt(formData.get('height')) : null,
|
||||
quality: formData.get('quality') ? parseInt(formData.get('quality')) : null,
|
||||
};
|
||||
|
||||
// Validate
|
||||
if (!data.variant) {
|
||||
if (window.Toast) {
|
||||
window.Toast.error('Variant name is required');
|
||||
} else {
|
||||
alert('Variant name is required');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const submitButton = this.modal.querySelector('#variant-create-submit');
|
||||
const originalText = submitButton.textContent;
|
||||
submitButton.disabled = true;
|
||||
submitButton.textContent = 'Creating...';
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/v1/assets/${this.assetId}/variants`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(errorData.error || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (window.Toast) {
|
||||
window.Toast.success('Variant creation queued. It will be processed shortly.');
|
||||
} else {
|
||||
alert('Variant creation queued successfully');
|
||||
}
|
||||
|
||||
this.closeModal();
|
||||
|
||||
// Reload page after a short delay to show new variant
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1500);
|
||||
} catch (error) {
|
||||
console.error('Failed to create variant:', error);
|
||||
|
||||
if (window.Toast) {
|
||||
window.Toast.error(`Failed to create variant: ${error.message}`);
|
||||
} else {
|
||||
alert(`Failed to create variant: ${error.message}`);
|
||||
}
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
submitButton.textContent = originalText;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-initialize
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
new VariantCreation();
|
||||
});
|
||||
|
||||
137
resources/js/modules/admin/view-transitions.js
Normal file
137
resources/js/modules/admin/view-transitions.js
Normal file
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* View Transitions Helper - Admin Interface
|
||||
*
|
||||
* Helper-Funktionen für View Transitions API.
|
||||
* Baseline 2023: View Transitions API ist Baseline Newly available.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if View Transitions are supported
|
||||
*/
|
||||
export function supportsViewTransitions() {
|
||||
return 'startViewTransition' in document;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start View Transition for Admin Navigation
|
||||
*/
|
||||
export function transitionNavigation(callback) {
|
||||
if (!supportsViewTransitions()) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
document.startViewTransition(() => {
|
||||
callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Start View Transition for Admin Content Updates
|
||||
*/
|
||||
export function transitionContentUpdate(callback) {
|
||||
if (!supportsViewTransitions()) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
const transition = document.startViewTransition(() => {
|
||||
callback();
|
||||
});
|
||||
|
||||
return transition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start View Transition for Popover
|
||||
*/
|
||||
export function transitionPopover(popoverElement, callback) {
|
||||
if (!supportsViewTransitions()) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
|
||||
// Set view-transition-name for this specific popover
|
||||
const originalName = popoverElement.style.viewTransitionName;
|
||||
popoverElement.style.viewTransitionName = `admin-popover-${popoverElement.id}`;
|
||||
|
||||
const transition = document.startViewTransition(() => {
|
||||
callback();
|
||||
});
|
||||
|
||||
transition.finished.finally(() => {
|
||||
// Restore original name
|
||||
if (originalName) {
|
||||
popoverElement.style.viewTransitionName = originalName;
|
||||
} else {
|
||||
popoverElement.style.viewTransitionName = '';
|
||||
}
|
||||
});
|
||||
|
||||
return transition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize View Transitions for Admin Navigation Links
|
||||
*/
|
||||
export function initAdminNavigationTransitions() {
|
||||
if (!supportsViewTransitions()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle navigation links
|
||||
document.querySelectorAll('.admin-nav a[href]').forEach(link => {
|
||||
link.addEventListener('click', (e) => {
|
||||
const href = link.getAttribute('href');
|
||||
|
||||
// Only handle internal links
|
||||
if (href && !href.startsWith('http') && !href.startsWith('#')) {
|
||||
e.preventDefault();
|
||||
|
||||
transitionNavigation(() => {
|
||||
window.location.href = href;
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize View Transitions for Popover Toggles
|
||||
*/
|
||||
export function initPopoverTransitions() {
|
||||
if (!supportsViewTransitions()) {
|
||||
return;
|
||||
}
|
||||
|
||||
document.querySelectorAll('[popovertarget]').forEach(trigger => {
|
||||
const popoverId = trigger.getAttribute('popovertarget');
|
||||
const popover = document.getElementById(popoverId);
|
||||
|
||||
if (popover) {
|
||||
popover.addEventListener('toggle', (e) => {
|
||||
const isOpen = popover.matches(':popover-open');
|
||||
|
||||
transitionPopover(popover, () => {
|
||||
// Transition is handled by browser
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all View Transitions
|
||||
*/
|
||||
export function initViewTransitions() {
|
||||
initAdminNavigationTransitions();
|
||||
initPopoverTransitions();
|
||||
}
|
||||
|
||||
// Auto-initialize if DOM is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', initViewTransitions);
|
||||
} else {
|
||||
initViewTransitions();
|
||||
}
|
||||
|
||||
534
resources/js/modules/common/ActionHandler.js
Normal file
534
resources/js/modules/common/ActionHandler.js
Normal file
@@ -0,0 +1,534 @@
|
||||
/**
|
||||
* Generic ActionHandler Module
|
||||
*
|
||||
* Provides reusable event delegation-based action handling with:
|
||||
* - Automatic CSRF token injection
|
||||
* - Loading state management
|
||||
* - Confirmation dialogs
|
||||
* - Toast integration
|
||||
* - URL template processing
|
||||
* - Error handling
|
||||
*/
|
||||
|
||||
export class ActionHandler {
|
||||
constructor(containerSelector, options = {}) {
|
||||
this.containerSelector = containerSelector;
|
||||
this.container = null;
|
||||
this.options = {
|
||||
csrfTokenSelector: options.csrfTokenSelector || '[data-live-component]',
|
||||
toastHandler: options.toastHandler || null,
|
||||
confirmationHandler: options.confirmationHandler || null,
|
||||
loadingTexts: options.loadingTexts || {},
|
||||
autoRefresh: options.autoRefresh !== false,
|
||||
refreshHandler: options.refreshHandler || null,
|
||||
...options
|
||||
};
|
||||
|
||||
this.handlers = new Map();
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize event delegation
|
||||
*/
|
||||
init() {
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => this.setupEventDelegation());
|
||||
} else {
|
||||
this.setupEventDelegation();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup event delegation on container
|
||||
*/
|
||||
setupEventDelegation() {
|
||||
this.container = document.querySelector(this.containerSelector);
|
||||
if (!this.container) {
|
||||
console.warn(`[ActionHandler] Container not found: ${this.containerSelector}`);
|
||||
return;
|
||||
}
|
||||
|
||||
this.container.addEventListener('click', (e) => {
|
||||
const button = e.target.closest('[data-action]');
|
||||
if (!button) return;
|
||||
|
||||
const action = button.dataset.action;
|
||||
if (action) {
|
||||
e.preventDefault();
|
||||
this.handleAction(action, button);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a named action handler
|
||||
*/
|
||||
registerHandler(name, config) {
|
||||
this.handlers.set(name, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle action from button click
|
||||
*/
|
||||
async handleAction(action, element) {
|
||||
// Check if handler is registered
|
||||
const handlerName = element.dataset.actionHandler || 'default';
|
||||
const handler = this.handlers.get(handlerName);
|
||||
|
||||
// Get action configuration
|
||||
const config = this.getActionConfig(action, element, handler);
|
||||
|
||||
// If handler provides URL template but config doesn't have URL, use template
|
||||
if (!config.url && handler?.urlTemplate) {
|
||||
config.url = handler.urlTemplate;
|
||||
}
|
||||
|
||||
if (!config.url) {
|
||||
console.warn(`[ActionHandler] No URL found for action: ${action}`, {
|
||||
element,
|
||||
handlerName,
|
||||
config
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Show confirmation if required
|
||||
if (config.confirm) {
|
||||
const confirmed = await this.showConfirmation(config.confirm);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Set loading state
|
||||
const loadingText = config.loadingText || this.options.loadingTexts[action] || 'Processing...';
|
||||
this.showLoading(element, loadingText);
|
||||
|
||||
try {
|
||||
// Process URL template first (needed for both window and fetch)
|
||||
let url = this.processUrlTemplate(config.url, element);
|
||||
|
||||
// Handle special actions (like logs that open in new window)
|
||||
if (config.type === 'window') {
|
||||
// Ensure URL is absolute for window.open (relative URLs don't work reliably)
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
url = `${window.location.origin}${url}`;
|
||||
}
|
||||
window.open(url, config.windowTarget || '_blank');
|
||||
this.resetLoading(element);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle inline expandable content (like logs in table rows)
|
||||
if (config.type === 'inline') {
|
||||
const containerId = element.dataset.actionParamId;
|
||||
const logsRow = document.querySelector(`[data-logs-container="${containerId}"]`);
|
||||
const logsContent = logsRow?.querySelector(`[data-logs-content="${containerId}"]`);
|
||||
|
||||
if (!logsRow || !logsContent) {
|
||||
console.warn(`[ActionHandler] Logs row not found for container: ${containerId}`);
|
||||
this.resetLoading(element);
|
||||
return;
|
||||
}
|
||||
|
||||
// Toggle visibility
|
||||
const isVisible = logsRow.style.display !== 'none';
|
||||
|
||||
if (isVisible) {
|
||||
// Collapse
|
||||
logsRow.style.display = 'none';
|
||||
const icon = element.querySelector('.logs-icon');
|
||||
if (icon) {
|
||||
icon.textContent = '📋';
|
||||
}
|
||||
element.classList.remove('active');
|
||||
this.resetLoading(element);
|
||||
return;
|
||||
}
|
||||
|
||||
// Expand and load logs
|
||||
logsRow.style.display = '';
|
||||
const icon = element.querySelector('.logs-icon');
|
||||
if (icon) {
|
||||
icon.textContent = '📖';
|
||||
}
|
||||
element.classList.add('active');
|
||||
|
||||
// Check if already loaded
|
||||
if (logsContent.dataset.loaded === 'true') {
|
||||
this.resetLoading(element);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure URL is absolute
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
url = `${window.location.origin}${url}`;
|
||||
}
|
||||
|
||||
// Fetch logs
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
...config.headers
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
this.resetLoading(element);
|
||||
|
||||
if (data.success && data.data?.logs) {
|
||||
// Render logs
|
||||
logsContent.innerHTML = `<pre class="docker-logs"><code>${this.escapeHtml(data.data.logs)}</code></pre>`;
|
||||
logsContent.dataset.loaded = 'true';
|
||||
} else {
|
||||
logsContent.innerHTML = '<div class="alert alert-error">Failed to load logs</div>';
|
||||
}
|
||||
} catch (error) {
|
||||
this.resetLoading(element);
|
||||
logsContent.innerHTML = `<div class="alert alert-error">Error loading logs: ${this.escapeHtml(error.message)}</div>`;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Get CSRF token
|
||||
const { token, formId } = this.getCsrfToken(element);
|
||||
|
||||
// Make request
|
||||
const response = await fetch(url, {
|
||||
method: config.method || 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-Token': token,
|
||||
...config.headers
|
||||
},
|
||||
body: JSON.stringify({
|
||||
_form_id: formId,
|
||||
_token: token,
|
||||
...config.body
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success !== false) {
|
||||
// Success
|
||||
const successMessage = config.successToast || config.successMessage ||
|
||||
(handler?.successMessages?.[action]) ||
|
||||
`Action ${action} completed successfully`;
|
||||
this.showToast(successMessage, 'success');
|
||||
|
||||
// Auto refresh if enabled
|
||||
if (this.options.autoRefresh && config.autoRefresh !== false) {
|
||||
this.refresh();
|
||||
}
|
||||
} else {
|
||||
// Error from server
|
||||
const errorMessage = config.errorToast || config.errorMessage ||
|
||||
(handler?.errorMessages?.[action]) ||
|
||||
data.message ||
|
||||
`Failed to ${action}`;
|
||||
this.showToast(errorMessage, 'error');
|
||||
this.resetLoading(element);
|
||||
}
|
||||
} catch (error) {
|
||||
this.handleError(error, element, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get action configuration from element attributes and handler
|
||||
*/
|
||||
getActionConfig(action, element, handler) {
|
||||
const config = {
|
||||
action: action,
|
||||
url: element.dataset.actionUrl,
|
||||
handler: element.dataset.actionHandler,
|
||||
method: element.dataset.actionMethod || 'POST',
|
||||
confirm: element.dataset.actionConfirm,
|
||||
loadingText: element.dataset.actionLoadingText,
|
||||
successToast: element.dataset.actionSuccessToast,
|
||||
errorToast: element.dataset.actionErrorToast,
|
||||
type: element.dataset.actionType,
|
||||
windowTarget: element.dataset.actionWindowTarget,
|
||||
autoRefresh: element.dataset.actionAutoRefresh !== 'false',
|
||||
headers: {},
|
||||
body: {}
|
||||
};
|
||||
|
||||
// Merge with handler config if available
|
||||
if (handler) {
|
||||
// Don't override explicit URL, but use template if no URL set
|
||||
if (!config.url && handler.urlTemplate) {
|
||||
config.url = handler.urlTemplate;
|
||||
}
|
||||
if (handler.confirmations?.[action]) {
|
||||
config.confirm = config.confirm || handler.confirmations[action];
|
||||
}
|
||||
if (handler.loadingTexts?.[action]) {
|
||||
config.loadingText = config.loadingText || handler.loadingTexts[action];
|
||||
}
|
||||
if (handler.successMessages?.[action]) {
|
||||
config.successToast = config.successToast || handler.successMessages[action];
|
||||
}
|
||||
if (handler.errorMessages?.[action]) {
|
||||
config.errorToast = config.errorToast || handler.errorMessages[action];
|
||||
}
|
||||
}
|
||||
|
||||
// Extract parameters from data-action-param-* attributes for request body
|
||||
Object.keys(element.dataset).forEach(key => {
|
||||
if (key.startsWith('actionParam')) {
|
||||
// Convert camelCase to lowercase (e.g., actionParamId -> id)
|
||||
const paramName = key.replace(/^actionParam/, '').replace(/([A-Z])/g, '-$1').toLowerCase();
|
||||
config.body[paramName] = element.dataset[key];
|
||||
}
|
||||
});
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process URL template with placeholders
|
||||
*/
|
||||
processUrlTemplate(url, element) {
|
||||
if (!url) return url;
|
||||
|
||||
// Replace {action} placeholder
|
||||
url = url.replace('{action}', element.dataset.action || '');
|
||||
|
||||
// Replace {id} placeholder - check multiple sources
|
||||
if (url.includes('{id}')) {
|
||||
// Try data-action-param-id (camelCase from dataset)
|
||||
const id = element.dataset.actionParamId ||
|
||||
// Try data-container-id (for backward compatibility)
|
||||
element.dataset.containerId ||
|
||||
// Try data-id
|
||||
element.dataset.id ||
|
||||
// Try data-action-id
|
||||
element.dataset.actionId ||
|
||||
// Try data-action-param-id as kebab-case attribute
|
||||
element.getAttribute('data-action-param-id');
|
||||
|
||||
if (id) {
|
||||
url = url.replace(/\{id\}/g, id);
|
||||
} else {
|
||||
console.warn(`[ActionHandler] Missing ID for URL template: ${url}`, element);
|
||||
}
|
||||
}
|
||||
|
||||
// Replace {param:name} placeholders
|
||||
url = url.replace(/\{param:(\w+)\}/g, (match, paramName) => {
|
||||
// Try camelCase (dataset converts kebab-case to camelCase)
|
||||
const camelCase = `actionParam${paramName.charAt(0).toUpperCase() + paramName.slice(1)}`;
|
||||
const value = element.dataset[camelCase] ||
|
||||
element.dataset[`actionParam${paramName}`] ||
|
||||
element.dataset[paramName] ||
|
||||
// Try kebab-case attribute
|
||||
element.getAttribute(`data-action-param-${paramName}`);
|
||||
return value || match;
|
||||
});
|
||||
|
||||
// Replace {data:name} placeholders
|
||||
url = url.replace(/\{data:(\w+)\}/g, (match, attrName) => {
|
||||
// Try camelCase from dataset
|
||||
const camelCase = attrName.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
|
||||
return element.dataset[camelCase] ||
|
||||
element.dataset[attrName] ||
|
||||
element.getAttribute(`data-${attrName}`) ||
|
||||
match;
|
||||
});
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get CSRF token from various sources
|
||||
*/
|
||||
getCsrfToken(element) {
|
||||
// Try element itself
|
||||
if (element.dataset.csrfToken) {
|
||||
return {
|
||||
token: element.dataset.csrfToken,
|
||||
formId: this.getFormId(element)
|
||||
};
|
||||
}
|
||||
|
||||
// Try closest LiveComponent
|
||||
const componentElement = element.closest(this.options.csrfTokenSelector);
|
||||
if (componentElement?.dataset.csrfToken) {
|
||||
return {
|
||||
token: componentElement.dataset.csrfToken,
|
||||
formId: componentElement.dataset.liveComponent
|
||||
? `livecomponent:${componentElement.dataset.liveComponent}`
|
||||
: this.getFormId(element)
|
||||
};
|
||||
}
|
||||
|
||||
// Try container
|
||||
if (this.container?.dataset.csrfToken) {
|
||||
return {
|
||||
token: this.container.dataset.csrfToken,
|
||||
formId: this.getFormId(element)
|
||||
};
|
||||
}
|
||||
|
||||
// Try meta tag
|
||||
const metaToken = document.querySelector('meta[name="csrf-token"]');
|
||||
if (metaToken) {
|
||||
return {
|
||||
token: metaToken.content,
|
||||
formId: this.getFormId(element)
|
||||
};
|
||||
}
|
||||
|
||||
// Fallback
|
||||
return {
|
||||
token: '',
|
||||
formId: this.getFormId(element)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate form ID for CSRF validation
|
||||
*/
|
||||
getFormId(element) {
|
||||
// If LiveComponent available, use component ID
|
||||
const componentElement = element.closest('[data-live-component]');
|
||||
if (componentElement?.dataset.liveComponent) {
|
||||
return `livecomponent:${componentElement.dataset.liveComponent}`;
|
||||
}
|
||||
|
||||
// Generate from URL
|
||||
const url = element.dataset.actionUrl;
|
||||
if (url) {
|
||||
// Extract path from URL
|
||||
const path = url.split('?')[0];
|
||||
return `action:${path}`;
|
||||
}
|
||||
|
||||
// Fallback
|
||||
return `action:${element.dataset.action}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show loading state on button
|
||||
*/
|
||||
showLoading(element, text) {
|
||||
element.dataset.originalText = element.textContent;
|
||||
element.disabled = true;
|
||||
element.textContent = text;
|
||||
element.style.opacity = '0.6';
|
||||
element.style.cursor = 'not-allowed';
|
||||
element.classList.add('action-loading');
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset loading state
|
||||
*/
|
||||
resetLoading(element) {
|
||||
element.disabled = false;
|
||||
element.textContent = element.dataset.originalText || element.textContent;
|
||||
element.style.opacity = '1';
|
||||
element.style.cursor = 'pointer';
|
||||
element.classList.remove('action-loading');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show confirmation dialog
|
||||
*/
|
||||
async showConfirmation(message) {
|
||||
if (this.options.confirmationHandler) {
|
||||
return await this.options.confirmationHandler(message);
|
||||
}
|
||||
return confirm(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show toast notification
|
||||
*/
|
||||
showToast(message, type = 'info') {
|
||||
if (this.options.toastHandler) {
|
||||
this.options.toastHandler(message, type);
|
||||
return;
|
||||
}
|
||||
|
||||
// Try LiveComponentUIHelper
|
||||
if (window.LiveComponentUIHelper) {
|
||||
const componentElement = document.querySelector(this.options.csrfTokenSelector);
|
||||
const componentId = componentElement?.dataset.liveComponent || 'global';
|
||||
window.LiveComponentUIHelper.showNotification(componentId, {
|
||||
message: message,
|
||||
type: type,
|
||||
duration: 5000
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Try global showToast
|
||||
if (typeof window.showToast === 'function') {
|
||||
window.showToast(message, type);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback: Simple alert
|
||||
if (type === 'error') {
|
||||
alert(`Error: ${message}`);
|
||||
} else {
|
||||
console.log(`[${type.toUpperCase()}] ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh page or component
|
||||
*/
|
||||
refresh() {
|
||||
if (this.options.refreshHandler) {
|
||||
this.options.refreshHandler();
|
||||
return;
|
||||
}
|
||||
|
||||
// Try LiveComponent refresh
|
||||
const componentElement = document.querySelector(this.options.csrfTokenSelector);
|
||||
if (componentElement?.dataset.liveComponent) {
|
||||
const componentId = componentElement.dataset.liveComponent;
|
||||
if (window.LiveComponent && typeof window.LiveComponent.refresh === 'function') {
|
||||
window.LiveComponent.refresh(componentId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Reload page
|
||||
setTimeout(() => window.location.reload(), 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle errors
|
||||
*/
|
||||
handleError(error, element, config) {
|
||||
console.error('[ActionHandler] Error:', error);
|
||||
|
||||
const errorMessage = config.errorToast ||
|
||||
config.errorMessage ||
|
||||
`Error: ${error.message}`;
|
||||
|
||||
this.showToast(errorMessage, 'error');
|
||||
this.resetLoading(element);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape HTML to prevent XSS
|
||||
*/
|
||||
escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
}
|
||||
|
||||
104
resources/js/modules/common/ActionHandlers.js
Normal file
104
resources/js/modules/common/ActionHandlers.js
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Predefined Action Handlers
|
||||
*
|
||||
* Contains configuration for common action patterns
|
||||
*/
|
||||
|
||||
/**
|
||||
* Docker Container Handler
|
||||
*/
|
||||
export const dockerContainerHandler = {
|
||||
urlTemplate: '/admin/infrastructure/docker/api/containers/{id}/{action}',
|
||||
method: 'POST',
|
||||
confirmations: {
|
||||
stop: 'Are you sure you want to stop this container?',
|
||||
restart: 'Are you sure you want to restart this container?'
|
||||
},
|
||||
loadingTexts: {
|
||||
start: 'Starting...',
|
||||
stop: 'Stopping...',
|
||||
restart: 'Restarting...',
|
||||
reload: 'Reloading...',
|
||||
logs: 'Loading logs...'
|
||||
},
|
||||
successMessages: {
|
||||
start: 'Container started successfully',
|
||||
stop: 'Container stopped successfully',
|
||||
restart: 'Container restarted successfully',
|
||||
reload: 'Container reloaded successfully'
|
||||
},
|
||||
errorMessages: {
|
||||
start: 'Failed to start container',
|
||||
stop: 'Failed to stop container',
|
||||
restart: 'Failed to restart container',
|
||||
reload: 'Failed to reload container'
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Generic API Handler
|
||||
*/
|
||||
export const genericApiHandler = {
|
||||
urlTemplate: '/api/{entity}/{id}/{action}',
|
||||
method: 'POST',
|
||||
confirmations: {
|
||||
delete: 'Are you sure you want to delete this item?'
|
||||
},
|
||||
loadingTexts: {
|
||||
delete: 'Deleting...',
|
||||
update: 'Updating...',
|
||||
create: 'Creating...'
|
||||
},
|
||||
successMessages: {
|
||||
delete: 'Item deleted successfully',
|
||||
update: 'Item updated successfully',
|
||||
create: 'Item created successfully'
|
||||
},
|
||||
errorMessages: {
|
||||
delete: 'Failed to delete item',
|
||||
update: 'Failed to update item',
|
||||
create: 'Failed to create item'
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Bulk Operations Handler
|
||||
*/
|
||||
export const bulkOperationsHandler = {
|
||||
urlTemplate: '/admin/api/{entity}/bulk/{action}',
|
||||
method: 'POST',
|
||||
confirmations: {
|
||||
delete: 'Are you sure you want to delete the selected items?',
|
||||
publish: 'Are you sure you want to publish the selected items?',
|
||||
unpublish: 'Are you sure you want to unpublish the selected items?'
|
||||
},
|
||||
loadingTexts: {
|
||||
delete: 'Deleting...',
|
||||
publish: 'Publishing...',
|
||||
unpublish: 'Unpublishing...',
|
||||
tag: 'Tagging...'
|
||||
},
|
||||
successMessages: {
|
||||
delete: 'Items deleted successfully',
|
||||
publish: 'Items published successfully',
|
||||
unpublish: 'Items unpublished successfully',
|
||||
tag: 'Items tagged successfully'
|
||||
},
|
||||
errorMessages: {
|
||||
delete: 'Failed to delete items',
|
||||
publish: 'Failed to publish items',
|
||||
unpublish: 'Failed to unpublish items',
|
||||
tag: 'Failed to tag items'
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Default handler for actions without specific handler
|
||||
*/
|
||||
export const defaultHandler = {
|
||||
method: 'POST',
|
||||
loadingTexts: {
|
||||
default: 'Processing...'
|
||||
}
|
||||
};
|
||||
|
||||
98
resources/js/modules/common/index.js
Normal file
98
resources/js/modules/common/index.js
Normal file
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Common Utilities Module
|
||||
*
|
||||
* Provides shared utilities and helpers used across the application
|
||||
*/
|
||||
|
||||
import { ActionHandler } from './ActionHandler.js';
|
||||
import { dockerContainerHandler, genericApiHandler, bulkOperationsHandler, defaultHandler } from './ActionHandlers.js';
|
||||
|
||||
// Export ActionHandler and handlers
|
||||
export { ActionHandler };
|
||||
export { dockerContainerHandler, genericApiHandler, bulkOperationsHandler, defaultHandler };
|
||||
|
||||
// Make ActionHandler globally available for easy access
|
||||
if (typeof window !== 'undefined') {
|
||||
window.ActionHandler = ActionHandler;
|
||||
window.ActionHandlers = {
|
||||
dockerContainer: dockerContainerHandler,
|
||||
genericApi: genericApiHandler,
|
||||
bulkOperations: bulkOperationsHandler,
|
||||
default: defaultHandler
|
||||
};
|
||||
}
|
||||
|
||||
// Framework module definition
|
||||
export const definition = {
|
||||
name: 'common',
|
||||
version: '1.0.0',
|
||||
dependencies: [],
|
||||
provides: ['ActionHandler'],
|
||||
priority: 0
|
||||
};
|
||||
|
||||
// Framework module initialization
|
||||
export async function init(config = {}, state = {}) {
|
||||
console.log('[Common] Module initialized');
|
||||
|
||||
// Auto-initialize ActionHandlers for elements with data-action-handler attribute
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const containers = document.querySelectorAll('[data-action-handler-container]');
|
||||
containers.forEach(container => {
|
||||
const selector = container.dataset.actionHandlerContainer || container.className.split(' ')[0];
|
||||
const handlerName = container.dataset.actionHandler || 'default';
|
||||
|
||||
const handler = new ActionHandler(selector, {
|
||||
csrfTokenSelector: '[data-live-component]',
|
||||
autoRefresh: true
|
||||
});
|
||||
|
||||
// Register handler if specified
|
||||
if (handlerName && window.ActionHandlers[handlerName]) {
|
||||
handler.registerHandler(handlerName, window.ActionHandlers[handlerName]);
|
||||
}
|
||||
|
||||
// Store handler on element for debugging
|
||||
container.actionHandler = handler;
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
ActionHandler,
|
||||
handlers: {
|
||||
dockerContainer: dockerContainerHandler,
|
||||
genericApi: genericApiHandler,
|
||||
bulkOperations: bulkOperationsHandler,
|
||||
default: defaultHandler
|
||||
},
|
||||
state
|
||||
};
|
||||
}
|
||||
|
||||
// Framework DOM element initialization
|
||||
export function initElement(element, options = {}) {
|
||||
// Check if element needs ActionHandler
|
||||
if (element.hasAttribute('data-action-handler-container')) {
|
||||
const selector = element.dataset.actionHandlerContainer || `.${element.className.split(' ')[0]}`;
|
||||
const handlerName = element.dataset.actionHandler || 'default';
|
||||
|
||||
const handler = new ActionHandler(selector, {
|
||||
csrfTokenSelector: '[data-live-component]',
|
||||
autoRefresh: true,
|
||||
...options
|
||||
});
|
||||
|
||||
// Register handler if specified
|
||||
if (handlerName && window.ActionHandlers?.[handlerName]) {
|
||||
handler.registerHandler(handlerName, window.ActionHandlers[handlerName]);
|
||||
}
|
||||
|
||||
// Store handler on element
|
||||
element.actionHandler = handler;
|
||||
|
||||
return handler;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -16,7 +16,7 @@ export class CsrfManager {
|
||||
headerName: config.headerName || 'X-CSRF-TOKEN',
|
||||
refreshInterval: config.refreshInterval || 30 * 60 * 1000, // 30 minutes
|
||||
autoRefresh: config.autoRefresh ?? true,
|
||||
endpoint: config.endpoint || '/api/csrf-token',
|
||||
endpoint: config.endpoint || '/api/csrf/token',
|
||||
...config
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user