// 添加防抖函数
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// 优化排序功能
function sortCards(sortBy) {
const grid = document.getElementById('loraGrid');
if (!grid) return;
const fragment = document.createDocumentFragment();
const cards = Array.from(grid.children);
requestAnimationFrame(() => {
cards.sort((a, b) => {
if (sortBy === 'date') {
// 将字符串转换为浮点数进行比较
return parseFloat(b.dataset.modified) - parseFloat(a.dataset.modified);
} else {
// 名称排序保持不变
return a.dataset.name.localeCompare(b.dataset.name);
}
}).forEach(card => fragment.appendChild(card));
grid.appendChild(fragment);
});
}
// 改进WebSocket处理
class WebSocketClient {
constructor(url, options = {}) {
this.url = url;
this.options = {
reconnectDelay: 1000,
maxReconnectAttempts: 5,
...options
};
this.reconnectAttempts = 0;
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = this.onOpen.bind(this);
this.ws.onclose = this.onClose.bind(this);
this.ws.onerror = this.onError.bind(this);
this.ws.onmessage = this.onMessage.bind(this);
}
onOpen() {
this.reconnectAttempts = 0;
console.log('WebSocket connected');
}
onClose() {
if (this.reconnectAttempts < this.options.maxReconnectAttempts) {
setTimeout(() => {
this.reconnectAttempts++;
this.connect();
}, this.options.reconnectDelay);
}
}
onError(error) {
console.error('WebSocket error:', error);
}
onMessage(event) {
try {
const data = JSON.parse(event.data);
window.api.dispatchEvent(new CustomEvent('lora-scan-progress', { detail: data }));
} catch (error) {
console.error('Failed to parse WebSocket message:', error);
}
}
}
// 优化图片加载
function lazyLoadImages() {
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
if (img.dataset.src) {
img.src = img.dataset.src;
img.removeAttribute('data-src');
}
observer.unobserve(img);
}
});
});
document.querySelectorAll('img[data-src]').forEach(img => {
imageObserver.observe(img);
});
}
// 优化模态窗口
class ModalManager {
constructor() {
this.modal = document.getElementById('loraModal');
this.boundHandleEscape = this.handleEscape.bind(this);
this.boundHandleOutsideClick = this.handleOutsideClick.bind(this);
}
show(content) {
this.modal.innerHTML = content;
this.modal.style.display = 'block';
document.body.classList.add('modal-open');
document.addEventListener('keydown', this.boundHandleEscape);
this.modal.addEventListener('click', this.boundHandleOutsideClick);
}
close() {
this.modal.style.display = 'none';
document.body.classList.remove('modal-open');
document.removeEventListener('keydown', this.boundHandleEscape);
this.modal.removeEventListener('click', this.boundHandleOutsideClick);
}
handleEscape(e) {
if (e.key === 'Escape') this.close();
}
handleOutsideClick(e) {
if (e.target === this.modal) this.close();
}
}
// 初始化
document.addEventListener('DOMContentLoaded', () => {
const wsClient = new WebSocketClient(`ws://${window.location.host}/ws`);
const modalManager = new ModalManager();
// 优化搜索功能,添加防抖
const debouncedSearch = debounce((term) => {
const cards = document.querySelectorAll('.lora-card');
requestAnimationFrame(() => {
cards.forEach(card => {
const match = card.dataset.name.toLowerCase().includes(term) ||
card.dataset.folder.toLowerCase().includes(term);
card.style.display = match ? 'block' : 'none';
});
});
}, 250);
document.getElementById('searchInput')?.addEventListener('input', (e) => {
debouncedSearch(e.target.value.toLowerCase());
});
// 初始化懒加载
lazyLoadImages();
// 优化滚动性能
document.addEventListener('scroll', debounce(() => {
lazyLoadImages();
}, 100), { passive: true });
});
// 刷新功能
async function refreshLoras() {
const loadingOverlay = document.getElementById('loading-overlay');
const loraGrid = document.getElementById('loraGrid');
const currentSort = document.getElementById('sortSelect').value;
const activeFolder = document.querySelector('.tag.active')?.dataset.folder;
try {
// Show loading overlay
loadingOverlay.style.display = 'flex';
// Fetch new data
const response = await fetch('/loras?refresh=true');
if (!response.ok) throw new Error('Refresh failed');
// Parse the HTML response
const parser = new DOMParser();
const doc = parser.parseFromString(await response.text(), 'text/html');
// Get the new lora cards
const newLoraGrid = doc.getElementById('loraGrid');
// Update the grid content
loraGrid.innerHTML = newLoraGrid.innerHTML;
// Re-attach click listeners to new cards
document.querySelectorAll('.lora-card').forEach(card => {
card.addEventListener('click', () => {
const meta = JSON.parse(card.dataset.meta || '{}');
if (Object.keys(meta).length > 0) {
showModal(meta);
}
});
});
// Re-apply current sorting
sortCards(currentSort);
// Modified folder filtering logic
if (activeFolder !== undefined) { // Check if there's an active folder
document.querySelectorAll('.lora-card').forEach(card => {
const cardFolder = card.getAttribute('data-folder');
// For empty folder (root directory), only show cards with empty folder path
if (activeFolder === '') {
card.style.display = cardFolder === '' ? '' : 'none';
} else {
// For other folders, show cards matching the folder path
card.style.display = cardFolder === activeFolder ? '' : 'none';
}
});
}
} catch (error) {
console.error('Refresh failed:', error);
alert('Failed to refresh loras');
} finally {
// Hide loading overlay
loadingOverlay.style.display = 'none';
}
}
// 占位功能函数
function openCivitai(modelName) {
// 从卡片的data-meta属性中获取civitai ID
const loraCard = document.querySelector(`.lora-card[data-name="${modelName}"]`);
if (!loraCard) return;
const metaData = JSON.parse(loraCard.dataset.meta);
const civitaiId = metaData.modelId; // 使用modelId作为civitai模型ID
const versionId = metaData.id; // 使用id作为版本ID
// 构建URL
if (civitaiId) {
let url = `https://civitai.com/models/${civitaiId}`;
if (versionId) {
url += `?modelVersionId=${versionId}`;
}
window.open(url, '_blank');
} else {
// 如果没有ID,尝试使用名称搜索
window.open(`https://civitai.com/models?query=${encodeURIComponent(modelName)}`, '_blank');
}
}
let pendingDeletePath = null;
function showDeleteModal(filePath) {
event.stopPropagation();
pendingDeletePath = filePath;
const card = document.querySelector(`.lora-card[data-filepath="${filePath}"]`);
const modelName = card.dataset.name;
const modal = document.getElementById('deleteModal');
const modelInfo = modal.querySelector('.delete-model-info');
// Format the info with better structure
modelInfo.innerHTML = `
Model: ${modelName}
File: ${filePath}
`;
modal.classList.add('show'); // Use class instead of style.display
document.body.classList.add('modal-open');
// Add click outside to close
modal.onclick = function(event) {
if (event.target === modal) {
closeDeleteModal();
}
};
}
function closeDeleteModal() {
const modal = document.getElementById('deleteModal');
modal.classList.remove('show'); // Use class instead of style.display
document.body.classList.remove('modal-open');
pendingDeletePath = null;
}
async function confirmDelete() {
if (!pendingDeletePath) return;
const modal = document.getElementById('deleteModal');
const card = document.querySelector(`.lora-card[data-filepath="${pendingDeletePath}"]`);
try {
const response = await fetch('/api/delete_model', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
file_path: pendingDeletePath
})
});
if (response.ok) {
if (card) {
card.remove();
}
closeDeleteModal();
} else {
const error = await response.text();
alert(`Failed to delete model: ${error}`);
}
} catch (error) {
alert(`Error deleting model: ${error}`);
}
}
// Replace the existing deleteModel function with this one
async function deleteModel(filePath) {
showDeleteModal(filePath);
}
// 初始化排序
document.getElementById('sortSelect')?.addEventListener('change', (e) => {
sortCards(e.target.value);
});
// 立即执行初始排序
const sortSelect = document.getElementById('sortSelect');
if (sortSelect) {
sortCards(sortSelect.value);
}
// 添加搜索功能
document.getElementById('searchInput')?.addEventListener('input', (e) => {
const term = e.target.value.toLowerCase();
document.querySelectorAll('.lora-card').forEach(card => {
const match = card.dataset.name.toLowerCase().includes(term) ||
card.dataset.folder.toLowerCase().includes(term);
card.style.display = match ? 'block' : 'none';
});
});
// 模态窗口管理
let currentLora = null;
let currentImageIndex = 0;
document.querySelectorAll('.lora-card').forEach(card => {
card.addEventListener('click', () => {
if (card.dataset.meta && Object.keys(JSON.parse(card.dataset.meta)).length > 0) {
currentLora = JSON.parse(card.dataset.meta);
showModal(currentLora);
}
});
});
function showModal(lora) {
const modal = document.getElementById('loraModal');
modal.innerHTML = `