kserver.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /**
  2. * NSEServerBrowser v1.2.0
  3. * A simple file browser component for web applications.
  4. * retro engineering by ChatGPT
  5. *
  6. * Modifications
  7. * - 2025-09-18 - E.Podvin - 1.2.0 - Initial version depuis kserver.js étudié par chatGPT
  8. * - 2025-09-23 - E.Podvin - 1.2.1 - small text formatting
  9. *
  10. */
  11. class NSEServerBrowser {
  12. constructor(cfg) {
  13. this.config = cfg;
  14. this.container = typeof cfg.containerId === 'string'
  15. ? document.getElementById(cfg.containerId)
  16. : cfg.containerId;
  17. if (!this.container) throw new Error('[NSEServerBrowser] - Container not found.');
  18. // i18n packs
  19. const packs = {
  20. fr: { validate: 'Valider', back: 'Retour', preview: 'Prévisualiser', close: 'Fermer', root: 'Racine' },
  21. en: { validate: 'Validate', back: 'Back', preview: 'Preview', close: 'Close', root: 'Root' },
  22. es: { validate: 'Confirmar', back: 'Atrás', preview: 'Vista previa', close: 'Cerrar', root: 'Raíz' },
  23. de: { validate: 'Bestätigen', back: 'Zurück', preview: 'Vorschau', close: 'Schließen', root: 'Wurzel' }
  24. };
  25. const t = (cfg.lang?.toLowerCase()) ?? 'en';
  26. const langKey = packs[t] ? t : 'en';
  27. this.lang = { ...packs[langKey], ...(cfg.langModule || {}) };
  28. this.icons = {
  29. folder: '📁', folderOpen: '📂', file: '📄', image: '🖼️', video: '🎥', pdf: '📑',
  30. ...(cfg.icons || {})
  31. };
  32. this.acceptedExtensions = (cfg.acceptedTypeFiles || []).map(s => s.toLowerCase());
  33. this.autoHideEmptyFolders = cfg.autoHideEmptyFolders ?? false;
  34. this.selectedFile = null;
  35. this.navigationHistory = [];
  36. this.initialData = [];
  37. this.validateButton = null;
  38. this.previewButton = null;
  39. this.applyTheme(cfg.theme);
  40. }
  41. async open() {
  42. const data = await this.loadData();
  43. this.initialData = data && data[0] && data[0].children;
  44. this.renderExplorer(this.initialData);
  45. }
  46. async loadData() {
  47. const dataSource = this.config.dataSource;
  48. if (typeof dataSource === 'string') {
  49. let json;
  50. try {
  51. json = await (await fetch(dataSource)).json();
  52. } catch {
  53. throw new Error('Unable to load data from URL.');
  54. }
  55. const root = Array.isArray(json?.data?.[0]?.folder)
  56. ? json.data[0].folder
  57. : [json?.data?.[0]?.folder].filter(Boolean);
  58. if (!root) throw new Error('Your datasource is invalid.');
  59. return root;
  60. }
  61. if (Array.isArray(dataSource)) return dataSource;
  62. throw new Error('Your datasource is invalid.');
  63. }
  64. renderExplorer(nodes) {
  65. this.container.innerHTML = '';
  66. const wrap = document.createElement('div');
  67. wrap.classList.add('kcontainer');
  68. // back / close
  69. const topBtn = document.createElement('button');
  70. topBtn.className = 'k-back-btn';
  71. if (this.navigationHistory.length > 0) {
  72. topBtn.textContent = this.lang.back;
  73. topBtn.onclick = () => this.goBack();
  74. } else {
  75. topBtn.textContent = this.lang.close;
  76. topBtn.onclick = () => this.destroy();
  77. }
  78. wrap.appendChild(topBtn);
  79. const header = document.createElement('div');
  80. header.classList.add('kheader');
  81. header.appendChild(this.buildBreadcrumbs());
  82. wrap.appendChild(header);
  83. const ul = document.createElement('ul');
  84. ul.classList.add('kfile-tree');
  85. this.buildTree(nodes, ul);
  86. ul.addEventListener('click', this.handleClick.bind(this));
  87. wrap.appendChild(ul);
  88. const footer = document.createElement('div');
  89. footer.classList.add('kfooter');
  90. this.previewButton = document.createElement('button');
  91. this.previewButton.className = 'k-preview-btn';
  92. this.previewButton.textContent = this.lang.preview;
  93. this.previewButton.style.display = 'none';
  94. this.previewButton.onclick = () => this.previewSelectedImage();
  95. footer.appendChild(this.previewButton);
  96. this.validateButton = document.createElement('button');
  97. this.validateButton.className = 'k-validate-btn';
  98. this.validateButton.disabled = true;
  99. this.validateButton.textContent = this.lang.validate;
  100. this.validateButton.onclick = () => this.validateSelectedFile();
  101. footer.appendChild(this.validateButton);
  102. wrap.appendChild(footer);
  103. this.container.appendChild(wrap);
  104. }
  105. buildTree(nodes, ul) {
  106. const frag = document.createDocumentFragment();
  107. for (const n of nodes || []) {
  108. if (!this.shouldDisplayItem(n)) continue;
  109. if (n.type === 'folder' && this.autoHideEmptyFolders && !this.folderHasDisplayableChildren(n)) continue;
  110. const li = this.createListItem(n);
  111. frag.appendChild(li);
  112. if (n.type === 'folder') this.attachFolderChildren(n, li);
  113. }
  114. ul.appendChild(frag);
  115. }
  116. buildBreadcrumbs() {
  117. const breadCrumbs = document.createElement('div');
  118. breadCrumbs.className = 'k-breadcrumb';
  119. const hist = [...this.navigationHistory];
  120. if (hist.length === 0) { breadCrumbs.textContent = this.lang.root; return breadCrumbs; }
  121. if (hist.length > 2) {
  122. const dots = document.createElement('span');
  123. dots.textContent = '...';
  124. breadCrumbs.appendChild(dots);
  125. }
  126. const tail = hist.slice(-2);
  127. tail.forEach((node, idx) => {
  128. const span = document.createElement('span');
  129. span.className = 'k-breadcrumb-item';
  130. span.textContent = node.name;
  131. span.onclick = () => {
  132. const pos = this.navigationHistory.indexOf(node);
  133. this.navigationHistory = this.navigationHistory.slice(0, pos + 1);
  134. this.renderExplorer(node.children || []);
  135. };
  136. breadCrumbs.appendChild(span);
  137. if (idx < tail.length - 1) {
  138. const sep = document.createElement('span'); sep.textContent = ' / ';
  139. breadCrumbs.appendChild(sep);
  140. }
  141. });
  142. return breadCrumbs;
  143. }
  144. shouldDisplayItem(n) {
  145. if (n.type !== 'file') return true;
  146. if (this.acceptedExtensions.length === 0) return true;
  147. const ext = (n.name.split('.').pop() || '').toLowerCase();
  148. return this.acceptedExtensions.includes(ext);
  149. }
  150. createListItem(n) {
  151. const li = document.createElement('li');
  152. li.dataset.type = n.type;
  153. li.classList.add('k' + n.type);
  154. li._fileData = n;
  155. if (n.disabled) {
  156. li.classList.add('k-disabled');
  157. li.setAttribute('aria-disabled', 'true');
  158. }
  159. const ic = document.createElement('span');
  160. if (n.type === 'folder') {
  161. ic.textContent = this.icons.folder;
  162. } else {
  163. const icon = this.getIconForFile(n.name);
  164. if (icon === null && n.previewURL) {
  165. const img = document.createElement('img');
  166. img.src = n.previewURL;
  167. img.alt = n.name;
  168. img.loading = 'lazy';
  169. img.className = 'kfile-thumb';
  170. ic.appendChild(img);
  171. } else {
  172. ic.textContent = icon ?? this.icons.file;
  173. }
  174. }
  175. li.prepend(ic);
  176. const label = document.createElement('p');
  177. label.className = 'k-name';
  178. label.textContent = n.type === 'folder' ? (n.name + '/') : n.name;
  179. li.appendChild(label);
  180. return li;
  181. }
  182. attachFolderChildren(folder, li) {
  183. li.classList.add('kfolder');
  184. if (folder.children?.length) {
  185. const ul = document.createElement('ul');
  186. this.buildTree(folder.children, ul);
  187. li.appendChild(ul);
  188. } else {
  189. li.dataset.lazy = 'true';
  190. }
  191. }
  192. getIconForFile(name) {
  193. const ext = (name.split('.').pop() || '').toLowerCase();
  194. if (!ext) return this.icons.file;
  195. if (['jpg', 'jpeg', 'png', 'webp', 'gif'].includes(ext)) return null; // vignette si previewURL
  196. if (['mp4', 'webm', 'mov'].includes(ext)) return this.icons.video;
  197. if (['pdf', 'txt'].includes(ext)) return this.icons.pdf;
  198. return this.icons.file;
  199. }
  200. applyTheme(theme) {
  201. if (!theme) return;
  202. if (theme.endsWith('.css') || theme.startsWith('http')) {
  203. const link = document.createElement('link');
  204. link.rel = 'stylesheet';
  205. link.href = theme;
  206. document.head.appendChild(link);
  207. } else {
  208. this.container.classList.add(`k-theme-${theme}`);
  209. }
  210. }
  211. isImageFile(name) {
  212. const ext = (name.split('.').pop() || '').toLowerCase();
  213. return ['jpg', 'jpeg', 'png', 'webp'].includes(ext);
  214. }
  215. previewSelectedImage() {
  216. const f = this.selectedFile;
  217. if (!f) return;
  218. // Correctif: accepter previewURL OU url
  219. const src = f.previewURL || f.url;
  220. if (!src) return;
  221. if (!this.isImageFile(f.name)) return;
  222. this.openImageModal(src);
  223. }
  224. openImageModal(src) {
  225. const root = this.container.querySelector('.kcontainer');
  226. if (!root) return;
  227. root.querySelector('.k-modal')?.remove();
  228. const modal = document.createElement('div');
  229. modal.className = 'k-modal';
  230. const overlay = document.createElement('div');
  231. overlay.className = 'k-modal-overlay';
  232. overlay.onclick = close;
  233. const content = document.createElement('div');
  234. content.className = 'k-modal-content';
  235. const img = document.createElement('img');
  236. img.src = src;
  237. img.alt = 'Preview';
  238. img.className = 'k-modal-img';
  239. const closeBtn = document.createElement('button');
  240. closeBtn.textContent = this.lang.close;
  241. closeBtn.className = 'k-modal-close';
  242. closeBtn.onclick = close;
  243. content.appendChild(closeBtn);
  244. content.appendChild(img);
  245. modal.appendChild(overlay);
  246. modal.appendChild(content);
  247. root.appendChild(modal);
  248. const onKey = (e) => { if (e.key === 'Escape') close(); };
  249. document.addEventListener('keydown', onKey);
  250. function close() {
  251. modal.remove();
  252. document.removeEventListener('keydown', onKey);
  253. }
  254. }
  255. handleClick(ev) {
  256. const li = ev.target.closest('li');
  257. if (!li || !this.container.contains(li)) return;
  258. const node = li._fileData;
  259. if (!node || node.disabled) return;
  260. if (node.type === 'folder') {
  261. this.navigationHistory.push(node);
  262. this.renderExplorer(node.children || []);
  263. return;
  264. }
  265. if (node.type === 'file') {
  266. if (this.validateButton) this.validateButton.disabled = false;
  267. this.container.querySelectorAll('li.kfile.selected')
  268. .forEach(el => el.classList.remove('selected'));
  269. li.classList.add('selected');
  270. this.selectedFile = node;
  271. if (this.previewButton) {
  272. this.previewButton.style.display = this.isImageFile(node.name) && (node.previewURL || node.url)
  273. ? 'inline-block'
  274. : 'none';
  275. }
  276. this.config.onFileClick?.(node);
  277. }
  278. }
  279. goBack() {
  280. this.navigationHistory.pop();
  281. const at = this.navigationHistory[this.navigationHistory.length - 1];
  282. this.renderExplorer(at?.children || this.initialData);
  283. }
  284. getSelectedFiles() {
  285. return this.selectedFile;
  286. }
  287. validateSelectedFile() {
  288. if (!this.selectedFile) return;
  289. const folder = this.navigationHistory.map(n => n.name).join('/');
  290. if (typeof this.config.onValidate === 'function') {
  291. this.config.onValidate({ folder, file: this.selectedFile });
  292. } else {
  293. console.warn('[NSEServerBrowser] No callback onValidate was define.');
  294. }
  295. }
  296. folderHasDisplayableChildren(folder) {
  297. if (!folder.children?.length) return false;
  298. return folder.children.some(ch =>
  299. ch.type === 'file' ? this.shouldDisplayItem(ch)
  300. : ch.type === 'folder' ? this.folderHasDisplayableChildren(ch)
  301. : false
  302. );
  303. }
  304. destroy() {
  305. this.container.innerHTML = '';
  306. this.selectedFile = null;
  307. this.validateButton = null;
  308. this.previewButton = null;
  309. this.navigationHistory = [];
  310. this.initialData = [];
  311. const evt = new CustomEvent('kserverbrowser:closed', { detail: { containerId: this.config.containerId } });
  312. document.dispatchEvent(evt);
  313. console.log('[NSEServerBrowser] was destroy.');
  314. }
  315. }