Enhance Checkpoints Manager: Implement API integration for checkpoints, add filtering and sorting options, and improve UI components for better user experience

This commit is contained in:
Will Miao
2025-04-10 16:04:08 +08:00
parent 048d486fa6
commit 252e90a633
10 changed files with 877 additions and 41 deletions

View File

@@ -0,0 +1,247 @@
import { state, getCurrentPageState } from '../state/index.js';
import { showToast } from '../utils/uiHelpers.js';
import { confirmDelete } from '../utils/modalUtils.js';
import { createCheckpointCard } from '../components/CheckpointCard.js';
// Load more checkpoints with pagination
export async function loadMoreCheckpoints(resetPagination = true) {
try {
const pageState = getCurrentPageState();
// Don't load if we're already loading or there are no more items
if (pageState.isLoading || (!resetPagination && !pageState.hasMore)) {
return;
}
// Set loading state
pageState.isLoading = true;
document.body.classList.add('loading');
// Reset pagination if requested
if (resetPagination) {
pageState.currentPage = 1;
const grid = document.getElementById('checkpointGrid');
if (grid) grid.innerHTML = '';
}
// Build API URL with parameters
const params = new URLSearchParams({
page: pageState.currentPage,
page_size: pageState.pageSize || 20,
sort: pageState.sortBy || 'name'
});
// Add folder filter if active
if (pageState.activeFolder) {
params.append('folder', pageState.activeFolder);
}
// Add search if available
if (pageState.filters && pageState.filters.search) {
params.append('search', pageState.filters.search);
// Add search options
if (pageState.searchOptions) {
params.append('search_filename', pageState.searchOptions.filename.toString());
params.append('search_modelname', pageState.searchOptions.modelname.toString());
params.append('recursive', pageState.searchOptions.recursive.toString());
}
}
// Add base model filters
if (pageState.filters && pageState.filters.baseModel && pageState.filters.baseModel.length > 0) {
pageState.filters.baseModel.forEach(model => {
params.append('base_model', model);
});
}
// Add tags filters
if (pageState.filters && pageState.filters.tags && pageState.filters.tags.length > 0) {
pageState.filters.tags.forEach(tag => {
params.append('tag', tag);
});
}
// Execute fetch
const response = await fetch(`/api/checkpoints?${params.toString()}`);
if (!response.ok) {
throw new Error(`Failed to load checkpoints: ${response.status} ${response.statusText}`);
}
const data = await response.json();
// Update state with response data
pageState.hasMore = data.page < data.total_pages;
// Update UI with checkpoints
const grid = document.getElementById('checkpointGrid');
if (!grid) {
return;
}
// Clear grid if this is the first page
if (resetPagination) {
grid.innerHTML = '';
}
// Check for empty result
if (data.items.length === 0 && resetPagination) {
grid.innerHTML = `
<div class="placeholder-message">
<p>No checkpoints found</p>
<p>Add checkpoints to your models folders to see them here.</p>
</div>
`;
return;
}
// Render checkpoint cards
data.items.forEach(checkpoint => {
const card = createCheckpointCard(checkpoint);
grid.appendChild(card);
});
} catch (error) {
console.error('Error loading checkpoints:', error);
showToast('Failed to load checkpoints', 'error');
} finally {
// Clear loading state
const pageState = getCurrentPageState();
pageState.isLoading = false;
document.body.classList.remove('loading');
}
}
// Reset and reload checkpoints
export async function resetAndReload() {
const pageState = getCurrentPageState();
pageState.currentPage = 1;
pageState.hasMore = true;
await loadMoreCheckpoints(true);
}
// Refresh checkpoints
export async function refreshCheckpoints() {
try {
showToast('Scanning for checkpoints...', 'info');
const response = await fetch('/api/checkpoints/scan');
if (!response.ok) {
throw new Error(`Failed to scan checkpoints: ${response.status} ${response.statusText}`);
}
await resetAndReload();
showToast('Checkpoints refreshed successfully', 'success');
} catch (error) {
console.error('Error refreshing checkpoints:', error);
showToast('Failed to refresh checkpoints', 'error');
}
}
// Delete a checkpoint
export function deleteCheckpoint(filePath) {
confirmDelete('Are you sure you want to delete this checkpoint?', () => {
_performDelete(filePath);
});
}
// Private function to perform the delete operation
async function _performDelete(filePath) {
try {
showToast('Deleting checkpoint...', 'info');
const response = await fetch('/api/model/delete', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
file_path: filePath,
model_type: 'checkpoint'
})
});
if (!response.ok) {
throw new Error(`Failed to delete checkpoint: ${response.status} ${response.statusText}`);
}
const data = await response.json();
if (data.success) {
// Remove the card from UI
const card = document.querySelector(`.lora-card[data-filepath="${filePath}"]`);
if (card) {
card.remove();
}
showToast('Checkpoint deleted successfully', 'success');
} else {
throw new Error(data.error || 'Failed to delete checkpoint');
}
} catch (error) {
console.error('Error deleting checkpoint:', error);
showToast(`Failed to delete checkpoint: ${error.message}`, 'error');
}
}
// Replace checkpoint preview
export function replaceCheckpointPreview(filePath) {
// Open file picker
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = async (e) => {
if (!e.target.files.length) return;
const file = e.target.files[0];
await _uploadPreview(filePath, file);
};
input.click();
}
// Upload a preview image
async function _uploadPreview(filePath, file) {
try {
showToast('Uploading preview...', 'info');
const formData = new FormData();
formData.append('file', file);
formData.append('file_path', filePath);
formData.append('model_type', 'checkpoint');
const response = await fetch('/api/model/preview', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`Failed to upload preview: ${response.status} ${response.statusText}`);
}
const data = await response.json();
if (data.success) {
// Update the preview in UI
const card = document.querySelector(`.lora-card[data-filepath="${filePath}"]`);
if (card) {
const img = card.querySelector('.card-preview img');
if (img) {
// Add timestamp to prevent caching
const timestamp = new Date().getTime();
if (data.preview_url) {
img.src = `${data.preview_url}?t=${timestamp}`;
} else {
img.src = `/api/model/preview_image?path=${encodeURIComponent(filePath)}&t=${timestamp}`;
}
}
}
showToast('Preview updated successfully', 'success');
} else {
throw new Error(data.error || 'Failed to update preview');
}
} catch (error) {
console.error('Error updating preview:', error);
showToast(`Failed to update preview: ${error.message}`, 'error');
}
}

