Initial commit: FuZip - Application de fusion interactive de fichiers ZIP
- Backend PHP: architecture MVC avec API REST (upload, merge, preview, extract) - Frontend JavaScript: composants modulaires (arborescence, upload, themes, i18n) - Fonctionnalités: drag&drop, sélection exclusive, détection conflits, persistance état - Sécurité: validation stricte, isolation sessions, sanitization chemins - UI/UX: responsive, thèmes clair/sombre, multi-langue (FR/EN) - Documentation: README complet avec installation et utilisation
This commit is contained in:
754
assets/js/FileTreeRenderer.js
Normal file
754
assets/js/FileTreeRenderer.js
Normal file
@@ -0,0 +1,754 @@
|
||||
/**
|
||||
* FuZip - Rendu de l'arborescence de fichiers
|
||||
* Gère l'affichage hiérarchique, la sélection exclusive, les conflits
|
||||
*/
|
||||
|
||||
class FileTreeRenderer {
|
||||
constructor(side, container, app) {
|
||||
this.side = side; // 'left' ou 'right'
|
||||
this.container = container; // DOM element
|
||||
this.app = app; // Référence à FuZipApp pour accès à la sélection globale
|
||||
this.tree = null;
|
||||
this.filesList = [];
|
||||
this.conflicts = [];
|
||||
this.expandedFolders = new Set(); // Dossiers expand/collapsed
|
||||
this.searchQuery = '';
|
||||
|
||||
// Initialiser la barre de recherche
|
||||
this.initSearchBar();
|
||||
|
||||
console.log(`[FileTreeRenderer] Initialized for side: ${this.side}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise la barre de recherche
|
||||
*/
|
||||
initSearchBar() {
|
||||
// Trouver le champ de recherche dans le même panel
|
||||
const panel = this.container.closest('.tree-panel');
|
||||
if (!panel) return;
|
||||
|
||||
const searchInput = panel.querySelector('.search-input');
|
||||
if (!searchInput) return;
|
||||
|
||||
// Créer un wrapper pour le champ de recherche
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'search-input-wrapper';
|
||||
|
||||
// Remplacer le searchInput par le wrapper dans le DOM
|
||||
searchInput.parentElement.insertBefore(wrapper, searchInput);
|
||||
wrapper.appendChild(searchInput);
|
||||
|
||||
// Créer le bouton de réinitialisation
|
||||
const clearBtn = document.createElement('button');
|
||||
clearBtn.className = 'search-clear-btn hidden';
|
||||
clearBtn.type = 'button';
|
||||
clearBtn.title = 'Effacer la recherche';
|
||||
clearBtn.innerHTML = `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||
</svg>
|
||||
`;
|
||||
|
||||
// Ajouter le bouton dans le wrapper
|
||||
wrapper.appendChild(clearBtn);
|
||||
|
||||
// Événement de recherche en temps réel
|
||||
searchInput.addEventListener('input', (e) => {
|
||||
const query = e.target.value.trim();
|
||||
|
||||
// Afficher/masquer le bouton X
|
||||
if (query) {
|
||||
clearBtn.classList.remove('hidden');
|
||||
} else {
|
||||
clearBtn.classList.add('hidden');
|
||||
}
|
||||
|
||||
this.search(query);
|
||||
});
|
||||
|
||||
// Événement clic sur le bouton X
|
||||
clearBtn.addEventListener('click', () => {
|
||||
searchInput.value = '';
|
||||
clearBtn.classList.add('hidden');
|
||||
this.search('');
|
||||
});
|
||||
|
||||
this.searchInput = searchInput;
|
||||
this.searchClearBtn = clearBtn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge et rend l'arborescence
|
||||
* @param {Object} structure - Structure de l'arbre depuis l'API
|
||||
* @param {Array} conflicts - Liste des chemins en conflit
|
||||
*/
|
||||
render(structure, conflicts = []) {
|
||||
this.tree = structure.tree || {};
|
||||
this.filesList = structure.files_list || [];
|
||||
this.conflicts = conflicts;
|
||||
|
||||
// Vide le container
|
||||
this.container.innerHTML = '';
|
||||
|
||||
// Si arbre vide
|
||||
if (this.filesList.length === 0) {
|
||||
this.renderEmpty();
|
||||
return;
|
||||
}
|
||||
|
||||
// Rend récursivement l'arbre (commence par les enfants de la racine)
|
||||
if (this.tree.children && Array.isArray(this.tree.children)) {
|
||||
this.renderChildren(this.tree.children, this.container, 1);
|
||||
}
|
||||
|
||||
// Restaurer l'état des checkboxes après le render
|
||||
this.updateAllCheckboxStates();
|
||||
|
||||
console.log(`[FileTreeRenderer] Rendered ${this.filesList.length} items for ${this.side}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Affiche un message d'arbre vide
|
||||
*/
|
||||
renderEmpty() {
|
||||
const emptyDiv = document.createElement('div');
|
||||
emptyDiv.className = 'tree-empty';
|
||||
emptyDiv.innerHTML = `
|
||||
<svg class="tree-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>
|
||||
</svg>
|
||||
<p class="tree-empty-text">Aucun fichier</p>
|
||||
`;
|
||||
this.container.appendChild(emptyDiv);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rend un tableau d'enfants
|
||||
* @param {Array} children - Tableau d'enfants
|
||||
* @param {HTMLElement} parentElement - Élément parent DOM
|
||||
* @param {number} level - Niveau de profondeur (pour indentation)
|
||||
*/
|
||||
renderChildren(children, parentElement, level) {
|
||||
// Trie : dossiers d'abord, puis fichiers, alphabétique
|
||||
const sortedChildren = [...children].sort((a, b) => {
|
||||
const isFileA = a.type === 'file';
|
||||
const isFileB = b.type === 'file';
|
||||
|
||||
if (isFileA !== isFileB) {
|
||||
return isFileA ? 1 : -1; // Dossiers avant fichiers
|
||||
}
|
||||
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
sortedChildren.forEach((childNode) => {
|
||||
this.renderNode(childNode, parentElement, level);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Rend un noeud de l'arbre
|
||||
* @param {Object} childNode - Noeud à rendre
|
||||
* @param {HTMLElement} parentElement - Élément parent DOM
|
||||
* @param {number} level - Niveau de profondeur (pour indentation)
|
||||
*/
|
||||
renderNode(childNode, parentElement, level) {
|
||||
const isFile = childNode.type === 'file';
|
||||
const name = childNode.name;
|
||||
const path = childNode.path;
|
||||
const isExpanded = this.expandedFolders.has(path);
|
||||
const isConflict = this.conflicts.includes(path);
|
||||
|
||||
// Filtre recherche
|
||||
const hasMatch = this.searchQuery ? this.matchesSearch(name, path) : true;
|
||||
const hasChildMatch = !isFile && this.searchQuery ? this.hasMatchingChildren(childNode) : false;
|
||||
|
||||
// Ne pas afficher si ni le noeud ni ses enfants ne matchent
|
||||
if (this.searchQuery && !hasMatch && !hasChildMatch) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Auto-expand les dossiers qui contiennent des résultats
|
||||
const shouldAutoExpand = this.searchQuery && !isFile && hasChildMatch;
|
||||
if (shouldAutoExpand && !this.expandedFolders.has(path)) {
|
||||
this.expandedFolders.add(path);
|
||||
}
|
||||
|
||||
// Créer l'élément tree-item
|
||||
const itemDiv = document.createElement('div');
|
||||
itemDiv.className = 'tree-item';
|
||||
itemDiv.setAttribute('data-level', level);
|
||||
itemDiv.setAttribute('data-path', path);
|
||||
itemDiv.setAttribute('data-type', isFile ? 'file' : 'folder');
|
||||
|
||||
if (isFile) {
|
||||
itemDiv.classList.add('file');
|
||||
} else {
|
||||
itemDiv.classList.add('folder');
|
||||
// Vérifier l'état après auto-expand
|
||||
const isFinallyExpanded = this.expandedFolders.has(path);
|
||||
itemDiv.classList.add(isFinallyExpanded ? 'expanded' : 'collapsed');
|
||||
}
|
||||
|
||||
if (isConflict) {
|
||||
itemDiv.classList.add('conflict');
|
||||
}
|
||||
|
||||
// Highlight si correspondance de recherche
|
||||
if (this.searchQuery && hasMatch) {
|
||||
itemDiv.classList.add('search-match');
|
||||
}
|
||||
|
||||
// Icône expand/collapse (seulement pour dossiers)
|
||||
const expandIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
||||
expandIcon.setAttribute('class', 'tree-expand');
|
||||
expandIcon.setAttribute('viewBox', '0 0 24 24');
|
||||
expandIcon.innerHTML = '<polyline points="9 18 15 12 9 6"></polyline>';
|
||||
|
||||
// Rendre l'item entier cliquable pour expand/collapse si c'est un dossier
|
||||
if (!isFile) {
|
||||
itemDiv.addEventListener('click', (e) => {
|
||||
// Ne déclencher que si on ne clique pas sur la checkbox
|
||||
if (e.target.closest('.tree-checkbox') || e.target.closest('input[type="checkbox"]')) {
|
||||
return;
|
||||
}
|
||||
console.log(`[FileTreeRenderer] Folder item clicked: ${path}`);
|
||||
this.toggleFolder(path, itemDiv);
|
||||
});
|
||||
}
|
||||
|
||||
// Checkbox (input caché + style custom)
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.setAttribute('data-path', path);
|
||||
|
||||
const checkboxSpan = document.createElement('span');
|
||||
checkboxSpan.className = 'tree-checkbox';
|
||||
|
||||
// Événement sur le checkbox caché
|
||||
checkbox.addEventListener('change', (e) => {
|
||||
e.stopPropagation();
|
||||
console.log(`[FileTreeRenderer] Checkbox clicked: ${path}, checked: ${checkbox.checked}`);
|
||||
this.handleCheckboxClick(path, checkbox.checked);
|
||||
});
|
||||
|
||||
// Événement sur le span visible pour propager le clic
|
||||
checkboxSpan.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
checkbox.checked = !checkbox.checked;
|
||||
checkbox.dispatchEvent(new Event('change'));
|
||||
});
|
||||
|
||||
// Icône fichier/dossier
|
||||
const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
||||
icon.setAttribute('class', isFile ? 'tree-icon file' : 'tree-icon folder');
|
||||
icon.setAttribute('viewBox', '0 0 24 24');
|
||||
|
||||
if (isFile) {
|
||||
icon.innerHTML = `
|
||||
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
|
||||
<polyline points="13 2 13 9 20 9"></polyline>
|
||||
`;
|
||||
} else {
|
||||
icon.innerHTML = `
|
||||
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>
|
||||
`;
|
||||
}
|
||||
|
||||
// Nom
|
||||
const nameSpan = document.createElement('span');
|
||||
nameSpan.className = 'tree-name';
|
||||
nameSpan.textContent = name;
|
||||
|
||||
// Taille (seulement pour fichiers)
|
||||
let sizeSpan = null;
|
||||
if (isFile && childNode.size !== undefined) {
|
||||
sizeSpan = document.createElement('span');
|
||||
sizeSpan.className = 'tree-size';
|
||||
sizeSpan.textContent = this.formatBytes(childNode.size);
|
||||
}
|
||||
|
||||
// Actions (preview et download) - seulement pour fichiers
|
||||
let actionsDiv = null;
|
||||
if (isFile) {
|
||||
actionsDiv = document.createElement('div');
|
||||
actionsDiv.className = 'tree-actions';
|
||||
|
||||
// Bouton preview
|
||||
const btnPreview = document.createElement('button');
|
||||
btnPreview.className = 'btn-item-action';
|
||||
btnPreview.title = 'Prévisualiser';
|
||||
|
||||
const svgPreview = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
||||
svgPreview.setAttribute('viewBox', '0 0 24 24');
|
||||
svgPreview.innerHTML = `
|
||||
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
|
||||
<circle cx="12" cy="12" r="3"></circle>
|
||||
`;
|
||||
btnPreview.appendChild(svgPreview);
|
||||
|
||||
btnPreview.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.app.previewManager.preview(this.side, path, name);
|
||||
});
|
||||
|
||||
// Bouton download
|
||||
const btnDownload = document.createElement('button');
|
||||
btnDownload.className = 'btn-item-action';
|
||||
btnDownload.title = 'Télécharger';
|
||||
|
||||
const svgDownload = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
||||
svgDownload.setAttribute('viewBox', '0 0 24 24');
|
||||
svgDownload.innerHTML = `
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
|
||||
<polyline points="7 10 12 15 17 10"></polyline>
|
||||
<line x1="12" y1="15" x2="12" y2="3"></line>
|
||||
`;
|
||||
btnDownload.appendChild(svgDownload);
|
||||
|
||||
btnDownload.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.app.previewManager.extract(this.side, path, name);
|
||||
});
|
||||
|
||||
actionsDiv.appendChild(btnPreview);
|
||||
actionsDiv.appendChild(btnDownload);
|
||||
}
|
||||
|
||||
// Assemblage
|
||||
itemDiv.appendChild(expandIcon);
|
||||
itemDiv.appendChild(checkbox);
|
||||
itemDiv.appendChild(checkboxSpan);
|
||||
itemDiv.appendChild(icon);
|
||||
itemDiv.appendChild(nameSpan);
|
||||
if (sizeSpan) {
|
||||
itemDiv.appendChild(sizeSpan);
|
||||
}
|
||||
if (actionsDiv) {
|
||||
itemDiv.appendChild(actionsDiv);
|
||||
}
|
||||
|
||||
parentElement.appendChild(itemDiv);
|
||||
|
||||
// Si dossier et expanded, rend les enfants
|
||||
// Vérifier directement dans expandedFolders (car isExpanded peut être obsolète après auto-expand)
|
||||
if (!isFile && this.expandedFolders.has(path) && childNode.children && Array.isArray(childNode.children)) {
|
||||
this.renderChildren(childNode.children, parentElement, level + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle expand/collapse d'un dossier
|
||||
* @param {string} path - Chemin du dossier
|
||||
* @param {HTMLElement} itemDiv - Élément DOM du dossier
|
||||
*/
|
||||
toggleFolder(path, itemDiv) {
|
||||
console.log(`[FileTreeRenderer] toggleFolder called for: ${path}`);
|
||||
|
||||
if (this.expandedFolders.has(path)) {
|
||||
console.log(`[FileTreeRenderer] Collapsing folder: ${path}`);
|
||||
this.expandedFolders.delete(path);
|
||||
itemDiv.classList.remove('expanded');
|
||||
itemDiv.classList.add('collapsed');
|
||||
|
||||
// Supprime les enfants affichés
|
||||
let nextSibling = itemDiv.nextElementSibling;
|
||||
while (nextSibling && parseInt(nextSibling.getAttribute('data-level')) > parseInt(itemDiv.getAttribute('data-level'))) {
|
||||
const toRemove = nextSibling;
|
||||
nextSibling = nextSibling.nextElementSibling;
|
||||
toRemove.remove();
|
||||
}
|
||||
} else {
|
||||
console.log(`[FileTreeRenderer] Expanding folder: ${path}`);
|
||||
this.expandedFolders.add(path);
|
||||
itemDiv.classList.remove('collapsed');
|
||||
itemDiv.classList.add('expanded');
|
||||
|
||||
// Re-render pour afficher les enfants
|
||||
const level = parseInt(itemDiv.getAttribute('data-level'));
|
||||
const node = this.findNodeByPath(this.tree, path);
|
||||
|
||||
console.log(`[FileTreeRenderer] Found node:`, node);
|
||||
|
||||
if (node && node.children && Array.isArray(node.children)) {
|
||||
console.log(`[FileTreeRenderer] Rendering ${node.children.length} children`);
|
||||
// Créer un fragment temporaire
|
||||
const tempDiv = document.createElement('div');
|
||||
this.renderChildren(node.children, tempDiv, level + 1);
|
||||
|
||||
// Insérer après l'item
|
||||
let nextSibling = itemDiv.nextElementSibling;
|
||||
while (tempDiv.firstChild) {
|
||||
if (nextSibling) {
|
||||
this.container.insertBefore(tempDiv.firstChild, nextSibling);
|
||||
} else {
|
||||
this.container.appendChild(tempDiv.firstChild);
|
||||
}
|
||||
}
|
||||
|
||||
// Restaurer l'état des checkboxes après l'insertion
|
||||
this.updateAllCheckboxStates();
|
||||
}
|
||||
}
|
||||
|
||||
// Sauvegarder l'état après toggle
|
||||
this.app.saveState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Trouve un noeud par son chemin dans l'arbre
|
||||
* @param {Object} tree - Arbre ou noeud
|
||||
* @param {string} targetPath - Chemin recherché
|
||||
* @returns {Object|null}
|
||||
*/
|
||||
findNodeByPath(tree, targetPath) {
|
||||
// Fonction récursive pour chercher dans un noeud
|
||||
const searchInNode = (node) => {
|
||||
// Si ce noeud correspond
|
||||
if (node.path === targetPath) {
|
||||
return node;
|
||||
}
|
||||
|
||||
// Si ce noeud a des enfants, chercher récursivement
|
||||
if (node.children && Array.isArray(node.children)) {
|
||||
for (const child of node.children) {
|
||||
const found = searchInNode(child);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
// Si tree est la racine avec un tableau children, commencer par là
|
||||
if (tree.children && Array.isArray(tree.children)) {
|
||||
for (const child of tree.children) {
|
||||
const found = searchInNode(child);
|
||||
if (found) return found;
|
||||
}
|
||||
} else {
|
||||
// Sinon chercher dans le noeud directement
|
||||
return searchInNode(tree);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gère le clic sur une checkbox (SÉLECTION EXCLUSIVE)
|
||||
* @param {string} path - Chemin du fichier/dossier
|
||||
* @param {boolean} checked - Nouvel état
|
||||
*/
|
||||
handleCheckboxClick(path, checked) {
|
||||
const newSelection = checked ? this.side : null;
|
||||
|
||||
// Sélection exclusive : si on sélectionne ici, on désélectionne de l'autre côté
|
||||
const currentSelection = this.app.state.selection.get(path);
|
||||
|
||||
if (checked && currentSelection && currentSelection !== this.side) {
|
||||
// Désélectionner de l'autre côté avec animation
|
||||
const otherSide = this.side === 'left' ? 'right' : 'left';
|
||||
const otherRenderer = this.side === 'left' ? this.app.treeRendererRight : this.app.treeRendererLeft;
|
||||
|
||||
if (otherRenderer) {
|
||||
otherRenderer.animateAutoDeselect(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Met à jour la sélection globale
|
||||
this.app.state.selection.set(path, newSelection);
|
||||
|
||||
// Propage aux enfants si c'est un dossier
|
||||
this.propagateSelectionToChildren(path, newSelection);
|
||||
|
||||
// Remonte pour mettre à jour les parents
|
||||
this.updateParentCheckboxes(path);
|
||||
|
||||
// Met à jour les états des checkboxes
|
||||
this.updateAllCheckboxStates();
|
||||
|
||||
// Notifie l'app
|
||||
this.app.onSelectionChanged();
|
||||
|
||||
console.log(`[FileTreeRenderer] ${this.side} - Selection: ${path} = ${newSelection}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Propage la sélection aux enfants
|
||||
* @param {string} parentPath - Chemin du parent
|
||||
* @param {string|null} selection - 'left', 'right', ou null
|
||||
*/
|
||||
propagateSelectionToChildren(parentPath, selection) {
|
||||
const node = this.findNodeByPath(this.tree, parentPath);
|
||||
|
||||
if (node && node.children && Array.isArray(node.children)) {
|
||||
const collectPaths = (children) => {
|
||||
const paths = [];
|
||||
children.forEach(child => {
|
||||
paths.push(child.path);
|
||||
if (child.children && Array.isArray(child.children)) {
|
||||
paths.push(...collectPaths(child.children));
|
||||
}
|
||||
});
|
||||
return paths;
|
||||
};
|
||||
|
||||
const childPaths = collectPaths(node.children);
|
||||
childPaths.forEach(childPath => {
|
||||
this.app.state.selection.set(childPath, selection);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour les checkboxes des parents en remontant la hiérarchie
|
||||
* @param {string} childPath - Chemin de l'enfant modifié
|
||||
*/
|
||||
updateParentCheckboxes(childPath) {
|
||||
// Trouve le parent en remontant le chemin
|
||||
const pathParts = childPath.split('/').filter(p => p);
|
||||
|
||||
// Remonte chaque niveau parent du plus profond au plus haut
|
||||
for (let i = pathParts.length - 1; i > 0; i--) {
|
||||
const parentPath = pathParts.slice(0, i).join('/') + '/';
|
||||
|
||||
const parentNode = this.findNodeByPath(this.tree, parentPath);
|
||||
|
||||
if (!parentNode || !parentNode.children || !Array.isArray(parentNode.children)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Vérifie l'état des enfants DIRECTS uniquement
|
||||
let allSelected = true;
|
||||
let noneSelected = true;
|
||||
|
||||
for (const child of parentNode.children) {
|
||||
const childSelection = this.app.state.selection.get(child.path);
|
||||
|
||||
if (childSelection === this.side) {
|
||||
noneSelected = false;
|
||||
} else {
|
||||
allSelected = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Décide de l'état du parent
|
||||
if (allSelected) {
|
||||
// Tous les enfants directs sélectionnés : parent coché
|
||||
this.app.state.selection.set(parentPath, this.side);
|
||||
console.log(`[FileTreeRenderer] Parent ${parentPath} checked (all children selected)`);
|
||||
} else if (noneSelected) {
|
||||
// Aucun enfant direct sélectionné : parent décoché
|
||||
this.app.state.selection.set(parentPath, null);
|
||||
console.log(`[FileTreeRenderer] Parent ${parentPath} unchecked (no children selected)`);
|
||||
} else {
|
||||
// Sélection partielle : parent décoché mais sera en état indeterminate visuellement
|
||||
this.app.state.selection.set(parentPath, null);
|
||||
console.log(`[FileTreeRenderer] Parent ${parentPath} indeterminate (partial selection)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour tous les états des checkboxes (checked, unchecked, indeterminate)
|
||||
*/
|
||||
updateAllCheckboxStates() {
|
||||
const checkboxes = this.container.querySelectorAll('input[type="checkbox"]');
|
||||
|
||||
checkboxes.forEach(checkbox => {
|
||||
const path = checkbox.getAttribute('data-path');
|
||||
const selection = this.app.state.selection.get(path);
|
||||
const itemDiv = checkbox.closest('.tree-item');
|
||||
const checkboxSpan = itemDiv.querySelector('.tree-checkbox');
|
||||
|
||||
// Réinitialise les classes
|
||||
checkboxSpan.classList.remove('checked', 'indeterminate');
|
||||
|
||||
if (selection === this.side) {
|
||||
checkbox.checked = true;
|
||||
checkboxSpan.classList.add('checked');
|
||||
} else {
|
||||
checkbox.checked = false;
|
||||
|
||||
// Si c'est un dossier, vérifie l'état indeterminate
|
||||
if (itemDiv.classList.contains('folder')) {
|
||||
const hasSelectedChildren = this.hasSelectedChildren(path);
|
||||
const hasUnselectedChildren = this.hasUnselectedChildren(path);
|
||||
|
||||
if (hasSelectedChildren && hasUnselectedChildren) {
|
||||
checkboxSpan.classList.add('indeterminate');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si un dossier a des enfants sélectionnés de ce côté
|
||||
* @param {string} folderPath
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasSelectedChildren(folderPath) {
|
||||
const node = this.findNodeByPath(this.tree, folderPath);
|
||||
if (!node || !node.children || !Array.isArray(node.children)) return false;
|
||||
|
||||
const collectPaths = (children) => {
|
||||
const paths = [];
|
||||
children.forEach(child => {
|
||||
paths.push(child.path);
|
||||
if (child.children && Array.isArray(child.children)) {
|
||||
paths.push(...collectPaths(child.children));
|
||||
}
|
||||
});
|
||||
return paths;
|
||||
};
|
||||
|
||||
const childPaths = collectPaths(node.children);
|
||||
return childPaths.some(path => this.app.state.selection.get(path) === this.side);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si un dossier a des enfants non sélectionnés
|
||||
* @param {string} folderPath
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasUnselectedChildren(folderPath) {
|
||||
const node = this.findNodeByPath(this.tree, folderPath);
|
||||
if (!node || !node.children || !Array.isArray(node.children)) return false;
|
||||
|
||||
const collectPaths = (children) => {
|
||||
const paths = [];
|
||||
children.forEach(child => {
|
||||
paths.push(child.path);
|
||||
if (child.children && Array.isArray(child.children)) {
|
||||
paths.push(...collectPaths(child.children));
|
||||
}
|
||||
});
|
||||
return paths;
|
||||
};
|
||||
|
||||
const childPaths = collectPaths(node.children);
|
||||
return childPaths.some(path => this.app.state.selection.get(path) !== this.side);
|
||||
}
|
||||
|
||||
/**
|
||||
* Anime la désélection automatique (pulse jaune) - SÉLECTION EXCLUSIVE
|
||||
* @param {string} path - Chemin du fichier à animer
|
||||
*/
|
||||
animateAutoDeselect(path) {
|
||||
const itemDiv = this.container.querySelector(`[data-path="${path}"]`);
|
||||
|
||||
if (itemDiv) {
|
||||
itemDiv.classList.add('auto-deselected');
|
||||
|
||||
// Retire la classe après l'animation
|
||||
setTimeout(() => {
|
||||
itemDiv.classList.remove('auto-deselected');
|
||||
}, 600);
|
||||
}
|
||||
|
||||
// Met à jour la checkbox
|
||||
const checkbox = this.container.querySelector(`input[data-path="${path}"]`);
|
||||
if (checkbox) {
|
||||
checkbox.checked = false;
|
||||
const checkboxSpan = checkbox.nextElementSibling;
|
||||
if (checkboxSpan) {
|
||||
checkboxSpan.classList.remove('checked');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filtre l'arbre par recherche
|
||||
* @param {string} query
|
||||
*/
|
||||
search(query) {
|
||||
this.searchQuery = query.toLowerCase();
|
||||
|
||||
// Réinitialiser l'auto-expansion à chaque changement de recherche
|
||||
// pour éviter l'accumulation de dossiers expanded
|
||||
this.expandedFolders.clear();
|
||||
|
||||
this.render({ tree: this.tree, files_list: this.filesList }, this.conflicts);
|
||||
|
||||
// Sauvegarder l'état après recherche
|
||||
this.app.saveState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si un nom/chemin correspond à la recherche
|
||||
* @param {string} name
|
||||
* @param {string} path
|
||||
* @returns {boolean}
|
||||
*/
|
||||
matchesSearch(name, path) {
|
||||
if (!this.searchQuery) return true;
|
||||
return name.toLowerCase().includes(this.searchQuery) ||
|
||||
path.toLowerCase().includes(this.searchQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie récursivement si un noeud a des enfants qui matchent la recherche
|
||||
* @param {Object} node - Noeud à vérifier
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasMatchingChildren(node) {
|
||||
if (!node.children || !Array.isArray(node.children)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const child of node.children) {
|
||||
// Si l'enfant matche directement
|
||||
if (this.matchesSearch(child.name, child.path)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Si l'enfant est un dossier, vérifier récursivement
|
||||
if (child.type === 'folder' && this.hasMatchingChildren(child)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formate les octets
|
||||
* @param {number} bytes
|
||||
* @returns {string}
|
||||
*/
|
||||
formatBytes(bytes) {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
/**
|
||||
* Réinitialise le renderer
|
||||
*/
|
||||
clear() {
|
||||
this.tree = null;
|
||||
this.filesList = [];
|
||||
this.conflicts = [];
|
||||
this.expandedFolders.clear();
|
||||
this.searchQuery = '';
|
||||
this.container.innerHTML = '';
|
||||
|
||||
// Vider le champ de recherche
|
||||
if (this.searchInput) {
|
||||
this.searchInput.value = '';
|
||||
}
|
||||
|
||||
// Masquer le bouton X
|
||||
if (this.searchClearBtn) {
|
||||
this.searchClearBtn.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export pour utilisation dans app.js
|
||||
window.FileTreeRenderer = FileTreeRenderer;
|
||||
105
assets/js/LanguageManager.js
Normal file
105
assets/js/LanguageManager.js
Normal file
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* FuZip - Gestionnaire de langue (Bilingual FR/EN)
|
||||
* Gère le toggle entre français et anglais avec persistance localStorage
|
||||
*/
|
||||
|
||||
class LanguageManager {
|
||||
constructor() {
|
||||
this.storageKey = 'fuzip_lang';
|
||||
this.currentLang = this.loadLang();
|
||||
this.btnToggle = document.getElementById('btn-lang-toggle');
|
||||
this.i18n = window.FUZIP_CONFIG?.i18n || {};
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise le gestionnaire de langue
|
||||
*/
|
||||
init() {
|
||||
// Écoute le clic sur le bouton toggle
|
||||
if (this.btnToggle) {
|
||||
this.btnToggle.addEventListener('click', () => this.toggle());
|
||||
}
|
||||
|
||||
// Synchronise le localStorage avec la langue actuelle de la page
|
||||
this.saveLang(this.currentLang);
|
||||
|
||||
console.log(`[LanguageManager] Initialized with lang: ${this.currentLang}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge la langue depuis localStorage ou depuis la config globale
|
||||
* @returns {string} 'fr' ou 'en'
|
||||
*/
|
||||
loadLang() {
|
||||
// Vérifie localStorage en premier
|
||||
const saved = localStorage.getItem(this.storageKey);
|
||||
if (saved === 'fr' || saved === 'en') {
|
||||
return saved;
|
||||
}
|
||||
|
||||
// Sinon utilise la langue de la config (depuis PHP)
|
||||
return window.FUZIP_CONFIG?.lang || 'fr';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sauvegarde la langue dans localStorage
|
||||
* @param {string} lang - 'fr' ou 'en'
|
||||
*/
|
||||
saveLang(lang) {
|
||||
if (lang === 'fr' || lang === 'en') {
|
||||
localStorage.setItem(this.storageKey, lang);
|
||||
this.currentLang = lang;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle entre français et anglais
|
||||
* Recharge la page avec le paramètre ?lang=XX
|
||||
*/
|
||||
toggle() {
|
||||
const newLang = this.currentLang === 'fr' ? 'en' : 'fr';
|
||||
this.saveLang(newLang);
|
||||
|
||||
// Recharge la page avec le nouveau paramètre lang
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('lang', newLang);
|
||||
window.location.href = url.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère la langue actuelle
|
||||
* @returns {string}
|
||||
*/
|
||||
getLang() {
|
||||
return this.currentLang;
|
||||
}
|
||||
|
||||
/**
|
||||
* Définit une langue spécifique
|
||||
* @param {string} lang - 'fr' ou 'en'
|
||||
*/
|
||||
setLang(lang) {
|
||||
if (lang === 'fr' || lang === 'en') {
|
||||
this.saveLang(lang);
|
||||
|
||||
// Recharge la page
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('lang', lang);
|
||||
window.location.href = url.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère une traduction depuis l'objet i18n
|
||||
* @param {string} key - Clé de traduction
|
||||
* @returns {string}
|
||||
*/
|
||||
t(key) {
|
||||
return this.i18n[key] || key;
|
||||
}
|
||||
}
|
||||
|
||||
// Export pour utilisation dans app.js
|
||||
window.LanguageManager = LanguageManager;
|
||||
139
assets/js/PreviewManager.js
Normal file
139
assets/js/PreviewManager.js
Normal file
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* FuZip - Gestionnaire de preview et extraction
|
||||
* Options A et D : Preview de fichiers et download individuel
|
||||
*/
|
||||
|
||||
class PreviewManager {
|
||||
constructor() {
|
||||
this.apiBase = window.FUZIP_CONFIG?.apiBase || '/api/';
|
||||
|
||||
// Éléments DOM de la modal
|
||||
this.modal = document.getElementById('preview-modal');
|
||||
this.modalTitle = document.getElementById('preview-title');
|
||||
this.modalContent = document.getElementById('preview-content');
|
||||
this.modalClose = document.getElementById('preview-close');
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise les événements
|
||||
*/
|
||||
init() {
|
||||
// Fermeture de la modal
|
||||
if (this.modalClose) {
|
||||
this.modalClose.addEventListener('click', () => this.closeModal());
|
||||
}
|
||||
|
||||
// Fermeture en cliquant à l'extérieur
|
||||
if (this.modal) {
|
||||
this.modal.addEventListener('click', (e) => {
|
||||
if (e.target === this.modal) {
|
||||
this.closeModal();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Fermeture avec Escape
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && this.modal && !this.modal.classList.contains('hidden')) {
|
||||
this.closeModal();
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[PreviewManager] Initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Prévisualise un fichier (Option A)
|
||||
* @param {string} side - 'left' ou 'right'
|
||||
* @param {string} path - Chemin du fichier
|
||||
* @param {string} fileName - Nom du fichier pour affichage
|
||||
*/
|
||||
async preview(side, path, fileName) {
|
||||
try {
|
||||
this.openModal(fileName, 'Chargement...');
|
||||
|
||||
const url = `${this.apiBase}preview.php?side=${side}&path=${encodeURIComponent(path)}&max_length=50000`;
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
let content = data.content || '';
|
||||
|
||||
// Si tronqué
|
||||
if (data.truncated) {
|
||||
content += `\n\n... (fichier tronqué à ${data.size_shown} octets sur ${data.total_size})`;
|
||||
}
|
||||
|
||||
// Si fichier binaire
|
||||
if (data.is_binary) {
|
||||
content = `[Fichier binaire - ${data.total_size} octets]\n\nAperçu non disponible pour ce type de fichier.`;
|
||||
}
|
||||
|
||||
this.modalContent.textContent = content;
|
||||
} else {
|
||||
this.modalContent.textContent = `Erreur : ${data.error || 'Impossible de charger le fichier'}`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[PreviewManager] Preview error:', error);
|
||||
this.modalContent.textContent = `Erreur réseau : ${error.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Télécharge un fichier individuel (Option D)
|
||||
* @param {string} side - 'left' ou 'right'
|
||||
* @param {string} path - Chemin du fichier
|
||||
* @param {string} fileName - Nom du fichier
|
||||
*/
|
||||
async extract(side, path, fileName) {
|
||||
try {
|
||||
const url = `${this.apiBase}extract.php?side=${side}&path=${encodeURIComponent(path)}`;
|
||||
|
||||
// Créer un lien de téléchargement temporaire
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = fileName;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
|
||||
console.log(`[PreviewManager] Extracted: ${fileName} from ${side}`);
|
||||
} catch (error) {
|
||||
console.error('[PreviewManager] Extract error:', error);
|
||||
alert(`Erreur lors du téléchargement : ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ouvre la modal de preview
|
||||
* @param {string} title - Titre (nom du fichier)
|
||||
* @param {string} content - Contenu initial
|
||||
*/
|
||||
openModal(title, content = '') {
|
||||
if (this.modalTitle) {
|
||||
this.modalTitle.textContent = title;
|
||||
}
|
||||
|
||||
if (this.modalContent) {
|
||||
this.modalContent.textContent = content;
|
||||
}
|
||||
|
||||
if (this.modal) {
|
||||
this.modal.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ferme la modal de preview
|
||||
*/
|
||||
closeModal() {
|
||||
if (this.modal) {
|
||||
this.modal.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export pour utilisation dans app.js
|
||||
window.PreviewManager = PreviewManager;
|
||||
112
assets/js/ThemeManager.js
Normal file
112
assets/js/ThemeManager.js
Normal file
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* FuZip - Gestionnaire de thème (Option E: Dark Mode)
|
||||
* Gère le toggle entre thème clair et sombre avec persistance localStorage
|
||||
*/
|
||||
|
||||
class ThemeManager {
|
||||
constructor() {
|
||||
this.storageKey = 'fuzip_theme';
|
||||
this.currentTheme = this.loadTheme();
|
||||
this.btnToggle = document.getElementById('btn-theme-toggle');
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise le gestionnaire de thème
|
||||
*/
|
||||
init() {
|
||||
// Applique le thème initial
|
||||
this.applyTheme(this.currentTheme);
|
||||
|
||||
// Écoute le clic sur le bouton toggle
|
||||
if (this.btnToggle) {
|
||||
this.btnToggle.addEventListener('click', () => this.toggle());
|
||||
}
|
||||
|
||||
// Écoute les changements de préférence système
|
||||
this.watchSystemPreference();
|
||||
|
||||
console.log(`[ThemeManager] Initialized with theme: ${this.currentTheme}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge le thème depuis localStorage ou détecte la préférence système
|
||||
* @returns {string} 'light' ou 'dark'
|
||||
*/
|
||||
loadTheme() {
|
||||
// Vérifie localStorage en premier
|
||||
const saved = localStorage.getItem(this.storageKey);
|
||||
if (saved === 'light' || saved === 'dark') {
|
||||
return saved;
|
||||
}
|
||||
|
||||
// Sinon détecte la préférence système
|
||||
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
|
||||
return 'dark';
|
||||
}
|
||||
|
||||
return 'light'; // Par défaut
|
||||
}
|
||||
|
||||
/**
|
||||
* Applique un thème
|
||||
* @param {string} theme - 'light' ou 'dark'
|
||||
*/
|
||||
applyTheme(theme) {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
this.currentTheme = theme;
|
||||
localStorage.setItem(this.storageKey, theme);
|
||||
|
||||
// Log pour debug
|
||||
console.log(`[ThemeManager] Theme applied: ${theme}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle entre light et dark
|
||||
*/
|
||||
toggle() {
|
||||
const newTheme = this.currentTheme === 'light' ? 'dark' : 'light';
|
||||
this.applyTheme(newTheme);
|
||||
}
|
||||
|
||||
/**
|
||||
* Écoute les changements de préférence système
|
||||
* (seulement si l'utilisateur n'a pas explicitement choisi un thème)
|
||||
*/
|
||||
watchSystemPreference() {
|
||||
if (!window.matchMedia) return;
|
||||
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
|
||||
mediaQuery.addEventListener('change', (e) => {
|
||||
// Ne change automatiquement que si pas de préférence explicite
|
||||
const hasExplicitPreference = localStorage.getItem(this.storageKey) !== null;
|
||||
if (!hasExplicitPreference) {
|
||||
const newTheme = e.matches ? 'dark' : 'light';
|
||||
this.applyTheme(newTheme);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère le thème actuel
|
||||
* @returns {string}
|
||||
*/
|
||||
getTheme() {
|
||||
return this.currentTheme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Définit un thème spécifique (utilisé par LanguageManager si besoin)
|
||||
* @param {string} theme - 'light' ou 'dark'
|
||||
*/
|
||||
setTheme(theme) {
|
||||
if (theme === 'light' || theme === 'dark') {
|
||||
this.applyTheme(theme);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export pour utilisation dans app.js
|
||||
window.ThemeManager = ThemeManager;
|
||||
304
assets/js/UploadManager.js
Normal file
304
assets/js/UploadManager.js
Normal file
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* FuZip - Gestionnaire d'upload
|
||||
* Gère le drag & drop, browse, upload vers API, progression
|
||||
*/
|
||||
|
||||
class UploadManager {
|
||||
constructor(side, onStructureLoaded) {
|
||||
this.side = side; // 'left' ou 'right'
|
||||
this.onStructureLoaded = onStructureLoaded; // Callback quand structure reçue
|
||||
this.apiBase = window.FUZIP_CONFIG?.apiBase || '/api/';
|
||||
this.i18n = window.FUZIP_CONFIG?.i18n || {};
|
||||
|
||||
// Éléments DOM
|
||||
this.panel = document.getElementById(`upload-panel-${side}`);
|
||||
this.dropZone = document.getElementById(`drop-zone-${side}`);
|
||||
this.fileInput = document.getElementById(`file-input-${side}`);
|
||||
this.btnBrowse = document.getElementById(`btn-browse-${side}`);
|
||||
this.uploadInfo = document.getElementById(`upload-info-${side}`);
|
||||
this.fileName = document.getElementById(`file-name-${side}`);
|
||||
this.fileSize = document.getElementById(`file-size-${side}`);
|
||||
this.fileCount = document.getElementById(`file-count-${side}`);
|
||||
this.progressBar = document.getElementById(`progress-bar-${side}`);
|
||||
this.progressFill = document.getElementById(`progress-fill-${side}`);
|
||||
this.progressText = document.getElementById(`progress-text-${side}`);
|
||||
|
||||
// État
|
||||
this.currentFile = null;
|
||||
this.structure = null;
|
||||
this.isUploading = false;
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise les événements
|
||||
*/
|
||||
init() {
|
||||
// Drag & Drop
|
||||
if (this.dropZone) {
|
||||
this.dropZone.addEventListener('dragover', (e) => this.onDragOver(e));
|
||||
this.dropZone.addEventListener('dragleave', (e) => this.onDragLeave(e));
|
||||
this.dropZone.addEventListener('drop', (e) => this.onDrop(e));
|
||||
this.dropZone.addEventListener('click', () => this.fileInput?.click());
|
||||
}
|
||||
|
||||
// Browse button
|
||||
if (this.btnBrowse) {
|
||||
this.btnBrowse.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.fileInput?.click();
|
||||
});
|
||||
}
|
||||
|
||||
// File input change
|
||||
if (this.fileInput) {
|
||||
this.fileInput.addEventListener('change', (e) => this.onFileSelected(e));
|
||||
}
|
||||
|
||||
console.log(`[UploadManager] Initialized for side: ${this.side}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Événement dragover
|
||||
*/
|
||||
onDragOver(e) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.dropZone?.classList.add('drag-over');
|
||||
}
|
||||
|
||||
/**
|
||||
* Événement dragleave
|
||||
*/
|
||||
onDragLeave(e) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.dropZone?.classList.remove('drag-over');
|
||||
}
|
||||
|
||||
/**
|
||||
* Événement drop
|
||||
*/
|
||||
onDrop(e) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.dropZone?.classList.remove('drag-over');
|
||||
|
||||
const files = e.dataTransfer?.files;
|
||||
if (files && files.length > 0) {
|
||||
this.handleFile(files[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Événement file input change
|
||||
*/
|
||||
onFileSelected(e) {
|
||||
const files = e.target?.files;
|
||||
if (files && files.length > 0) {
|
||||
this.handleFile(files[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gère un fichier sélectionné
|
||||
* @param {File} file
|
||||
*/
|
||||
async handleFile(file) {
|
||||
// Validation basique
|
||||
if (!file.name.endsWith('.zip')) {
|
||||
this.showError(this.i18n.error_not_zip || 'Le fichier doit être un ZIP');
|
||||
return;
|
||||
}
|
||||
|
||||
if (file.size > 500 * 1024 * 1024) { // 500 MB
|
||||
this.showError(this.i18n.error_file_too_large || 'Fichier trop volumineux (max 500 MB)');
|
||||
return;
|
||||
}
|
||||
|
||||
this.currentFile = file;
|
||||
|
||||
// Upload
|
||||
await this.upload();
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload le fichier vers l'API
|
||||
*/
|
||||
async upload() {
|
||||
if (!this.currentFile || this.isUploading) return;
|
||||
|
||||
this.isUploading = true;
|
||||
this.panel?.classList.add('uploading');
|
||||
this.showProgress(0);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', this.currentFile);
|
||||
formData.append('side', this.side);
|
||||
|
||||
try {
|
||||
const xhr = new XMLHttpRequest();
|
||||
|
||||
// Progression
|
||||
xhr.upload.addEventListener('progress', (e) => {
|
||||
if (e.lengthComputable) {
|
||||
const percent = Math.round((e.loaded / e.total) * 100);
|
||||
this.showProgress(percent);
|
||||
}
|
||||
});
|
||||
|
||||
// Promesse pour gérer le résultat
|
||||
const response = await new Promise((resolve, reject) => {
|
||||
xhr.addEventListener('load', () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
try {
|
||||
const data = JSON.parse(xhr.responseText);
|
||||
resolve(data);
|
||||
} catch (err) {
|
||||
reject(new Error('Réponse JSON invalide'));
|
||||
}
|
||||
} else {
|
||||
reject(new Error(`Erreur HTTP ${xhr.status}`));
|
||||
}
|
||||
});
|
||||
|
||||
xhr.addEventListener('error', () => reject(new Error('Erreur réseau')));
|
||||
xhr.addEventListener('abort', () => reject(new Error('Upload annulé')));
|
||||
|
||||
xhr.open('POST', `${this.apiBase}upload.php`);
|
||||
xhr.send(formData);
|
||||
});
|
||||
|
||||
// Succès
|
||||
if (response.success) {
|
||||
this.structure = response.structure;
|
||||
this.showSuccess(response.stats);
|
||||
|
||||
// Callback vers app.js
|
||||
if (this.onStructureLoaded) {
|
||||
this.onStructureLoaded(this.side, response.structure, response.stats);
|
||||
}
|
||||
} else {
|
||||
throw new Error(response.error || 'Erreur inconnue');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`[UploadManager] Upload error for ${this.side}:`, error);
|
||||
this.showError(error.message);
|
||||
} finally {
|
||||
this.isUploading = false;
|
||||
this.panel?.classList.remove('uploading');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Affiche la progression
|
||||
* @param {number} percent - 0-100
|
||||
*/
|
||||
showProgress(percent) {
|
||||
if (this.uploadInfo) {
|
||||
this.uploadInfo.classList.remove('hidden');
|
||||
}
|
||||
|
||||
if (this.progressBar) {
|
||||
this.progressBar.classList.remove('hidden');
|
||||
}
|
||||
|
||||
if (this.progressFill) {
|
||||
this.progressFill.style.width = `${percent}%`;
|
||||
}
|
||||
|
||||
if (this.progressText) {
|
||||
this.progressText.textContent = `${percent}%`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Affiche le succès avec stats
|
||||
* @param {Object} stats
|
||||
*/
|
||||
showSuccess(stats) {
|
||||
this.panel?.classList.remove('error');
|
||||
this.panel?.classList.add('success');
|
||||
|
||||
if (this.fileName) {
|
||||
this.fileName.textContent = this.currentFile?.name || '';
|
||||
}
|
||||
|
||||
if (this.fileSize) {
|
||||
this.fileSize.textContent = this.formatBytes(stats.total_size || 0);
|
||||
}
|
||||
|
||||
if (this.fileCount) {
|
||||
this.fileCount.textContent = (stats.total_files || 0).toString();
|
||||
}
|
||||
|
||||
// Cache la progress bar après 1s
|
||||
setTimeout(() => {
|
||||
this.progressBar?.classList.add('hidden');
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Affiche une erreur
|
||||
* @param {string} message
|
||||
*/
|
||||
showError(message) {
|
||||
this.panel?.classList.remove('success');
|
||||
this.panel?.classList.add('error');
|
||||
|
||||
alert(message); // TODO: Afficher dans l'UI plutôt qu'une alerte
|
||||
|
||||
// Réinitialise
|
||||
this.currentFile = null;
|
||||
this.structure = null;
|
||||
if (this.uploadInfo) {
|
||||
this.uploadInfo.classList.add('hidden');
|
||||
}
|
||||
if (this.progressBar) {
|
||||
this.progressBar.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formate les octets en format lisible
|
||||
* @param {number} bytes
|
||||
* @returns {string}
|
||||
*/
|
||||
formatBytes(bytes) {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère la structure actuelle
|
||||
* @returns {Object|null}
|
||||
*/
|
||||
getStructure() {
|
||||
return this.structure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Réinitialise l'upload
|
||||
*/
|
||||
reset() {
|
||||
this.currentFile = null;
|
||||
this.structure = null;
|
||||
this.isUploading = false;
|
||||
|
||||
this.panel?.classList.remove('success', 'error', 'uploading');
|
||||
this.uploadInfo?.classList.add('hidden');
|
||||
this.progressBar?.classList.add('hidden');
|
||||
|
||||
if (this.fileInput) {
|
||||
this.fileInput.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export pour utilisation dans app.js
|
||||
window.UploadManager = UploadManager;
|
||||
578
assets/js/app.js
Normal file
578
assets/js/app.js
Normal file
@@ -0,0 +1,578 @@
|
||||
/**
|
||||
* FuZip - Application principale
|
||||
* Point d'entrée et orchestrateur de l'application
|
||||
*/
|
||||
|
||||
class FuZipApp {
|
||||
constructor() {
|
||||
// Vérification config
|
||||
if (!window.FUZIP_CONFIG) {
|
||||
console.error('[FuZipApp] FUZIP_CONFIG not found!');
|
||||
return;
|
||||
}
|
||||
|
||||
// État de l'application
|
||||
this.state = {
|
||||
leftStructure: null,
|
||||
rightStructure: null,
|
||||
leftStats: null,
|
||||
rightStats: null,
|
||||
conflicts: [],
|
||||
selection: new Map() // path -> 'left'|'right'|null
|
||||
};
|
||||
|
||||
// Managers
|
||||
this.themeManager = null;
|
||||
this.langManager = null;
|
||||
this.uploadLeft = null;
|
||||
this.uploadRight = null;
|
||||
this.treeRendererLeft = null;
|
||||
this.treeRendererRight = null;
|
||||
this.previewManager = null;
|
||||
|
||||
// Éléments DOM
|
||||
this.conflictsBanner = document.getElementById('conflicts-banner');
|
||||
this.conflictsCount = document.getElementById('conflicts-count');
|
||||
this.btnMerge = document.getElementById('btn-merge');
|
||||
this.btnReset = document.getElementById('btn-reset');
|
||||
this.selectionCount = document.getElementById('selection-count');
|
||||
this.loadingOverlay = document.getElementById('loading-overlay');
|
||||
this.loadingText = document.getElementById('loading-text');
|
||||
this.treeContainerLeft = document.getElementById('tree-left');
|
||||
this.treeContainerRight = document.getElementById('tree-right');
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise l'application
|
||||
*/
|
||||
async init() {
|
||||
console.log('[FuZipApp] Initializing...');
|
||||
|
||||
// Initialise les managers de base
|
||||
this.themeManager = new ThemeManager();
|
||||
this.langManager = new LanguageManager();
|
||||
|
||||
// Initialise les gestionnaires d'upload
|
||||
this.uploadLeft = new UploadManager('left', (side, structure, stats) => {
|
||||
this.onStructureLoaded(side, structure, stats);
|
||||
});
|
||||
|
||||
this.uploadRight = new UploadManager('right', (side, structure, stats) => {
|
||||
this.onStructureLoaded(side, structure, stats);
|
||||
});
|
||||
|
||||
// Initialise les renderers d'arbres (Phase 6)
|
||||
if (this.treeContainerLeft) {
|
||||
this.treeRendererLeft = new FileTreeRenderer('left', this.treeContainerLeft, this);
|
||||
}
|
||||
|
||||
if (this.treeContainerRight) {
|
||||
this.treeRendererRight = new FileTreeRenderer('right', this.treeContainerRight, this);
|
||||
}
|
||||
|
||||
// Initialise le gestionnaire de preview (Phase 6)
|
||||
this.previewManager = new PreviewManager();
|
||||
|
||||
// Événements boutons
|
||||
this.setupEventListeners();
|
||||
|
||||
// Nettoyage automatique des anciennes sessions
|
||||
this.cleanupOldSessions();
|
||||
|
||||
// Restaurer l'état sauvegardé si disponible
|
||||
this.restoreState();
|
||||
|
||||
console.log('[FuZipApp] Initialized successfully');
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure les événements globaux
|
||||
*/
|
||||
setupEventListeners() {
|
||||
// Bouton merge
|
||||
if (this.btnMerge) {
|
||||
this.btnMerge.addEventListener('click', () => this.onMergeClick());
|
||||
this.updateMergeButton(); // Désactive par défaut
|
||||
}
|
||||
|
||||
// Bouton reset
|
||||
if (this.btnReset) {
|
||||
this.btnReset.addEventListener('click', () => this.reset());
|
||||
}
|
||||
|
||||
// Cleanup au unload
|
||||
window.addEventListener('beforeunload', () => {
|
||||
// Placeholder pour cleanup si nécessaire
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Affiche les informations d'upload dans l'UI
|
||||
* @param {string} side - 'left' ou 'right'
|
||||
* @param {Object} stats - {total_files, total_size}
|
||||
* @param {string|null} fileNameText - Nom du fichier à afficher (optionnel)
|
||||
*/
|
||||
displayUploadInfo(side, stats, fileNameText = null) {
|
||||
const uploadInfo = document.getElementById(`upload-info-${side}`);
|
||||
const fileName = document.getElementById(`file-name-${side}`);
|
||||
const fileSize = document.getElementById(`file-size-${side}`);
|
||||
const fileCount = document.getElementById(`file-count-${side}`);
|
||||
const panel = document.getElementById(`upload-panel-${side}`);
|
||||
|
||||
if (panel) {
|
||||
panel.classList.add('success');
|
||||
}
|
||||
|
||||
if (uploadInfo) {
|
||||
uploadInfo.classList.remove('hidden');
|
||||
}
|
||||
|
||||
if (fileName && fileNameText) {
|
||||
fileName.textContent = fileNameText;
|
||||
}
|
||||
|
||||
if (fileCount && stats.total_files !== undefined) {
|
||||
fileCount.textContent = stats.total_files.toString();
|
||||
}
|
||||
|
||||
if (fileSize && stats.total_size !== undefined) {
|
||||
fileSize.textContent = this.formatBytes(stats.total_size);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formate les octets en format lisible
|
||||
* @param {number} bytes
|
||||
* @returns {string}
|
||||
*/
|
||||
formatBytes(bytes) {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback quand une structure est chargée
|
||||
* @param {string} side - 'left' ou 'right'
|
||||
* @param {Object} structure
|
||||
* @param {Object} stats
|
||||
*/
|
||||
async onStructureLoaded(side, structure, stats) {
|
||||
console.log(`[FuZipApp] Structure loaded for ${side}:`, stats);
|
||||
|
||||
// Mise à jour de l'état
|
||||
if (side === 'left') {
|
||||
this.state.leftStructure = structure;
|
||||
this.state.leftStats = stats;
|
||||
} else {
|
||||
this.state.rightStructure = structure;
|
||||
this.state.rightStats = stats;
|
||||
}
|
||||
|
||||
// Rend l'arborescence (Phase 6)
|
||||
const renderer = side === 'left' ? this.treeRendererLeft : this.treeRendererRight;
|
||||
if (renderer) {
|
||||
// Attendre les conflits si les deux sont chargés
|
||||
if (this.state.leftStructure && this.state.rightStructure) {
|
||||
await this.detectConflicts();
|
||||
}
|
||||
|
||||
// Rendre avec les conflits
|
||||
const conflictPaths = this.state.conflicts.map(c => c.path);
|
||||
renderer.render(structure, conflictPaths);
|
||||
}
|
||||
|
||||
// Met à jour le bouton merge
|
||||
this.updateMergeButton();
|
||||
|
||||
// Sauvegarder l'état
|
||||
this.saveState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Détecte les conflits entre les deux structures
|
||||
*/
|
||||
async detectConflicts() {
|
||||
try {
|
||||
const response = await fetch(`${window.FUZIP_CONFIG.apiBase}structure.php?action=conflicts`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success && data.conflicts) {
|
||||
this.state.conflicts = data.conflicts;
|
||||
this.showConflictsBanner(data.conflicts.length);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[FuZipApp] Error detecting conflicts:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Affiche la bannière de conflits
|
||||
* @param {number} count
|
||||
*/
|
||||
showConflictsBanner(count) {
|
||||
if (count > 0 && this.conflictsBanner) {
|
||||
this.conflictsBanner.classList.remove('hidden');
|
||||
|
||||
if (this.conflictsCount) {
|
||||
this.conflictsCount.textContent = count.toString();
|
||||
}
|
||||
} else if (this.conflictsBanner) {
|
||||
this.conflictsBanner.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour l'état du bouton merge
|
||||
*/
|
||||
updateMergeButton() {
|
||||
if (!this.btnMerge) return;
|
||||
|
||||
// Active seulement si les deux structures sont chargées
|
||||
const canMerge = this.state.leftStructure && this.state.rightStructure;
|
||||
|
||||
this.btnMerge.disabled = !canMerge;
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimise la sélection en supprimant les enfants si le parent est sélectionné
|
||||
* @param {Object} selection - Sélection {path: 'left'|'right'|null}
|
||||
* @returns {Object} Sélection optimisée
|
||||
*/
|
||||
optimizeSelection(selection) {
|
||||
const optimized = {};
|
||||
|
||||
for (const [path, side] of Object.entries(selection)) {
|
||||
if (side === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Vérifier si un parent de ce chemin est déjà sélectionné du même côté
|
||||
let hasParentSelected = false;
|
||||
|
||||
for (const [otherPath, otherSide] of Object.entries(selection)) {
|
||||
if (otherSide === side && otherPath !== path) {
|
||||
// Vérifier si otherPath est un parent de path
|
||||
// Un parent se termine par / et path commence par ce parent
|
||||
if (otherPath.endsWith('/') && path.startsWith(otherPath)) {
|
||||
hasParentSelected = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Si aucun parent n'est sélectionné, garder ce chemin
|
||||
if (!hasParentSelected) {
|
||||
optimized[path] = side;
|
||||
}
|
||||
}
|
||||
|
||||
return optimized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback quand la sélection change
|
||||
*/
|
||||
onSelectionChanged() {
|
||||
// Compte les fichiers sélectionnés
|
||||
let count = 0;
|
||||
this.state.selection.forEach((side, path) => {
|
||||
if (side !== null) {
|
||||
count++;
|
||||
}
|
||||
});
|
||||
|
||||
// Met à jour le footer
|
||||
if (this.selectionCount) {
|
||||
this.selectionCount.textContent = count.toString();
|
||||
}
|
||||
|
||||
// Met à jour les deux renderers
|
||||
if (this.treeRendererLeft) {
|
||||
this.treeRendererLeft.updateAllCheckboxStates();
|
||||
}
|
||||
|
||||
if (this.treeRendererRight) {
|
||||
this.treeRendererRight.updateAllCheckboxStates();
|
||||
}
|
||||
|
||||
// Sauvegarder l'état
|
||||
this.saveState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Événement clic sur le bouton merge
|
||||
*/
|
||||
async onMergeClick() {
|
||||
if (!this.state.leftStructure || !this.state.rightStructure) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.showLoading('Fusion en cours...');
|
||||
|
||||
try {
|
||||
// Convertit la sélection Map en objet pour JSON
|
||||
const selection = {};
|
||||
this.state.selection.forEach((side, path) => {
|
||||
selection[path] = side;
|
||||
});
|
||||
|
||||
// Optimiser la sélection (supprimer les enfants si parent déjà sélectionné)
|
||||
const optimizedSelection = this.optimizeSelection(selection);
|
||||
|
||||
console.log(`[FuZipApp] Selection: ${Object.keys(selection).length} paths -> ${Object.keys(optimizedSelection).length} paths (optimized)`);
|
||||
|
||||
const response = await fetch(`${window.FUZIP_CONFIG.apiBase}merge.php`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ selection: optimizedSelection })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
// Le serveur envoie le fichier ZIP en stream
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
|
||||
// Déclenche le téléchargement
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'merged.zip';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
|
||||
console.log('[FuZipApp] Merge completed successfully');
|
||||
} catch (error) {
|
||||
console.error('[FuZipApp] Merge error:', error);
|
||||
alert(`Erreur lors de la fusion : ${error.message}`);
|
||||
} finally {
|
||||
this.hideLoading();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Affiche l'overlay de loading
|
||||
* @param {string} text
|
||||
*/
|
||||
showLoading(text = 'Chargement...') {
|
||||
if (this.loadingOverlay) {
|
||||
this.loadingOverlay.classList.remove('hidden');
|
||||
}
|
||||
|
||||
if (this.loadingText) {
|
||||
this.loadingText.textContent = text;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache l'overlay de loading
|
||||
*/
|
||||
hideLoading() {
|
||||
if (this.loadingOverlay) {
|
||||
this.loadingOverlay.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Nettoyage automatique des anciennes sessions
|
||||
*/
|
||||
async cleanupOldSessions() {
|
||||
try {
|
||||
await fetch(`${window.FUZIP_CONFIG.apiBase}cleanup.php`);
|
||||
console.log('[FuZipApp] Old sessions cleaned');
|
||||
} catch (error) {
|
||||
console.warn('[FuZipApp] Cleanup failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sauvegarde l'état de l'application dans localStorage
|
||||
*/
|
||||
saveState() {
|
||||
try {
|
||||
// Récupérer les noms de fichiers affichés
|
||||
const fileNameLeft = document.getElementById('file-name-left');
|
||||
const fileNameRight = document.getElementById('file-name-right');
|
||||
|
||||
const state = {
|
||||
sessionId: window.FUZIP_CONFIG.sessionId,
|
||||
leftStructure: this.state.leftStructure,
|
||||
rightStructure: this.state.rightStructure,
|
||||
leftStats: this.state.leftStats,
|
||||
rightStats: this.state.rightStats,
|
||||
leftFileName: fileNameLeft ? fileNameLeft.textContent : null,
|
||||
rightFileName: fileNameRight ? fileNameRight.textContent : null,
|
||||
conflicts: this.state.conflicts,
|
||||
selection: Array.from(this.state.selection.entries()),
|
||||
expandedFoldersLeft: this.treeRendererLeft ? Array.from(this.treeRendererLeft.expandedFolders) : [],
|
||||
expandedFoldersRight: this.treeRendererRight ? Array.from(this.treeRendererRight.expandedFolders) : [],
|
||||
searchQueryLeft: this.treeRendererLeft ? this.treeRendererLeft.searchQuery : '',
|
||||
searchQueryRight: this.treeRendererRight ? this.treeRendererRight.searchQuery : ''
|
||||
};
|
||||
|
||||
localStorage.setItem('fuzip_state', JSON.stringify(state));
|
||||
console.log('[FuZipApp] State saved');
|
||||
} catch (error) {
|
||||
console.warn('[FuZipApp] Failed to save state:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restaure l'état de l'application depuis localStorage
|
||||
*/
|
||||
async restoreState() {
|
||||
try {
|
||||
const saved = localStorage.getItem('fuzip_state');
|
||||
if (!saved) {
|
||||
console.log('[FuZipApp] No saved state found');
|
||||
return;
|
||||
}
|
||||
|
||||
const state = JSON.parse(saved);
|
||||
|
||||
// Vérifier que la session PHP est toujours la même
|
||||
if (state.sessionId !== window.FUZIP_CONFIG.sessionId) {
|
||||
console.log('[FuZipApp] Session ID mismatch, clearing old state');
|
||||
localStorage.removeItem('fuzip_state');
|
||||
return;
|
||||
}
|
||||
|
||||
// Vérifier que les structures existent
|
||||
if (!state.leftStructure && !state.rightStructure) {
|
||||
console.log('[FuZipApp] No structures to restore');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[FuZipApp] Restoring state...');
|
||||
|
||||
// Restaurer conflicts EN PREMIER (utilisés par render)
|
||||
if (state.conflicts) {
|
||||
this.state.conflicts = state.conflicts;
|
||||
this.showConflictsBanner(state.conflicts.length);
|
||||
}
|
||||
|
||||
// Restaurer selection EN SECOND (utilisée par updateAllCheckboxStates)
|
||||
if (state.selection) {
|
||||
this.state.selection = new Map(state.selection);
|
||||
// Ne pas appeler onSelectionChanged() maintenant, on le fera après les renders
|
||||
}
|
||||
|
||||
// Restaurer left
|
||||
if (state.leftStructure) {
|
||||
this.state.leftStructure = state.leftStructure;
|
||||
this.state.leftStats = state.leftStats;
|
||||
|
||||
// Afficher les stats dans l'UI
|
||||
this.displayUploadInfo('left', state.leftStats, state.leftFileName);
|
||||
|
||||
// Restaurer expanded folders AVANT le rendu
|
||||
if (this.treeRendererLeft && state.expandedFoldersLeft) {
|
||||
this.treeRendererLeft.expandedFolders = new Set(state.expandedFoldersLeft);
|
||||
}
|
||||
|
||||
// Restaurer recherche AVANT le rendu
|
||||
if (this.treeRendererLeft && state.searchQueryLeft) {
|
||||
this.treeRendererLeft.searchQuery = state.searchQueryLeft;
|
||||
if (this.treeRendererLeft.searchInput) {
|
||||
this.treeRendererLeft.searchInput.value = state.searchQueryLeft;
|
||||
}
|
||||
if (state.searchQueryLeft && this.treeRendererLeft.searchClearBtn) {
|
||||
this.treeRendererLeft.searchClearBtn.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// Charger la structure (ne pas appeler onStructureLoaded car ça va déclencher saveState)
|
||||
const conflictPaths = this.state.conflicts.map(c => c.path);
|
||||
this.treeRendererLeft.render(state.leftStructure, conflictPaths);
|
||||
}
|
||||
|
||||
// Restaurer right
|
||||
if (state.rightStructure) {
|
||||
this.state.rightStructure = state.rightStructure;
|
||||
this.state.rightStats = state.rightStats;
|
||||
|
||||
// Afficher les stats dans l'UI
|
||||
this.displayUploadInfo('right', state.rightStats, state.rightFileName);
|
||||
|
||||
// Restaurer expanded folders AVANT le rendu
|
||||
if (this.treeRendererRight && state.expandedFoldersRight) {
|
||||
this.treeRendererRight.expandedFolders = new Set(state.expandedFoldersRight);
|
||||
}
|
||||
|
||||
// Restaurer recherche AVANT le rendu
|
||||
if (this.treeRendererRight && state.searchQueryRight) {
|
||||
this.treeRendererRight.searchQuery = state.searchQueryRight;
|
||||
if (this.treeRendererRight.searchInput) {
|
||||
this.treeRendererRight.searchInput.value = state.searchQueryRight;
|
||||
}
|
||||
if (state.searchQueryRight && this.treeRendererRight.searchClearBtn) {
|
||||
this.treeRendererRight.searchClearBtn.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// Charger la structure (ne pas appeler onStructureLoaded car ça va déclencher saveState)
|
||||
const conflictPaths = this.state.conflicts.map(c => c.path);
|
||||
this.treeRendererRight.render(state.rightStructure, conflictPaths);
|
||||
}
|
||||
|
||||
// Mettre à jour les checkboxes et le compteur APRÈS les renders
|
||||
if (state.selection) {
|
||||
this.onSelectionChanged();
|
||||
}
|
||||
|
||||
// Mettre à jour le bouton merge
|
||||
this.updateMergeButton();
|
||||
|
||||
console.log('[FuZipApp] State restored');
|
||||
} catch (error) {
|
||||
console.warn('[FuZipApp] Failed to restore state:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Réinitialise l'application
|
||||
*/
|
||||
reset() {
|
||||
this.state = {
|
||||
leftStructure: null,
|
||||
rightStructure: null,
|
||||
leftStats: null,
|
||||
rightStats: null,
|
||||
conflicts: [],
|
||||
selection: new Map()
|
||||
};
|
||||
|
||||
this.uploadLeft?.reset();
|
||||
this.uploadRight?.reset();
|
||||
this.showConflictsBanner(0);
|
||||
this.updateMergeButton();
|
||||
|
||||
// Clear trees (Phase 6)
|
||||
this.treeRendererLeft?.clear();
|
||||
this.treeRendererRight?.clear();
|
||||
|
||||
// Reset selection count
|
||||
if (this.selectionCount) {
|
||||
this.selectionCount.textContent = '0';
|
||||
}
|
||||
|
||||
// Effacer l'état sauvegardé
|
||||
localStorage.removeItem('fuzip_state');
|
||||
console.log('[FuZipApp] State cleared');
|
||||
}
|
||||
}
|
||||
|
||||
// Initialisation au chargement du DOM
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
window.fuZipApp = new FuZipApp();
|
||||
});
|
||||
Reference in New Issue
Block a user