/**
* 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 = `
`;
// 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 = `
Aucun fichier
`;
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 = '';
// 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 = `
`;
} else {
icon.innerHTML = `
`;
}
// 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 = `
`;
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 = `
`;
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;