| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362 |
- /**
- * 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 defined.');
- }
- }
- 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.');
- }
- }
|