/** * NSEServerBrowser v1.2.0 * A simple file browser component for web applications. * retro engineering by ChatGPT * * Modifications * - 2025-09-18 - E.Podvin - 1.2.0 - Initial version depuis kserver.js étudié par chatGPT * - 2025-09-23 - E.Podvin - 1.2.1 - small text formatting * */ class NSEServerBrowser { constructor(cfg) { this.config = cfg; this.container = typeof cfg.containerId === 'string' ? document.getElementById(cfg.containerId) : cfg.containerId; if (!this.container) throw new Error('[NSEServerBrowser] - Container not found.'); // i18n packs const packs = { fr: { validate: 'Valider', back: 'Retour', preview: 'Prévisualiser', close: 'Fermer', root: 'Racine' }, en: { validate: 'Validate', back: 'Back', preview: 'Preview', close: 'Close', root: 'Root' }, es: { validate: 'Confirmar', back: 'Atrás', preview: 'Vista previa', close: 'Cerrar', root: 'Raíz' }, de: { validate: 'Bestätigen', back: 'Zurück', preview: 'Vorschau', close: 'Schließen', root: 'Wurzel' } }; const t = (cfg.lang?.toLowerCase()) ?? 'en'; const langKey = packs[t] ? t : 'en'; this.lang = { ...packs[langKey], ...(cfg.langModule || {}) }; this.icons = { folder: '📁', folderOpen: '📂', file: '📄', image: '🖼️', video: '🎥', pdf: '📑', ...(cfg.icons || {}) }; this.acceptedExtensions = (cfg.acceptedTypeFiles || []).map(s => s.toLowerCase()); this.autoHideEmptyFolders = cfg.autoHideEmptyFolders ?? false; this.selectedFile = null; this.navigationHistory = []; this.initialData = []; this.validateButton = null; this.previewButton = null; this.applyTheme(cfg.theme); } async open() { const data = await this.loadData(); this.initialData = data && data[0] && data[0].children; this.renderExplorer(this.initialData); } async loadData() { const dataSource = this.config.dataSource; if (typeof dataSource === 'string') { let json; try { json = await (await fetch(dataSource)).json(); } catch { throw new Error('Unable to load data from URL.'); } const root = Array.isArray(json?.data?.[0]?.folder) ? json.data[0].folder : [json?.data?.[0]?.folder].filter(Boolean); if (!root) throw new Error('Your datasource is invalid.'); return root; } if (Array.isArray(dataSource)) return dataSource; throw new Error('Your datasource is invalid.'); } renderExplorer(nodes) { this.container.innerHTML = ''; const wrap = document.createElement('div'); wrap.classList.add('kcontainer'); // back / close const topBtn = document.createElement('button'); topBtn.className = 'k-back-btn'; if (this.navigationHistory.length > 0) { topBtn.textContent = this.lang.back; topBtn.onclick = () => this.goBack(); } else { topBtn.textContent = this.lang.close; topBtn.onclick = () => this.destroy(); } wrap.appendChild(topBtn); const header = document.createElement('div'); header.classList.add('kheader'); header.appendChild(this.buildBreadcrumbs()); wrap.appendChild(header); const ul = document.createElement('ul'); ul.classList.add('kfile-tree'); this.buildTree(nodes, ul); ul.addEventListener('click', this.handleClick.bind(this)); wrap.appendChild(ul); const footer = document.createElement('div'); footer.classList.add('kfooter'); this.previewButton = document.createElement('button'); this.previewButton.className = 'k-preview-btn'; this.previewButton.textContent = this.lang.preview; this.previewButton.style.display = 'none'; this.previewButton.onclick = () => this.previewSelectedImage(); footer.appendChild(this.previewButton); this.validateButton = document.createElement('button'); this.validateButton.className = 'k-validate-btn'; this.validateButton.disabled = true; this.validateButton.textContent = this.lang.validate; this.validateButton.onclick = () => this.validateSelectedFile(); footer.appendChild(this.validateButton); wrap.appendChild(footer); this.container.appendChild(wrap); } buildTree(nodes, ul) { const frag = document.createDocumentFragment(); for (const n of nodes || []) { if (!this.shouldDisplayItem(n)) continue; if (n.type === 'folder' && this.autoHideEmptyFolders && !this.folderHasDisplayableChildren(n)) continue; const li = this.createListItem(n); frag.appendChild(li); if (n.type === 'folder') this.attachFolderChildren(n, li); } ul.appendChild(frag); } buildBreadcrumbs() { const breadCrumbs = document.createElement('div'); breadCrumbs.className = 'k-breadcrumb'; const hist = [...this.navigationHistory]; if (hist.length === 0) { breadCrumbs.textContent = this.lang.root; return breadCrumbs; } if (hist.length > 2) { const dots = document.createElement('span'); dots.textContent = '...'; breadCrumbs.appendChild(dots); } const tail = hist.slice(-2); tail.forEach((node, idx) => { const span = document.createElement('span'); span.className = 'k-breadcrumb-item'; span.textContent = node.name; span.onclick = () => { const pos = this.navigationHistory.indexOf(node); this.navigationHistory = this.navigationHistory.slice(0, pos + 1); this.renderExplorer(node.children || []); }; breadCrumbs.appendChild(span); if (idx < tail.length - 1) { const sep = document.createElement('span'); sep.textContent = ' / '; breadCrumbs.appendChild(sep); } }); return breadCrumbs; } shouldDisplayItem(n) { if (n.type !== 'file') return true; if (this.acceptedExtensions.length === 0) return true; const ext = (n.name.split('.').pop() || '').toLowerCase(); return this.acceptedExtensions.includes(ext); } createListItem(n) { const li = document.createElement('li'); li.dataset.type = n.type; li.classList.add('k' + n.type); li._fileData = n; if (n.disabled) { li.classList.add('k-disabled'); li.setAttribute('aria-disabled', 'true'); } const ic = document.createElement('span'); if (n.type === 'folder') { ic.textContent = this.icons.folder; } else { const icon = this.getIconForFile(n.name); if (icon === null && n.previewURL) { const img = document.createElement('img'); img.src = n.previewURL; img.alt = n.name; img.loading = 'lazy'; img.className = 'kfile-thumb'; ic.appendChild(img); } else { ic.textContent = icon ?? this.icons.file; } } li.prepend(ic); const label = document.createElement('p'); label.className = 'k-name'; label.textContent = n.type === 'folder' ? (n.name + '/') : n.name; li.appendChild(label); return li; } attachFolderChildren(folder, li) { li.classList.add('kfolder'); if (folder.children?.length) { const ul = document.createElement('ul'); this.buildTree(folder.children, ul); li.appendChild(ul); } else { li.dataset.lazy = 'true'; } } getIconForFile(name) { const ext = (name.split('.').pop() || '').toLowerCase(); if (!ext) return this.icons.file; if (['jpg', 'jpeg', 'png', 'webp', 'gif'].includes(ext)) return null; // vignette si previewURL if (['mp4', 'webm', 'mov'].includes(ext)) return this.icons.video; if (['pdf', 'txt'].includes(ext)) return this.icons.pdf; return this.icons.file; } applyTheme(theme) { if (!theme) return; if (theme.endsWith('.css') || theme.startsWith('http')) { const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = theme; document.head.appendChild(link); } else { this.container.classList.add(`k-theme-${theme}`); } } isImageFile(name) { const ext = (name.split('.').pop() || '').toLowerCase(); return ['jpg', 'jpeg', 'png', 'webp'].includes(ext); } previewSelectedImage() { const f = this.selectedFile; if (!f) return; // Correctif: accepter previewURL OU url const src = f.previewURL || f.url; if (!src) return; if (!this.isImageFile(f.name)) return; this.openImageModal(src); } openImageModal(src) { const root = this.container.querySelector('.kcontainer'); if (!root) return; root.querySelector('.k-modal')?.remove(); const modal = document.createElement('div'); modal.className = 'k-modal'; const overlay = document.createElement('div'); overlay.className = 'k-modal-overlay'; overlay.onclick = close; const content = document.createElement('div'); content.className = 'k-modal-content'; const img = document.createElement('img'); img.src = src; img.alt = 'Preview'; img.className = 'k-modal-img'; const closeBtn = document.createElement('button'); closeBtn.textContent = this.lang.close; closeBtn.className = 'k-modal-close'; closeBtn.onclick = close; content.appendChild(closeBtn); content.appendChild(img); modal.appendChild(overlay); modal.appendChild(content); root.appendChild(modal); const onKey = (e) => { if (e.key === 'Escape') close(); }; document.addEventListener('keydown', onKey); function close() { modal.remove(); document.removeEventListener('keydown', onKey); } } handleClick(ev) { const li = ev.target.closest('li'); if (!li || !this.container.contains(li)) return; const node = li._fileData; if (!node || node.disabled) return; if (node.type === 'folder') { this.navigationHistory.push(node); this.renderExplorer(node.children || []); return; } if (node.type === 'file') { if (this.validateButton) this.validateButton.disabled = false; this.container.querySelectorAll('li.kfile.selected') .forEach(el => el.classList.remove('selected')); li.classList.add('selected'); this.selectedFile = node; if (this.previewButton) { this.previewButton.style.display = this.isImageFile(node.name) && (node.previewURL || node.url) ? 'inline-block' : 'none'; } this.config.onFileClick?.(node); } } goBack() { this.navigationHistory.pop(); const at = this.navigationHistory[this.navigationHistory.length - 1]; this.renderExplorer(at?.children || this.initialData); } getSelectedFiles() { return this.selectedFile; } validateSelectedFile() { if (!this.selectedFile) return; const folder = this.navigationHistory.map(n => n.name).join('/'); if (typeof this.config.onValidate === 'function') { this.config.onValidate({ folder, file: this.selectedFile }); } else { console.warn('[NSEServerBrowser] No callback onValidate was define.'); } } folderHasDisplayableChildren(folder) { if (!folder.children?.length) return false; return folder.children.some(ch => ch.type === 'file' ? this.shouldDisplayItem(ch) : ch.type === 'folder' ? this.folderHasDisplayableChildren(ch) : false ); } destroy() { this.container.innerHTML = ''; this.selectedFile = null; this.validateButton = null; this.previewButton = null; this.navigationHistory = []; this.initialData = []; const evt = new CustomEvent('kserverbrowser:closed', { detail: { containerId: this.config.containerId } }); document.dispatchEvent(evt); console.log('[NSEServerBrowser] was destroy.'); } }