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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user