View File

@@ -1,36 +1,128 @@
import { appCore } from './core.js';
import { state, initPageState } from './state/index.js';
import { state, getCurrentPageState } from './state/index.js';
import {
loadMoreCheckpoints,
resetAndReload,
refreshCheckpoints,
deleteCheckpoint,
replaceCheckpointPreview
} from './api/checkpointApi.js';
import {
restoreFolderFilter,
toggleFolder,
openCivitai,
showToast
} from './utils/uiHelpers.js';
import { confirmDelete, closeDeleteModal } from './utils/modalUtils.js';
import { toggleApiKeyVisibility } from './managers/SettingsManager.js';
import { initializeInfiniteScroll } from './utils/infiniteScroll.js';
import { setStorageItem, getStorageItem } from './utils/storageHelpers.js';
// Initialize the Checkpoints page
class CheckpointsPageManager {
constructor() {
// Initialize any necessary state
this.initialized = false;
// Get page state
this.pageState = getCurrentPageState();
// Set default values
this.pageState.pageSize = 20;
this.pageState.isLoading = false;
this.pageState.hasMore = true;
// Expose functions to window object
this._exposeGlobalFunctions();
}
_exposeGlobalFunctions() {
// API functions
window.loadCheckpoints = (reset = true) => this.loadCheckpoints(reset);
window.refreshCheckpoints = refreshCheckpoints;
window.deleteCheckpoint = deleteCheckpoint;
window.replaceCheckpointPreview = replaceCheckpointPreview;
// UI helper functions
window.toggleFolder = toggleFolder;
window.openCivitai = openCivitai;
window.confirmDelete = confirmDelete;
window.closeDeleteModal = closeDeleteModal;
window.toggleApiKeyVisibility = toggleApiKeyVisibility;
// Add reference to this manager
window.checkpointManager = this;
}
async initialize() {
if (this.initialized) return;
// Initialize event listeners
this._initEventListeners();
// Initialize page state
initPageState('checkpoints');
// Restore folder filters if available
restoreFolderFilter('checkpoints');
// Initialize core application
await appCore.initialize();
// Load sort preference
this._loadSortPreference();
// Initialize page-specific components
this._initializeWorkInProgress();
// Load initial checkpoints
await this.loadCheckpoints();
this.initialized = true;
// Initialize infinite scroll
initializeInfiniteScroll('checkpoints');
// Initialize common page features
appCore.initializePageFeatures();
console.log('Checkpoints Manager initialized');
}
_initializeWorkInProgress() {
// Add any work-in-progress specific initialization here
console.log('Checkpoints Manager is under development');
_initEventListeners() {
// Sort select handler
const sortSelect = document.getElementById('sortSelect');
if (sortSelect) {
sortSelect.addEventListener('change', async (e) => {
this.pageState.sortBy = e.target.value;
this._saveSortPreference(e.target.value);
await resetAndReload();
});
}
// Folder tags handler
document.querySelectorAll('.folder-tags .tag').forEach(tag => {
tag.addEventListener('click', toggleFolder);
});
// Refresh button handler
const refreshBtn = document.getElementById('refreshBtn');
if (refreshBtn) {
refreshBtn.addEventListener('click', () => refreshCheckpoints());
}
}
_loadSortPreference() {
const savedSort = getStorageItem('checkpoints_sort');
if (savedSort) {
this.pageState.sortBy = savedSort;
const sortSelect = document.getElementById('sortSelect');
if (sortSelect) {
sortSelect.value = savedSort;
}
}
}
_saveSortPreference(sortValue) {
setStorageItem('checkpoints_sort', sortValue);
}
// Load checkpoints with optional pagination reset
async loadCheckpoints(resetPage = true) {
await loadMoreCheckpoints(resetPage);
}
}
// Initialize everything when DOM is ready
document.addEventListener('DOMContentLoaded', async () => {
// Initialize core application
await appCore.initialize();
// Initialize checkpoints page
const checkpointsPage = new CheckpointsPageManager();
await checkpointsPage.initialize();
});

View File

@@ -0,0 +1,147 @@
import { showToast } from '../utils/uiHelpers.js';
import { state } from '../state/index.js';
import { CheckpointModal } from './CheckpointModal.js';
// Create an instance of the modal
const checkpointModal = new CheckpointModal();
export function createCheckpointCard(checkpoint) {
const card = document.createElement('div');
card.className = 'lora-card'; // Reuse the same class for styling
card.dataset.sha256 = checkpoint.sha256;
card.dataset.filepath = checkpoint.file_path;
card.dataset.name = checkpoint.model_name;
card.dataset.file_name = checkpoint.file_name;
card.dataset.folder = checkpoint.folder;
card.dataset.modified = checkpoint.modified;
card.dataset.file_size = checkpoint.file_size;
card.dataset.from_civitai = checkpoint.from_civitai;
card.dataset.base_model = checkpoint.base_model || 'Unknown';
// Store metadata if available
if (checkpoint.civitai) {
card.dataset.meta = JSON.stringify(checkpoint.civitai || {});
}
// Store tags if available
if (checkpoint.tags && Array.isArray(checkpoint.tags)) {
card.dataset.tags = JSON.stringify(checkpoint.tags);
}
// Determine preview URL
const previewUrl = checkpoint.preview_url || '/loras_static/images/no-preview.png';
const version = state.previewVersions ? state.previewVersions.get(checkpoint.file_path) : null;
const versionedPreviewUrl = version ? `${previewUrl}?t=${version}` : previewUrl;
card.innerHTML = `
<div class="card-preview">
<img src="${versionedPreviewUrl}" alt="${checkpoint.model_name}">
<div class="card-header">
<span class="base-model-label" title="${checkpoint.base_model || 'Unknown'}">
${checkpoint.base_model || 'Unknown'}
</span>
<div class="card-actions">
<i class="fas fa-globe"
title="${checkpoint.from_civitai ? 'View on Civitai' : 'Not available from Civitai'}"
${!checkpoint.from_civitai ? 'style="opacity: 0.5; cursor: not-allowed"' : ''}>
</i>
<i class="fas fa-trash"
title="Delete Model">
</i>
</div>
</div>
<div class="card-footer">
<div class="model-info">
<span class="model-name">${checkpoint.model_name}</span>
</div>
<div class="card-actions">
<i class="fas fa-image"
title="Replace Preview Image">
</i>
</div>
</div>
</div>
`;
// Main card click event
card.addEventListener('click', () => {
// Show checkpoint details modal
const checkpointMeta = {
sha256: card.dataset.sha256,
file_path: card.dataset.filepath,
model_name: card.dataset.name,
file_name: card.dataset.file_name,
folder: card.dataset.folder,
modified: card.dataset.modified,
file_size: parseInt(card.dataset.file_size || '0'),
from_civitai: card.dataset.from_civitai === 'true',
base_model: card.dataset.base_model,
preview_url: versionedPreviewUrl,
// Parse civitai metadata from the card's dataset
civitai: (() => {
try {
return JSON.parse(card.dataset.meta || '{}');
} catch (e) {
console.error('Failed to parse civitai metadata:', e);
return {}; // Return empty object on error
}
})(),
tags: (() => {
try {
return JSON.parse(card.dataset.tags || '[]');
} catch (e) {
console.error('Failed to parse tags:', e);
return []; // Return empty array on error
}
})()
};
checkpointModal.showCheckpointDetails(checkpointMeta);
});
// Civitai button click event
if (checkpoint.from_civitai) {
card.querySelector('.fa-globe')?.addEventListener('click', e => {
e.stopPropagation();
openCivitai(checkpoint.model_name);
});
}
// Delete button click event
card.querySelector('.fa-trash')?.addEventListener('click', e => {
e.stopPropagation();
deleteCheckpoint(checkpoint.file_path);
});
// Replace preview button click event
card.querySelector('.fa-image')?.addEventListener('click', e => {
e.stopPropagation();
replaceCheckpointPreview(checkpoint.file_path);
});
return card;
}
// These functions will be implemented in checkpointApi.js
function openCivitai(modelName) {
if (window.openCivitai) {
window.openCivitai(modelName);
} else {
console.log('Opening Civitai for:', modelName);
}
}
function deleteCheckpoint(filePath) {
if (window.deleteCheckpoint) {
window.deleteCheckpoint(filePath);
} else {
console.log('Delete checkpoint:', filePath);
}
}
function replaceCheckpointPreview(filePath) {
if (window.replaceCheckpointPreview) {
window.replaceCheckpointPreview(filePath);
} else {
console.log('Replace checkpoint preview:', filePath);
}
}

View File

@@ -0,0 +1,120 @@
import { showToast } from '../utils/uiHelpers.js';
import { modalManager } from '../managers/ModalManager.js';
/**
* CheckpointModal - Component for displaying checkpoint details
* This is a basic implementation that can be expanded in the future
*/
export class CheckpointModal {
constructor() {
this.modal = document.getElementById('checkpointModal');
this.modalTitle = document.getElementById('checkpointModalTitle');
this.modalContent = document.getElementById('checkpointModalContent');
this.currentCheckpoint = null;
// Initialize close events
this._initCloseEvents();
}
_initCloseEvents() {
if (!this.modal) return;
// Close button
const closeBtn = this.modal.querySelector('.close');
if (closeBtn) {
closeBtn.addEventListener('click', () => this.close());
}
// Click outside to close
this.modal.addEventListener('click', (e) => {
if (e.target === this.modal) {
this.close();
}
});
}
/**
* Show checkpoint details in the modal
* @param {Object} checkpoint - Checkpoint data
*/
showCheckpointDetails(checkpoint) {
if (!this.modal || !this.modalContent) {
console.error('Checkpoint modal elements not found');
return;
}
this.currentCheckpoint = checkpoint;
// Set modal title
if (this.modalTitle) {
this.modalTitle.textContent = checkpoint.model_name || 'Checkpoint Details';
}
// This is a basic implementation that can be expanded with more details
// For now, just display some basic information
this.modalContent.innerHTML = `
<div class="checkpoint-details">
<div class="checkpoint-preview">
<img src="${checkpoint.preview_url || '/loras_static/images/no-preview.png'}"
alt="${checkpoint.model_name}" />
</div>
<div class="checkpoint-info">
<h3>${checkpoint.model_name}</h3>
<div class="info-grid">
<div class="info-row">
<span class="info-label">File Name:</span>
<span class="info-value">${checkpoint.file_name}</span>
</div>
<div class="info-row">
<span class="info-label">Location:</span>
<span class="info-value">${checkpoint.folder}</span>
</div>
<div class="info-row">
<span class="info-label">Base Model:</span>
<span class="info-value">${checkpoint.base_model || 'Unknown'}</span>
</div>
<div class="info-row">
<span class="info-label">File Size:</span>
<span class="info-value">${this._formatFileSize(checkpoint.file_size)}</span>
</div>
<div class="info-row">
<span class="info-label">SHA256:</span>
<span class="info-value sha-value">${checkpoint.sha256 || 'Unknown'}</span>
</div>
</div>
</div>
</div>
<div class="placeholder-message">
<p>Detailed checkpoint information will be implemented in a future update.</p>
</div>
`;
// Show the modal
this.modal.style.display = 'block';
}
/**
* Close the modal
*/
close() {
if (this.modal) {
this.modal.style.display = 'none';
this.currentCheckpoint = null;
}
}
/**
* Format file size for display
* @param {number} bytes - File size in bytes
* @returns {string} - Formatted file size
*/
_formatFileSize(bytes) {
if (!bytes) return 'Unknown';
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Bytes';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
if (i === 0) return `${bytes} ${sizes[i]}`;
return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
}
}

View File

@@ -70,6 +70,8 @@ export class FilterManager {
let tagsEndpoint = '/api/loras/top-tags?limit=20';
if (this.currentPage === 'recipes') {
tagsEndpoint = '/api/recipes/top-tags?limit=20';
} else if (this.currentPage === 'checkpoints') {
tagsEndpoint = '/api/checkpoints/top-tags?limit=20';
}
const response = await fetch(tagsEndpoint);
@@ -143,7 +145,8 @@ export class FilterManager {
apiEndpoint = '/api/loras/base-models';
} else if (this.currentPage === 'recipes') {
apiEndpoint = '/api/recipes/base-models';
} else {
} else if (this.currentPage === 'checkpoints') {
apiEndpoint = '/api/checkpoints/base-models';
return; // No API endpoint for other pages
}

View File

@@ -302,6 +302,7 @@ export class SearchManager {
pageState.searchOptions = {
filename: options.filename || false,
modelname: options.modelname || false,
tags: options.tags || false,
recursive: recursive
};
}