const workspace = document.querySelector('#workspace'); const appShell = document.querySelector('.u-nav'); const statusText = document.querySelector('#statusText'); const transferButton = document.querySelector('#newQueueButton'); const settingsButton = document.querySelector('#settingsButton'); const API_BASE = window.UNAV_API_BASE || '/api'; applyHostTheme(); const APP_VERSION = window.UNAV_VERSION || 'dev'; const state = { config: null, windows: [], focusedId: null, selectedEntry: null, contextMenu: null, permissionsDialog: null, uploadConflictDialog: null, uiDialog: null, draggedEntry: null, pointerDrag: null, suppressClickPath: null, suppressItemActivationUntil: 0, debug: [], nextDebugId: 1, jobs: new Map(), uploadTransfers: new Map(), nextUploadTransferId: 1, jobRefresh: new Map(), sizeJobs: new Map(), sizeResults: new Map(), transferPanelVisible: false, transferPanelClosing: false, transferAutoHideTimer: null, settingsPanelVisible: false, clipboard: null, storageInfo: new Map(), jobSamples: new Map(), typeAhead: { key: '', sequence: '', windowId: null, at: 0 }, nextWindowId: 1, zIndex: 20 }; const icons = { directory: 'Folder', file: 'File', symlink: 'Link', other: 'Item' }; const uiIcons = { arrowLeft: '', arrowRight: '', arrowUp: '', archive: '', columns: '', compare: '', disk: '', folderPlus: '', hash: '', paste: '', scissors: '', search: '', star: '', stop: '', wrench: '', chevronDown: '', chevronRight: '', close: '', copy: '', delete: '', download: '', edit: '', enter: '', file: '', folder: '', folderUpload: '', grid: '', list: '', link: '', info: '', maximize: '', minimize: '', move: '', preview: '', refresh: '', save: '', shield: '', tree: '', upload: '' }; // Keep in sync with unav_preview_type() in api/preview.php. const previewExtensions = new Set([ 'ac', 'adoc', 'ahk', 'am', 'asc', 'asciidoc', 'ass', 'automount', 'awk', 'bash', 'bash_profile', 'bashrc', 'bat', 'bib', 'c', 'cc', 'cf', 'cfg', 'cjs', 'clj', 'cmake', 'cmd', 'cnf', 'compose', 'conf', 'config', 'containerfile', 'cpp', 'cron', 'crontab', 'cs', 'csh', 'csr', 'css', 'csv', 'cue', 'curlrc', 'cxx', 'dart', 'desktop', 'diff', 'diz', 'dockerfile', 'dockerignore', 'editorconfig', 'el', 'env', 'erl', 'err', 'ex', 'exports', 'exs', 'fish', 'flac', 'fs', 'fstab', 'geojson', 'gif', 'gitattributes', 'gitignore', 'gitmodules', 'go', 'gql', 'gradle', 'graphql', 'groovy', 'h', 'hbs', 'hcl', 'hh', 'hosts', 'hpp', 'hs', 'htaccess', 'htm', 'html', 'htpasswd', 'ics', 'in', 'inf', 'ini', 'inputrc', 'j2', 'java', 'jinja', 'jinja2', 'jl', 'jpeg', 'jpg', 'js', 'json', 'json5', 'jsonc', 'jsonl', 'jsx', 'ksh', 'kt', 'kts', 'less', 'link', 'lisp', 'list', 'lock', 'log', 'lst', 'lua', 'm3u', 'm3u8', 'm4', 'm4a', 'mak', 'make', 'markdown', 'md', 'md5', 'mdown', 'mdx', 'mjs', 'mk', 'mkd', 'mkv', 'ml', 'mod', 'mount', 'mov', 'mp3', 'mp4', 'mustache', 'ndjson', 'netdev', 'network', 'nfo', 'nix', 'npmrc', 'nvmrc', 'nzb', 'ogg', 'opml', 'org', 'out', 'page', 'patch', 'path', 'pdf', 'pem', 'php', 'phtml', 'pl', 'plg', 'plist', 'pls', 'pm', 'png', 'prefs', 'profile', 'properties', 'proto', 'ps1', 'psd1', 'psm1', 'pub', 'py', 'pyw', 'r', 'rb', 'rc', 'rd', 'repo', 'rs', 'rst', 'rtf', 'rules', 'sass', 'scala', 'screenrc', 'scss', 'sed', 'service', 'sfv', 'sh', 'sha1', 'sha256', 'sha512', 'socket', 'sources', 'spec', 'sql', 'srt', 'ssa', 'sub', 'sum', 'svelte', 'svg', 'swift', 'target', 'tcl', 'tex', 'text', 'tf', 'tfvars', 'timer', 'tmpl', 'tmux', 'toml', 'tpl', 'ts', 'tsv', 'tsx', 'twig', 'txt', 'vb', 'vbs', 'vcf', 'vim', 'vimrc', 'vtt', 'vue', 'wav', 'webm', 'webp', 'wgetrc', 'xhtml', 'xml', 'xsd', 'xsl', 'xslt', 'xspf', 'yaml', 'yarnrc', 'yml', 'zsh', 'zshrc' ]); const previewFilenames = new Set([ 'authorized_keys', 'authors', 'brewfile', 'caddyfile', 'changelog', 'codeowners', 'config', 'containerfile', 'copying', 'crontab', 'dockerfile', 'exports', 'fstab', 'gemfile', 'gnumakefile', 'go', 'group', 'hosts', 'jenkinsfile', 'known_hosts', 'licence', 'license', 'makefile', 'notice', 'passwd', 'procfile', 'rakefile', 'readme', 'shells', 'todo', 'vagrantfile', 'version' ]); document.querySelector('#newExplorerButton').addEventListener('click', () => openExplorer()); document.querySelector('#newPropertiesButton').addEventListener('click', () => openProperties()); transferButton.addEventListener('click', () => toggleTransferPanel()); settingsButton.addEventListener('click', () => toggleSettingsPanel()); window.addEventListener('error', (event) => { recordDebug('window.error', { message: event.message, source: event.filename, line: event.lineno, column: event.colno, error: serializeError(event.error) }); }); window.addEventListener('unhandledrejection', (event) => { recordDebug('window.unhandledrejection', { reason: serializeError(event.reason) }); }); document.querySelector('#tileButton')?.addEventListener('click', () => tileExplorers()); document.addEventListener('keydown', handleExplorerKeydown); document.addEventListener('paste', handleClipboardPaste); init(); async function init() { try { state.config = await api(apiUrl('config.php')); if (!state.config.roots?.length) { throw new Error('No U-Navigator roots configured'); } updateStatusText(); openExplorer(state.config.roots[0].path); } catch (error) { statusText.textContent = error.message; } } function openExplorer(initialPath = state.config?.roots?.[0]?.path, geometry = {}) { if (!initialPath) { statusText.textContent = 'Kein Root-Pfad konfiguriert'; return null; } const x = geometry.x ?? 24 + state.windows.length * 24; const y = geometry.y ?? 20 + state.windows.length * 20; // Use the available workspace on large screens; 900x540 stays the minimum default. const win = createWindow('Explorer', 'explorer', { width: geometry.width ?? Math.max(900, workspace.clientWidth - x - 24), height: geometry.height ?? Math.max(540, workspace.clientHeight - y - 20), x, y, data: { path: initialPath, history: [], historyIndex: -1, filter: '', search: null, editingPath: false, storage: null, entries: [], selectedPath: null, selectedPaths: [], selectionAnchorPath: null, view: 'icons', sort: { key: 'name', dir: 1 }, treeVisible: true, treeWidth: 220, treeExpanded: [], treeChildren: {}, treeLoading: [], loading: false, error: null } }); loadExplorer(win, initialPath); return win; } function openProperties(entry = state.selectedEntry) { if (entry) { state.selectedEntry = entry; } const existing = state.windows.find((item) => item.kind === 'properties'); if (existing) { focusWindow(existing); render(); return existing; } return createWindow('Eigenschaften', 'properties', { width: 420, height: 320, x: 160, y: 90, data: {} }); } function openPreview(entry, sourceWindowId = state.focusedId, options = {}) { if (!entry || (!options.force && !isPreviewable(entry))) { showError(new Error('Für diesen Dateityp ist keine Vorschau verfügbar.')); return null; } const existing = state.windows.find((item) => item.kind === 'preview'); if (existing) { existing.data.entry = entry; existing.data.sourceWindowId = sourceWindowId; existing.data.content = ''; existing.data.editable = false; existing.data.editing = false; existing.data.draft = ''; existing.data.revision = ''; existing.data.loading = true; existing.data.error = null; focusWindow(existing); render(); loadPreview(existing, entry); return existing; } const win = createWindow('Vorschau', 'preview', { width: 620, height: 460, x: 190, y: 110, data: { entry, sourceWindowId, content: '', editable: false, editing: false, draft: '', revision: '', loading: true, error: null } }); loadPreview(win, entry); return win; } function openQueue() { showTransferPanel(); return null; } function createWindow(title, kind, options) { const id = `win-${state.nextWindowId++}`; const win = { id, kind, title, x: options.x, y: options.y, width: options.width, height: options.height, maximized: false, zIndex: ++state.zIndex, data: options.data || {} }; state.windows.push(win); state.focusedId = id; render(); return win; } function render() { workspace.innerHTML = ''; for (const win of state.windows) { workspace.appendChild(renderWindow(win)); } if (state.contextMenu) { workspace.appendChild(renderContextMenu()); } if (state.permissionsDialog) { workspace.appendChild(renderPermissionsDialog()); } if (state.uploadConflictDialog) { workspace.appendChild(renderUploadConflictDialog()); } if (state.uiDialog) { workspace.appendChild(renderUiDialog()); } renderTransferPanel(); renderSettingsPanel(); } function renderWindow(win) { const el = document.createElement('section'); el.className = `window ${state.focusedId === win.id ? 'focused' : ''} ${win.maximized ? 'maximized' : ''}`; el.style.left = `${win.maximized ? 0 : win.x}px`; el.style.top = `${win.maximized ? 0 : win.y}px`; // Maximized windows follow the workspace when the browser is resized. el.style.width = win.maximized ? '100%' : `${win.width}px`; el.style.height = win.maximized ? '100%' : `${win.height}px`; el.style.zIndex = win.zIndex; el.dataset.windowId = win.id; el.addEventListener('pointerdown', () => focusWindow(win)); const titlebar = document.createElement('div'); titlebar.className = 'titlebar'; titlebar.innerHTML = ` ${escapeHtml(windowTitle(win))}
`; titlebar.addEventListener('pointerdown', (event) => startDragWindow(event, win)); titlebar.querySelector('[data-action="maximize"]').addEventListener('click', (event) => { event.stopPropagation(); win.maximized = !win.maximized; focusWindow(win); render(); }); titlebar.querySelector('[data-action="close"]').addEventListener('click', async (event) => { event.stopPropagation(); if (win.kind === 'preview' && win.data.editing && win.data.draft !== win.data.content) { const discard = await showConfirmDialog( 'Ungespeicherte Änderungen', 'Die Änderungen an dieser Datei wurden noch nicht gespeichert.', '', { confirmLabel: 'Verwerfen', danger: true } ); if (!discard) return; } state.windows = state.windows.filter((item) => item.id !== win.id); state.focusedId = state.windows.at(-1)?.id || null; render(); }); const body = document.createElement('div'); body.className = 'window-body'; if (win.kind === 'explorer') renderExplorer(body, win); if (win.kind === 'properties') renderProperties(body); if (win.kind === 'preview') renderPreview(body, win); const scrollHost = body.querySelector('.explorer-content') || body; scrollHost.addEventListener('scroll', () => { if (win.data.lockScroll) { scrollHost.scrollTop = win.data.lockScrollTop || 0; scrollHost.scrollLeft = win.data.lockScrollLeft || 0; return; } win.data.scrollTop = scrollHost.scrollTop; win.data.scrollLeft = scrollHost.scrollLeft; }); el.append(titlebar, body); requestAnimationFrame(() => { scrollHost.scrollTop = win.data.scrollTop || 0; scrollHost.scrollLeft = win.data.scrollLeft || 0; }); if (!win.maximized) { const resize = document.createElement('div'); resize.className = 'resize-handle'; resize.addEventListener('pointerdown', (event) => startResizeWindow(event, win)); el.appendChild(resize); } return el; } function renderExplorer(body, win) { const data = win.data; const readOnly = isReadOnly(); const favorite = isFavorite(data.path); body.classList.add('explorer-body'); body.innerHTML = `
${data.editingPath ? `` : ``}
${data.treeVisible ? renderFolderTree(win) : ''} ${data.treeVisible ? '' : ''}
${data.search ? searchBannerMarkup(data.search) : ''}
${data.error ? `

${escapeHtml(data.error)}

` : ''} ${data.loading ? '

Lade...

' : renderFileEntries(win)}
`; const pathInput = body.querySelector('.path-input'); if (pathInput) { pathInput.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); data.editingPath = false; loadExplorer(win, pathInput.value.trim() || data.path); } else if (event.key === 'Escape') { event.preventDefault(); data.editingPath = false; render(); } }); pathInput.addEventListener('blur', () => { if (!data.editingPath) return; data.editingPath = false; render(); }); setTimeout(() => { pathInput.focus(); pathInput.select(); }, 0); } const breadcrumb = body.querySelector('.breadcrumb'); breadcrumb?.addEventListener('click', (event) => { const crumb = event.target.closest('[data-crumb]'); if (crumb) { loadExplorer(win, crumb.dataset.crumb); return; } data.editingPath = true; render(); }); const filterInput = body.querySelector('.filter-input'); filterInput.addEventListener('input', () => { data.filter = filterInput.value; data.focusFilter = true; render(); }); filterInput.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); startSearch(win, filterInput.value.trim()); } else if (event.key === 'Escape') { event.preventDefault(); data.filter = ''; if (data.search) closeSearch(win); render(); } }); if (data.focusFilter) { data.focusFilter = false; setTimeout(() => { filterInput.focus(); filterInput.setSelectionRange(filterInput.value.length, filterInput.value.length); }, 0); } body.querySelector('[data-action="back"]').addEventListener('click', () => goHistory(win, -1)); body.querySelector('[data-action="forward"]').addEventListener('click', () => goHistory(win, 1)); body.querySelector('[data-action="refresh"]').addEventListener('click', () => loadExplorer(win, data.path)); body.querySelector('[data-action="up"]').addEventListener('click', () => goUp(win)); body.querySelector('[data-action="favorite"]').addEventListener('click', () => toggleFavorite(data.path)); body.querySelector('[data-action="new-folder"]').addEventListener('click', () => createFolder(win)); body.querySelector('[data-action="toggle-tree"]').addEventListener('click', () => { data.treeVisible = !data.treeVisible; render(); }); body.querySelector('[data-action="view-list"]').addEventListener('click', () => setExplorerView(win, 'list')); body.querySelector('[data-action="view-icons"]').addEventListener('click', () => setExplorerView(win, 'icons')); for (const th of body.querySelectorAll('.file-table th[data-sort-key]')) { th.addEventListener('click', () => { const key = th.dataset.sortKey; const current = data.sort || { key: 'name', dir: 1 }; data.sort = current.key === key ? { key, dir: -current.dir } : { key, dir: 1 }; render(); }); } body.querySelector('[data-action="search-cancel"]')?.addEventListener('click', () => cancelJob(data.search?.jobId)); body.querySelector('[data-action="search-close"]')?.addEventListener('click', () => { closeSearch(win); render(); }); body.querySelector('[data-action="upload-files"]').addEventListener('click', () => body.querySelector('[data-upload="files"]').click()); body.querySelector('[data-action="upload-folder"]').addEventListener('click', () => body.querySelector('[data-upload="folder"]').click()); body.querySelector('[data-action="delete-selected"]').addEventListener('click', () => deleteEntries(win)); bindFolderTree(body, win); body.querySelector('[data-action="resize-tree"]')?.addEventListener('pointerdown', (event) => startTreeResize(event, win, body)); for (const inputEl of body.querySelectorAll('.upload-input')) { inputEl.addEventListener('change', async () => { try { await uploadFileList(win, [...inputEl.files], data.path); } catch (error) { showError(error); } finally { inputEl.value = ''; } }); } for (const img of body.querySelectorAll('img.thumb')) { img.addEventListener('error', () => img.closest('.entry-thumb')?.classList.add('failed'), { once: true }); } const dropZone = body.querySelector('.drop-zone'); const fileScrollHost = body.querySelector('.explorer-content') || body; dropZone.addEventListener('dragenter', (event) => { if (hasDropPayload(event)) { event.preventDefault(); data.dragOver = true; dropZone.classList.add('drag-over'); } }); dropZone.addEventListener('dragover', (event) => { if (hasDropPayload(event)) { event.preventDefault(); setDropEffect(event, 'copy'); data.dragOver = true; dropZone.classList.add('drag-over'); } }); dropZone.addEventListener('dragleave', () => { data.dragOver = false; dropZone.classList.remove('drag-over'); }); dropZone.addEventListener('drop', async (event) => { event.preventDefault(); data.dragOver = false; dropZone.classList.remove('drag-over'); try { await handleDrop(event, win, data.path); } catch (error) { showError(error); } }); dropZone.addEventListener('contextmenu', (event) => { event.preventDefault(); showContextMenu(event, win, null); }); dropZone.addEventListener('click', (event) => { if (event.target.closest('.file-row') || event.ctrlKey || event.metaKey || event.shiftKey) return; if (shouldSuppressItemActivation()) return; if ((data.selectedPaths || []).length) { data.selectedPaths = []; data.selectedPath = null; updateSelectedRows(); updateStatusbar(win); } }); const items = currentItems(win); for (const row of body.querySelectorAll('.file-row')) { const entry = items.find((item) => item.path === row.dataset.path); if (!entry) continue; row.draggable = false; row.addEventListener('dragstart', (event) => event.preventDefault()); row.addEventListener('selectstart', (event) => event.preventDefault()); row.addEventListener('pointerdown', (event) => { lockExplorerScroll(win, fileScrollHost); startItemPointerDrag(event, win, entry); }); row.addEventListener('click', (event) => { if (shouldSuppressItemActivation()) return; selectEntry(win, entry, fileScrollHost, event); }); row.addEventListener('dblclick', () => { if (shouldSuppressItemActivation()) return; activateEntry(win, entry); }); row.addEventListener('contextmenu', (event) => { event.preventDefault(); event.stopPropagation(); if (selectedPathSet(win).has(entry.path)) { state.selectedEntry = entry; focusWindow(win); updatePropertiesWindows(); } else { selectEntry(win, entry, null, event); } showContextMenu(event, win, entry); }); } } function renderFolderTree(win) { const roots = state.config?.roots || []; const branches = roots.map((root) => renderTreeBranch(win, root.path, root.label || root.path, 0)).join(''); const favorites = state.config?.favorites || []; const favoriteMarkup = favorites.length ? `
Favoriten
${favorites.map((path) => `
${iconSvg('star')} ${iconSvg('folder')} ${escapeHtml(basename(path) || path)}
`).join('')}
` : ''; return ` `; } function renderTreeBranch(win, path, label, level) { const data = win.data; const expanded = (data.treeExpanded || []).includes(path); const loading = (data.treeLoading || []).includes(path); const children = data.treeChildren?.[path]; const active = normalizePath(data.path) === normalizePath(path); const mayExpand = loading || children === undefined || children.length > 0; const childMarkup = expanded && children?.length ? `
${children.map((entry) => renderTreeBranch(win, entry.path, entry.name, level + 1)).join('')}
` : ''; return `
${loading ? '' : iconSvg(expanded ? 'chevronDown' : 'chevronRight')} ${iconSvg('folder')} ${escapeHtml(label)}
${childMarkup}
`; } function bindFolderTree(body, win) { body.querySelector('[data-action="close-tree"]')?.addEventListener('click', () => { win.data.treeVisible = false; render(); }); for (const button of body.querySelectorAll('[data-tree-open]')) { button.addEventListener('click', () => loadExplorer(win, button.dataset.treeOpen)); bindTreeKeyboard(button); } for (const button of body.querySelectorAll('[data-tree-toggle]')) { button.addEventListener('click', async () => { const path = button.dataset.treeToggle; const expanded = new Set(win.data.treeExpanded || []); if (expanded.has(path)) { expanded.delete(path); win.data.treeExpanded = [...expanded]; render(); return; } expanded.add(path); win.data.treeExpanded = [...expanded]; await loadTreeChildren(win, path); }); bindTreeKeyboard(button); } } function bindTreeKeyboard(element) { element.addEventListener('keydown', (event) => { if (event.key !== 'Enter' && event.key !== ' ') return; event.preventDefault(); element.click(); }); } function startTreeResize(event, win, body) { if (event.button !== 0) return; event.preventDefault(); event.stopPropagation(); const handle = event.currentTarget; const layout = body.querySelector('.explorer-layout'); const startX = event.clientX; const startWidth = Number(win.data.treeWidth) || body.querySelector('.folder-tree')?.getBoundingClientRect().width || 220; const pointerId = event.pointerId; handle.classList.add('active'); try { handle.setPointerCapture(pointerId); } catch {} const move = (moveEvent) => { const maxWidth = Math.max(180, Math.min(480, body.clientWidth - 240)); win.data.treeWidth = Math.round(clamp(startWidth + moveEvent.clientX - startX, 150, maxWidth)); layout?.style.setProperty('--tree-width', `${win.data.treeWidth}px`); }; const up = () => { handle.classList.remove('active'); handle.removeEventListener('pointermove', move); handle.removeEventListener('pointerup', up); handle.removeEventListener('pointercancel', up); try { handle.releasePointerCapture(pointerId); } catch {} }; handle.addEventListener('pointermove', move); handle.addEventListener('pointerup', up); handle.addEventListener('pointercancel', up); } function sortEntries(entries, sort) { const key = sort?.key || 'name'; const dir = sort?.dir === -1 ? -1 : 1; const typeOrder = { directory: 0, file: 1, symlink: 2, other: 3 }; const compareValue = (entry) => { if (key === 'size') return entry.type === 'file' ? (entry.size || 0) : -1; if (key === 'modifiedAt') return Date.parse(entry.modifiedAt) || 0; if (key === 'type') return typeOrder[entry.type] ?? 4; return entry.name || ''; }; const compareName = (a, b) => (a.name || '').localeCompare(b.name || undefined, undefined, { numeric: true, sensitivity: 'base' }); return [...entries].sort((a, b) => { // Ordner immer zuerst, dann Dateien, dann Verknüpfungen/sonstige if (a.type !== b.type) return (typeOrder[a.type] ?? 4) - (typeOrder[b.type] ?? 4); if (key === 'name') return dir * compareName(a, b); const valueA = compareValue(a); const valueB = compareValue(b); if (valueA !== valueB) return dir * (valueA < valueB ? -1 : 1); return compareName(a, b); }); } function renderFileEntries(win) { const data = win.data; const entries = visibleEntries(win); if (!entries.length) { if (data.search) { return `

${data.search.status === 'running' ? 'Suche läuft…' : 'Keine Treffer.'}

`; } if (data.filter && (data.entries || []).length) { return '

Kein Eintrag passt zum Filter. Enter durchsucht auch die Unterordner.

'; } return '

Dieser Ordner ist leer. Dateien können hier abgelegt werden.

'; } const selectedPaths = selectedPathSet(win); const sort = data.sort || { key: 'name', dir: 1 }; return (data.view || 'list') === 'icons' && !data.search ? renderFileIcons(entries, selectedPaths) : renderFileTable(entries, selectedPaths, sort, data.search ? data.search.root : null); } function renderFileTable(entries, selectedPaths, sort = { key: 'name', dir: 1 }, searchRoot = null) { const showLocation = Boolean(searchRoot); const relativeFolder = (path) => { const folder = normalizePath(dirname(path)); const root = normalizePath(searchRoot); return folder === root ? '.' : (isPathInside(folder, root) ? folder.slice(root.length + 1) : folder); }; const rows = entries.map((entry) => ` ${fileTypeIcon(entry)}${escapeHtml(entry.name)} ${showLocation ? `${escapeHtml(relativeFolder(entry.path))}` : ''} ${escapeHtml(typeLabel(entry.type))} ${entry.type === 'file' ? formatBytes(entry.size) : ''} ${new Date(entry.modifiedAt).toLocaleString()} `).join(''); const header = (key, label) => { const active = sort.key === key; const arrow = active ? (sort.dir === 1 ? ' ▲' : ' ▼') : ''; return `${label}${arrow}`; }; return ` ${header('name', 'Name')}${showLocation ? '' : ''}${header('type', 'Typ')}${header('size', 'Größe')}${header('modifiedAt', 'Geändert')}${rows}
Ordner
`; } function renderFileIcons(entries, selectedPaths) { const items = entries.map((entry) => ` `).join(''); return `
${items}
`; } function fileTypeIcon(entry, large = false) { const name = entry?.type === 'directory' ? 'folder' : entry?.type === 'symlink' ? 'link' : 'file'; const label = icons[entry?.type] || 'Item'; return `${iconSvg(name)}`; } function typeLabel(type) { return ({ directory: 'Ordner', file: 'Datei', symlink: 'Verknüpfung', other: 'Element' })[type] || 'Element'; } function setExplorerView(win, view) { win.data.view = view; render(); } function renderProperties(body) { const entry = state.selectedEntry; if (!entry) { body.innerHTML = '

Keine Datei ausgewählt.

'; return; } const sizeLabel = entry.type === 'directory' ? directorySizeLabel(entry) : formatBytes(entry.size); body.classList.add('properties'); body.innerHTML = `
Name
${escapeHtml(entry.name)}
Typ
${escapeHtml(typeLabel(entry.type))}
Pfad
${escapeHtml(entry.path)}
Größe
${escapeHtml(sizeLabel)}
Geändert
${new Date(entry.modifiedAt).toLocaleString()}
Besitzer
${escapeHtml(formatPrincipal(entry.owner, entry.ownerId))}
Gruppe
${escapeHtml(formatPrincipal(entry.group, entry.groupId))}
Rechte
${escapeHtml(entry.permissions ? `0${entry.permissions}`.slice(-4) : '-')}
Liegt auf
${escapeHtml(storageLocationLabel(entry.path))}
Frei
${escapeHtml(storageFreeLabel(entry.path))}
`; if (entry.type === 'directory') { if (isSystemRootPath(entry.path)) { if (!state.sizeResults.has(entry.path) && !state.sizeJobs.has(entry.path)) { const sizeCell = body.querySelectorAll('dd')[3]; sizeCell.innerHTML = ''; sizeCell.querySelector('button').addEventListener('click', () => { ensureDirectorySize(entry); updatePropertiesWindows(); }); } } else { ensureDirectorySize(entry); } } ensureStorageInfo(entry.path); } function renderPreview(body, win) { const data = win.data; body.classList.add('preview-body'); if (data.loading) { body.innerHTML = '

Lade Vorschau...

'; return; } if (data.error) { body.innerHTML = `

${escapeHtml(data.error)}

`; return; } const entry = data.entry; const navigation = previewNavigation(data); const canEdit = data.editable && !isReadOnly(); body.innerHTML = `
${escapeHtml(entry?.name || data.name || 'Vorschau')}
${escapeHtml(formatBytes(data.size || entry?.size || 0))} ${canEdit && !data.editing ? `` : ''} ${data.editing ? `` : ''}
${renderPreviewContent(data)} ${isCodeView(data) ? `
${editorStatusMarkup(data)}
` : ''} `; if (isCodeView(data)) body.classList.add('with-status'); else body.classList.remove('with-status'); body.querySelector('[data-action="preview-prev"]')?.addEventListener('click', () => openPreview(navigation.previous, data.sourceWindowId)); body.querySelector('[data-action="preview-next"]')?.addEventListener('click', () => openPreview(navigation.next, data.sourceWindowId)); body.querySelector('[data-action="preview-edit"]')?.addEventListener('click', () => { data.editing = true; data.draft = data.content || ''; render(); }); body.querySelector('[data-action="preview-cancel"]')?.addEventListener('click', () => { data.editing = false; data.draft = ''; render(); }); const editor = body.querySelector('.preview-editor'); if (editor) { bindCodeEditor(body, editor, win); } body.querySelector('[data-action="preview-save"]')?.addEventListener('click', () => savePreview(win, editor?.value ?? data.draft ?? '')); } function renderPreviewContent(data) { if (data.editing) { const value = data.draft ?? data.content ?? ''; return `
`; } if (data.type === 'markdown') { return `
${renderMarkdown(data.content || '')}
`; } if (data.type === 'csv') { return renderCsvPreview(data.content || '', data.extension === 'tsv' ? '\t' : ','); } if (data.type === 'image') { return `
${escapeAttr(data.name || 'Vorschau')}
`; } if (data.type === 'pdf') { return ``; } if (data.type === 'audio') { return `
`; } if (data.type === 'video') { return `
`; } return `
${escapeHtml(data.content || '')}
`; } function previewNavigation(data) { const source = state.windows.find((win) => win.id === data.sourceWindowId && win.kind === 'explorer'); const entries = (source?.data.entries || []).filter(isPreviewable); if (entries.length < 2) { return { previous: null, next: null }; } const index = entries.findIndex((entry) => entry.path === data.entry?.path); if (index < 0) { return { previous: null, next: null }; } return { previous: entries[(index - 1 + entries.length) % entries.length], next: entries[(index + 1) % entries.length] }; } async function loadPreview(win, entry) { win.data.loading = true; win.data.error = null; render(); try { const result = await api(apiUrl(`preview.php?path=${encodeURIComponent(entry.path)}`)); win.data.entry = entry; win.data.sourceWindowId = win.data.sourceWindowId || state.focusedId; win.data.name = result.name; win.data.size = result.size; win.data.type = result.type; win.data.extension = result.extension; win.data.rawUrl = result.rawUrl; win.data.content = result.content; win.data.editable = Boolean(result.editable); win.data.editing = false; win.data.draft = ''; win.data.revision = result.revision || ''; win.data.encoding = result.encoding || 'utf-8'; win.data.lineEnding = /\r\n/.test(result.content || '') ? 'crlf' : 'lf'; // The textarea works with \n only; CRLF is restored on save. win.data.content = win.data.lineEnding === 'crlf' ? String(result.content).replace(/\r\n/g, '\n') : result.content; } catch (error) { win.data.error = error.message; } finally { win.data.loading = false; render(); } } async function savePreview(win, content) { if (win.data.saving || !win.data.editable || isReadOnly()) return; const problem = validateEditorContent(win.data, content); if (problem) { const proceed = await showConfirmDialog('Möglicher Fehler in der Datei', problem.message, problem.detail, { confirmLabel: 'Trotzdem speichern', danger: true }); if (!proceed) { if (problem.line) { requestAnimationFrame(() => goToEditorLine(win, problem.line)); } return; } } win.data.saving = true; render(); const body = new URLSearchParams(); body.set('content', win.data.lineEnding === 'crlf' ? content.replace(/\r?\n/g, '\r\n') : content); body.set('revision', win.data.revision || ''); appendCsrf(body); try { const result = await api(apiUrl(`preview.php?path=${encodeURIComponent(win.data.entry.path)}`), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body }); win.data.content = win.data.lineEnding === 'crlf' ? String(result.content).replace(/\r\n/g, '\n') : result.content; win.data.draft = ''; win.data.editing = false; win.data.revision = result.revision; win.data.size = result.size; win.data.entry = { ...win.data.entry, size: result.size, modifiedAt: result.modifiedAt }; const source = state.windows.find((item) => item.id === win.data.sourceWindowId && item.kind === 'explorer'); const sourceEntry = source?.data.entries?.find((item) => item.path === result.path); if (sourceEntry) { sourceEntry.size = result.size; sourceEntry.modifiedAt = result.modifiedAt; } if (state.selectedEntry?.path === result.path) { state.selectedEntry = win.data.entry; } } catch (error) { showError(error); } finally { win.data.saving = false; render(); } } function renderMarkdown(content) { const blocks = []; let listItems = []; const flushList = () => { if (listItems.length) { blocks.push(``); listItems = []; } }; for (const line of String(content).split(/\r?\n/)) { const heading = /^(#{1,6})\s+(.*)$/.exec(line); if (heading) { flushList(); const level = heading[1].length; blocks.push(`${renderInlineMarkdown(heading[2])}`); continue; } const list = /^\s*[-*]\s+(.*)$/.exec(line); if (list) { listItems.push(list[1]); continue; } flushList(); if (!line.trim()) continue; blocks.push(`

${renderInlineMarkdown(line)}

`); } flushList(); return blocks.join(''); } function renderInlineMarkdown(value) { return escapeHtml(value) .replace(/`([^`]+)`/g, '$1') .replace(/\*\*([^*]+)\*\*/g, '$1') .replace(/\*([^*]+)\*/g, '$1'); } function renderCsvPreview(content, delimiter) { const rows = parseDelimitedRows(content, delimiter).slice(0, 80); if (!rows.length) { return '

Keine Tabellenzeilen.

'; } return `
${rows.map((row) => `${row.map((cell) => ``).join('')}`).join('')}
${escapeHtml(cell)}
`; } function parseDelimitedRows(content, delimiter) { const rows = []; let row = []; let cell = ''; let quoted = false; const text = String(content || ''); for (let index = 0; index < text.length; index += 1) { const char = text[index]; if (char === '"') { if (quoted && text[index + 1] === '"') { cell += '"'; index += 1; } else { quoted = !quoted; } continue; } if (!quoted && char === delimiter) { row.push(cell); cell = ''; continue; } if (!quoted && (char === '\n' || char === '\r')) { if (char === '\r' && text[index + 1] === '\n') index += 1; row.push(cell); rows.push(row); row = []; cell = ''; continue; } cell += char; } if (cell || row.length) { row.push(cell); rows.push(row); } return rows; } function renderQueue(body) { body.innerHTML = queueMarkup(); bindQueueActions(body); } function queueMarkup() { const jobs = [...state.jobs.values()].reverse(); const uploads = [...state.uploadTransfers.values()].reverse(); const transferItems = [ ...uploads.map(uploadTransferMarkup), ...jobs.filter((job) => !['size', 'search'].includes(job.type)).map(renderJobCard) ]; const jobMarkup = transferItems.length ? transferItems.join('') : '

Keine Transfers.

'; const debugSection = state.config?.debug ? debugMarkup() : ''; return `
${jobMarkup}
${debugSection} `; } function uploadTransferMarkup(upload) { const progress = Math.max(0, Math.min(100, Number(upload.progress) || 0)); const fileText = `${upload.completedFiles + upload.skippedFiles}/${upload.totalFiles} Dateien`; const byteText = `${formatBytes(upload.uploadedBytes)} / ${formatBytes(upload.totalBytes)}`; const detail = upload.currentFile ? ` · ${upload.currentFile}` : ''; const skipped = upload.skippedFiles ? ` · ${upload.skippedFiles} übersprungen` : ''; const overwritten = upload.overwrittenFiles ? ` · ${upload.overwrittenFiles} überschrieben` : ''; return `
Upload #${escapeHtml(upload.id)}
${escapeHtml(upload.status)} · ${escapeHtml(fileText)} · ${escapeHtml(byteText)}${escapeHtml(detail)}${escapeHtml(skipped)}${escapeHtml(overwritten)}
`; } function debugMarkup() { const debugMarkup = state.debug.length ? state.debug.slice(-12).reverse().map((item) => `
#${item.id} ${escapeHtml(item.label)}
${escapeHtml(JSON.stringify(item.data, null, 2))}
`).join('') : '

Noch keine Debug-Einträge.

'; return `
Debug
${debugMarkup}
`; } function bindQueueActions(root) { for (const button of root.querySelectorAll('[data-cancel-job]')) { button.addEventListener('click', () => cancelJob(button.dataset.cancelJob)); } for (const button of root.querySelectorAll('[data-job-result]')) { button.addEventListener('click', () => showJobResult(state.jobs.get(button.dataset.jobResult))); } root.querySelector('[data-action="clear-finished"]')?.addEventListener('click', () => { for (const [id, job] of state.jobs) { if (!isJobActive(job)) state.jobs.delete(id); } for (const [id, upload] of state.uploadTransfers) { if (!['queued', 'running'].includes(upload.status)) state.uploadTransfers.delete(id); } updateTransferPanel(); }); root.querySelector('[data-action="clear-debug"]')?.addEventListener('click', () => { state.debug = []; updateTransferPanel(); }); } function toggleTransferPanel() { if (state.transferPanelVisible) { hideTransferPanel(); } else { showTransferPanel(); } } function showTransferPanel() { if (state.transferAutoHideTimer) { clearTimeout(state.transferAutoHideTimer); state.transferAutoHideTimer = null; } state.transferPanelVisible = true; state.transferPanelClosing = false; renderTransferPanel(); } function hideTransferPanel() { if (!state.transferPanelVisible && !state.transferPanelClosing) { return; } if (state.transferAutoHideTimer) { clearTimeout(state.transferAutoHideTimer); state.transferAutoHideTimer = null; } state.transferPanelVisible = false; state.transferPanelClosing = true; renderTransferPanel(); setTimeout(() => { if (!state.transferPanelVisible) { state.transferPanelClosing = false; renderTransferPanel(); } }, 220); } function scheduleTransferAutoHide() { if (!state.transferPanelVisible || activeTransferCount() > 0 || state.transferAutoHideTimer) { return; } state.transferAutoHideTimer = setTimeout(() => { state.transferAutoHideTimer = null; if (activeTransferCount() === 0) { hideTransferPanel(); } }, 2200); } function activeTransferCount() { const activeJobs = [...state.jobs.values()].filter((job) => !['size', 'search'].includes(job.type) && isJobActive(job)).length; const activeUploads = [...state.uploadTransfers.values()].filter((upload) => ['queued', 'running'].includes(upload.status)).length; return activeJobs + activeUploads; } function renderTransferPanel() { const existing = appShell.querySelector('.transfer-panel'); if (!state.transferPanelVisible && !state.transferPanelClosing) { existing?.remove(); transferButton.classList.remove('active'); transferButton.setAttribute('aria-expanded', 'false'); return; } const panel = existing || document.createElement('aside'); panel.className = `transfer-panel ${state.transferPanelClosing ? 'closing' : 'open'}`; panel.setAttribute('aria-label', 'Transfers'); panel.innerHTML = `
Transfers
${queueMarkup()}
`; if (!existing) { appShell.appendChild(panel); } const buttonRect = transferButton.getBoundingClientRect(); const shellRect = appShell.getBoundingClientRect(); const panelWidth = Math.min(520, Math.max(360, shellRect.width - 32)); const right = Math.max(16, shellRect.right - buttonRect.right); panel.style.width = `${panelWidth}px`; panel.style.right = `${right}px`; panel.style.top = `${buttonRect.bottom - shellRect.top + 8}px`; panel.querySelector('[data-action="close-transfers"]').addEventListener('click', () => hideTransferPanel()); bindQueueActions(panel); transferButton.classList.add('active'); transferButton.setAttribute('aria-expanded', 'true'); } function toggleSettingsPanel() { state.settingsPanelVisible = !state.settingsPanelVisible; renderSettingsPanel(); } function renderSettingsPanel() { const existing = appShell.querySelector('.settings-panel'); if (!state.settingsPanelVisible) { existing?.remove(); settingsButton.classList.remove('active'); settingsButton.setAttribute('aria-expanded', 'false'); return; } const panel = existing || document.createElement('aside'); panel.className = 'settings-panel'; panel.setAttribute('aria-label', 'Einstellungen'); panel.innerHTML = `
Einstellungen
`; if (!existing) { appShell.appendChild(panel); } const buttonRect = settingsButton.getBoundingClientRect(); const shellRect = appShell.getBoundingClientRect(); panel.style.right = `${Math.max(16, shellRect.right - buttonRect.right)}px`; panel.style.top = `${buttonRect.bottom - shellRect.top + 8}px`; panel.querySelector('[data-action="close-settings"]').addEventListener('click', () => { state.settingsPanelVisible = false; renderSettingsPanel(); }); panel.querySelector('[data-setting="debug"]').addEventListener('change', (event) => { saveSettings({ debug: event.currentTarget.checked }); }); panel.querySelector('[data-setting="write"]').addEventListener('change', (event) => { saveSettings({ readOnly: !event.currentTarget.checked }); }); panel.querySelector('[data-setting="thumbnails"]').addEventListener('change', (event) => { saveSettings({ thumbnails: event.currentTarget.checked }); }); panel.querySelector('[data-setting="systemRoot"]').addEventListener('change', async (event) => { const input = event.currentTarget; if (input.checked) { const confirmed = await showConfirmDialog( 'Ganzes System anzeigen', 'Der Navigator zeigt dann zusätzlich das komplette Dateisystem ab "/" – mit Root-Rechten.', 'Ordner direkt unter "/", /boot und die Mountpunkte unter /mnt bleiben vor Löschen, Verschieben und Rechteänderungen geschützt. Alles darunter lässt sich bei aktivem Schreibzugriff ändern – auch Systemdateien. /proc, /sys, /dev und /run werden nur angezeigt.', { confirmLabel: 'Aktivieren', danger: true } ); if (!confirmed) { input.checked = false; return; } } await saveSettings({ systemRoot: input.checked }); if (!input.checked) { for (const win of state.windows.filter((item) => item.kind === 'explorer' && !rootForPath(item.data.path))) { loadExplorer(win, state.config.roots[0].path); } } }); settingsButton.classList.add('active'); settingsButton.setAttribute('aria-expanded', 'true'); } async function saveSettings(changes) { const body = new URLSearchParams(); const readOnly = changes.readOnly ?? state.config.readOnly; const debug = changes.debug ?? state.config.debug; body.set('readOnly', readOnly ? '1' : '0'); body.set('debug', debug ? '1' : '0'); body.set('thumbnails', (changes.thumbnails ?? state.config.thumbnails) ? '1' : '0'); body.set('systemRoot', (changes.systemRoot ?? state.config.systemRoot) ? '1' : '0'); appendCsrf(body); try { state.config = await api(apiUrl('config.php'), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body }); updateStatusText(); if (!state.config.debug) { state.debug = []; } render(); } catch (error) { showError(error); } } function updateStatusText() { if (!state.config) return; statusText.textContent = `${state.config.roots.length} Root, ${state.config.readOnly ? 'Read-only' : 'Schreibzugriff aktiv'} · Debug ${state.config.debug ? 'aktiv' : 'aus'} · ${APP_VERSION}`; } function isReadOnly() { return Boolean(state.config?.readOnly); } async function loadExplorer(win, targetPath, options = {}) { const previousPath = win.data.path; win.data.loading = true; win.data.error = null; win.data.path = targetPath; if (normalizePath(previousPath) !== normalizePath(targetPath)) { win.data.filter = ''; closeSearch(win); } render(); try { const result = await api(apiUrl(`list.php?path=${encodeURIComponent(targetPath)}`)); win.data.path = result.path; win.data.entries = result.entries; if (!options.fromHistory) pushHistory(win, result.path); cacheTreeChildren(win, result.path, result.entries); await hydrateTreePath(win, result.path); reconcileExplorerSelection(win); if (options.select) { win.data.selectedPaths = [options.select]; win.data.selectedPath = options.select; win.data.selectionAnchorPath = options.select; } loadExplorerStorage(win); } catch (error) { win.data.error = error.message; win.data.path = previousPath || targetPath; } finally { win.data.loading = false; render(); if (options.select) scrollEntryIntoView(win, options.select); } } async function loadTreeChildren(win, path) { if (win.data.treeChildren?.[path] !== undefined) { render(); return; } const loading = new Set(win.data.treeLoading || []); loading.add(path); win.data.treeLoading = [...loading]; render(); try { const result = await api(apiUrl(`list.php?path=${encodeURIComponent(path)}`)); cacheTreeChildren(win, result.path, result.entries); } catch (error) { win.data.treeChildren = { ...(win.data.treeChildren || {}), [path]: [] }; showError(error); } finally { win.data.treeLoading = (win.data.treeLoading || []).filter((item) => item !== path); render(); } } function cacheTreeChildren(win, path, entries) { win.data.treeChildren = { ...(win.data.treeChildren || {}), [path]: (entries || []).filter((entry) => entry.type === 'directory') }; } async function hydrateTreePath(win, targetPath) { const root = rootForPath(targetPath); if (!root) return; const relative = normalizePath(targetPath).slice(normalizePath(root.path).length).split('/').filter(Boolean); const paths = [normalizePath(root.path)]; for (const part of relative) paths.push(joinPath(paths.at(-1), part)); win.data.treeExpanded = [...new Set([...(win.data.treeExpanded || []), ...paths])]; for (const path of paths.slice(0, -1)) { if (win.data.treeChildren?.[path] !== undefined) continue; try { const result = await api(apiUrl(`list.php?path=${encodeURIComponent(path)}`)); cacheTreeChildren(win, result.path, result.entries); } catch { win.data.treeChildren = { ...(win.data.treeChildren || {}), [path]: [] }; } } } function rootForPath(path) { const normalized = normalizePath(path); return (state.config?.roots || []) .filter((root) => normalized === normalizePath(root.path) || isPathInside(normalized, root.path)) .sort((a, b) => b.path.length - a.path.length)[0] || null; } async function handleDrop(event, win, targetPath) { const uploadItems = await getDroppedUploadItems(event); recordDebug('html.drop', { targetPath, types: dataTransferTypes(event), files: uploadItems.map((item) => ({ name: item.path, size: item.file.size })) }); if (state.config.readOnly) { showError(new Error('Read-only mode ist aktiv.')); return; } if (uploadItems.length) { await uploadFileList(win, uploadItems, targetPath); } } async function uploadFileList(win, files, targetPath) { if (isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } if (!files.length) return; const uploadItems = normalizeUploadItems(files); const transfer = createUploadTransfer(targetPath, uploadItems); let overwriteAll = false; for (const [index, item] of uploadItems.entries()) { updateUploadTransfer(transfer, { status: 'running', currentFile: item.path, currentIndex: index + 1 }); recordDebug('upload.file.request', { path: item.path, size: item.file.size, index: index + 1, total: uploadItems.length }); try { await uploadFileChunked(targetPath, item.file, item.path, false, (bytes) => { addUploadProgress(transfer, bytes); }); updateUploadTransfer(transfer, { completedFiles: transfer.completedFiles + 1, currentFile: item.path, progress: uploadProgressPercent(transfer) }); recordDebug('upload.file.done', { path: item.path, index: index + 1, total: uploadItems.length, overwrite: false }); } catch (error) { if (error.status !== 409) { if (isLocalFileReadError(error)) { updateUploadTransfer(transfer, { skippedFiles: transfer.skippedFiles + 1, skippedBytes: transfer.skippedBytes + Number(item.file.size || 0), currentFile: item.path, progress: uploadProgressPercent(transfer) }, true); recordDebug('upload.file.unreadable', { path: item.path, index: index + 1, total: uploadItems.length, error: serializeError(error) }); continue; } updateUploadTransfer(transfer, { status: 'failed', message: error.message || 'Upload fehlgeschlagen', currentFile: item.path, progress: uploadProgressPercent(transfer) }, true); throw error; } const conflictAction = overwriteAll ? 'overwrite' : await askUploadConflict({ path: item.path, targetPath, index: index + 1, total: uploadItems.length }); if (conflictAction === 'overwrite-all') { overwriteAll = true; } const overwrite = overwriteAll || conflictAction === 'overwrite'; recordDebug('upload.overwrite.prompt', { path: item.path, action: conflictAction, overwrite }); if (!overwrite) { updateUploadTransfer(transfer, { skippedFiles: transfer.skippedFiles + 1, skippedBytes: transfer.skippedBytes + Number(item.file.size || 0), currentFile: item.path, progress: uploadProgressPercent(transfer) }); recordDebug('upload.file.skipped', { path: item.path, index: index + 1, total: uploadItems.length }); continue; } await uploadFileChunked(targetPath, item.file, item.path, true, (bytes) => { addUploadProgress(transfer, bytes); }); updateUploadTransfer(transfer, { completedFiles: transfer.completedFiles + 1, overwrittenFiles: transfer.overwrittenFiles + 1, currentFile: item.path, progress: uploadProgressPercent(transfer) }); recordDebug('upload.file.done', { path: item.path, index: index + 1, total: uploadItems.length, overwrite: true }); } } updateUploadTransfer(transfer, { status: 'completed', message: 'Abgeschlossen', currentFile: '', progress: 100 }, true); scheduleTransferAutoHide(); await loadExplorer(win, targetPath); } async function uploadFileChunked(targetPath, file, relativePath, overwrite = false, onChunkUploaded = null) { const chunkSize = 256 * 1024; const totalChunks = Math.max(1, Math.ceil(file.size / chunkSize)); let finalPayload = null; for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex += 1) { const start = chunkIndex * chunkSize; const chunk = file.slice(start, Math.min(file.size, start + chunkSize)); const data = arrayBufferToBase64(await chunk.arrayBuffer()); const body = new URLSearchParams(); body.set('uploadMode', 'chunk'); body.set('relativePath', relativePath); body.set('chunkIndex', String(chunkIndex)); body.set('totalChunks', String(totalChunks)); body.set('data', data); if (overwrite) { body.set('overwrite', '1'); } appendCsrf(body); const response = await fetch(apiUrl(`upload.php?path=${encodeURIComponent(targetPath)}`), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body }); const text = await response.text(); recordDebug('upload.chunk.response', { path: relativePath, chunk: chunkIndex + 1, totalChunks, status: response.status, ok: response.ok, contentType: response.headers.get('content-type'), body: text.slice(0, 1000) }); if (!response.ok) { const error = new Error(text || `${response.status} ${response.statusText}`); error.status = response.status; error.path = relativePath; throw error; } onChunkUploaded?.(chunk.size); try { finalPayload = JSON.parse(text); } catch (error) { throw new Error(`Upload lieferte keine JSON-Antwort: ${text.slice(0, 200) || response.headers.get('content-type') || 'leer'}`); } } if (!finalPayload?.uploaded?.length) { throw new Error('Upload wurde vom Server nicht bestätigt.'); } } function createUploadTransfer(targetPath, uploadItems) { const transfer = { id: `upload-${state.nextUploadTransferId++}`, status: 'queued', message: 'Wartet', targetPath, totalFiles: uploadItems.length, completedFiles: 0, skippedFiles: 0, overwrittenFiles: 0, totalBytes: uploadItems.reduce((sum, item) => sum + Number(item.file?.size || 0), 0), uploadedBytes: 0, skippedBytes: 0, currentFile: '', currentIndex: 0, progress: 0, updatedAt: Date.now(), lastRenderAt: 0 }; state.uploadTransfers.set(transfer.id, transfer); showTransferPanel(); updateTransferPanel(); return transfer; } function updateUploadTransfer(transfer, patch, force = false) { Object.assign(transfer, patch, { message: patch.message ?? `${transfer.currentIndex || 0}/${transfer.totalFiles}`, updatedAt: Date.now() }); const now = Date.now(); if (force || now - transfer.lastRenderAt > 180) { transfer.lastRenderAt = now; updateTransferPanel(); } } function addUploadProgress(transfer, bytes) { transfer.uploadedBytes += Number(bytes || 0); updateUploadTransfer(transfer, { progress: uploadProgressPercent(transfer) }); } function uploadProgressPercent(transfer) { if (transfer.totalBytes > 0) { return ((transfer.uploadedBytes + transfer.skippedBytes) / transfer.totalBytes) * 100; } if (transfer.totalFiles > 0) { return ((transfer.completedFiles + transfer.skippedFiles) / transfer.totalFiles) * 100; } return 0; } function isLocalFileReadError(error) { return error?.name === 'NotReadableError' || error?.name === 'NotFoundError' || error?.name === 'SecurityError'; } function arrayBufferToBase64(buffer) { const bytes = new Uint8Array(buffer); let binary = ''; for (let index = 0; index < bytes.length; index += 0x8000) { binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000)); } return btoa(binary); } function normalizeUploadItems(files) { return files.map((item) => { if (item?.file && item?.path) { return item; } const file = item; return { file, path: file.webkitRelativePath || file.name }; }).filter((item) => item.file && item.path); } async function createJob(type, source, destination = null, refreshWindowIds = [], extra = {}, options = {}) { if (['move', 'copy', 'permissions', 'fixperms', 'delete', 'extract', 'compress'].includes(type) && isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return null; } recordDebug('job.create.request', { type, source, destination, refreshWindowIds, extra }); const body = new URLSearchParams(); if (source !== null) { body.set('source', source); } if (destination !== null) { body.set('destination', destination); } for (const [key, value] of Object.entries(extra)) { if (value !== null && value !== undefined) { body.set(key, String(value)); } } appendCsrf(body); const job = await api(apiUrl(`job.php?action=${encodeURIComponent(type)}`), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body }); recordDebug('job.create.response', job); state.jobs.set(job.id, job); state.jobRefresh.set(job.id, { windowIds: [...new Set(refreshWindowIds)].filter(Boolean), done: false }); if (!options.silent) showTransferPanel(); pollJob(job.id); updateTransferPanel(); return job; } async function createSizeJob(entry) { recordDebug('size.create.request', { source: entry.path }); const body = new URLSearchParams(); body.set('source', entry.path); appendCsrf(body); const job = await api(apiUrl('job.php?action=size'), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body }); recordDebug('size.create.response', job); state.jobs.set(job.id, job); state.sizeJobs.set(entry.path, job.id); pollJob(job.id); render(); return job; } async function reloadExplorerWindows(ids) { const uniqueIds = new Set(ids); const targets = state.windows.filter((win) => win.kind === 'explorer' && (uniqueIds.has(win.id) || !uniqueIds.size)); await Promise.all(targets.map((win) => loadExplorer(win, win.data.path))); } function hasDropPayload(event) { const types = dataTransferTypes(event); return types.includes('Files') || getDroppedFiles(event).length > 0; } async function getDroppedUploadItems(event) { const entries = getDroppedEntries(event); if (entries.length) { const items = []; for (const entry of entries) { items.push(...await readDroppedEntry(entry, '')); } if (items.length) { return items; } } return getDroppedFiles(event).filter((file) => file.size > 0 || file.type || file.name.includes('.')).map((file) => ({ file, path: file.webkitRelativePath || file.name })); } function getDroppedEntries(event) { try { return [...(event.dataTransfer?.items || [])] .map((item) => item.webkitGetAsEntry?.()) .filter(Boolean); } catch (error) { recordDebug('dataTransfer.entries.error', serializeError(error)); return []; } } async function readDroppedEntry(entry, parentPath) { const path = parentPath ? `${parentPath}/${entry.name}` : entry.name; if (entry.isFile) { const file = await new Promise((resolve, reject) => entry.file(resolve, reject)); return [{ file, path }]; } if (!entry.isDirectory) { return []; } const reader = entry.createReader(); const children = await readAllDirectoryEntries(reader); const results = []; for (const child of children) { results.push(...await readDroppedEntry(child, path)); } return results; } async function readAllDirectoryEntries(reader) { const entries = []; while (true) { const batch = await new Promise((resolve, reject) => reader.readEntries(resolve, reject)); if (!batch.length) { return entries; } entries.push(...batch); } } function showError(error) { const debug = recordDebug('error.shown', serializeError(error)); const message = error?.message || String(error); const detail = debug ? `Debug #${debug.id}: ${debug.label}` : ''; showMessageDialog('Fehler', message, detail).catch(() => {}); } function getDroppedFiles(event) { try { return [...(event.dataTransfer?.files || [])]; } catch { return []; } } function dataTransferTypes(event) { try { return [...(event.dataTransfer?.types || [])]; } catch (error) { recordDebug('dataTransfer.types.error', serializeError(error)); return []; } } function setEffectAllowed(event) { try { event.dataTransfer.effectAllowed = 'copyMove'; } catch (error) { recordDebug('dataTransfer.effectAllowed.error', serializeError(error)); } } function setDropEffect(event, effect) { try { event.dataTransfer.dropEffect = effect; } catch { recordDebug('dataTransfer.dropEffect.error', { effect }); } } async function renameEntry(win, entry) { if (isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } const nextName = await showPromptDialog('Umbenennen', 'Neuer Name', entry.name); if (!nextName || nextName === entry.name) { return; } if (!isValidName(nextName)) { showError(new Error('Ungültiger Name. Ein Name darf keinen Schrägstrich enthalten und nicht "." oder ".." sein.')); return; } try { await createJob('move', entry.path, `${dirname(entry.path)}/${nextName}`, [win.id], {}, { silent: true }); } catch (error) { if (isConflictError(error)) { showError(new Error(`"${nextName}" existiert in diesem Ordner bereits.`)); return; } throw error; } } async function promptTransfer(win, entry, type) { if (isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } const targetDir = await showPromptDialog( type === 'copy' ? 'Kopieren' : 'Verschieben', type === 'copy' ? 'Kopieren nach Ordner' : 'Verschieben nach Ordner', win.data.path ); if (!targetDir) { return; } const items = selectedPathSet(win).has(entry.path) ? selectedEntries(win) : [entry]; await runTransfers(type, items, targetDir.replace(/\/$/, '') || '/', [win.id, ...explorerIdsShowing(targetDir)]); } async function deleteEntries(win, entry = null) { if (isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } const entries = entry && selectedPathSet(win).has(entry.path) ? selectedEntries(win) : (entry ? [entry] : selectedEntries(win)); if (!entries.length) { showError(new Error('Keine Datei ausgewählt.')); return; } const folders = entries.filter((item) => item.type === 'directory').length; const label = entries.length === 1 ? `"${entries[0].name}" endgültig löschen?` : `${entries.length} Elemente endgültig löschen?`; const confirmed = await showUiDialog({ type: 'confirm', title: 'Endgültig löschen', message: label, detail: `Unraid hat keinen Papierkorb – gelöschte Dateien lassen sich nicht wiederherstellen.${folders ? ` ${folders === 1 ? 'Der Ordner wird' : 'Die Ordner werden'} samt Inhalt gelöscht.` : ''}`, items: entries.map((item) => `${item.type === 'directory' ? '📁 ' : ''}${item.name}`), confirmLabel: entries.length === 1 ? 'Endgültig löschen' : `${entries.length} Elemente löschen`, cancelLabel: 'Abbrechen', danger: true }); if (!confirmed) { return; } for (const item of entries) { await createJob('delete', item.path, null, [win.id]); } if (state.clipboard) { const removed = new Set(entries.map((item) => item.path)); state.clipboard.items = state.clipboard.items.filter((item) => !removed.has(item.path)); if (!state.clipboard.items.length) state.clipboard = null; } } function openPermissionsDialog(win, entry) { if (isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } const entries = selectedPathSet(win).has(entry.path) ? selectedEntries(win) : [entry]; state.permissionsDialog = { winId: win.id, entries, mode: normalizeMode(entry.permissions || '0755'), owner: entry.owner || '', group: entry.group || '', recursive: false, hasDirectory: entries.some((item) => item.type === 'directory') }; render(); } function downloadEntries(win, entry = null) { const entries = entry && selectedPathSet(win).has(entry.path) ? selectedEntries(win) : (entry ? [entry] : [{ path: win.data.path, name: basename(win.data.path), type: 'directory' }]); const paths = entries.map((item) => item.path); const query = paths.length === 1 ? `path=${encodeURIComponent(paths[0])}` : `paths=${encodeURIComponent(JSON.stringify(paths))}`; recordDebug('download.start', { paths }); const link = document.createElement('a'); link.href = apiUrl(`download.php?${query}`); link.download = ''; document.body.appendChild(link); link.click(); link.remove(); } function renderPermissionsDialog() { const dialog = state.permissionsDialog; const overlay = document.createElement('div'); overlay.className = 'modal-overlay'; overlay.innerHTML = `
Berechtigungen ändern
`; const form = overlay.querySelector('form'); form.addEventListener('click', (event) => event.stopPropagation()); overlay.addEventListener('click', () => closePermissionsDialog()); overlay.querySelectorAll('[data-action="cancel"]').forEach((button) => { button.addEventListener('click', () => closePermissionsDialog()); }); for (const checkboxName of ['changeMode', 'changeOwner', 'changeGroup']) { const checkbox = form.elements[checkboxName]; const inputName = checkboxName.replace('change', '').toLowerCase(); const input = form.elements[inputName]; checkbox.addEventListener('change', () => { input.disabled = !checkbox.checked; if (!input.disabled) input.focus(); }); } bindPermissionMatrix(form); form.addEventListener('submit', (event) => { event.preventDefault(); applyPermissionsDialog(form).catch(showError); }); return overlay; } function askUploadConflict(details) { return new Promise((resolve) => { state.uploadConflictDialog = { ...details, resolve }; render(); }); } function renderUploadConflictDialog() { const dialog = state.uploadConflictDialog; const overlay = document.createElement('div'); overlay.className = 'modal-overlay'; overlay.innerHTML = `
Datei existiert bereits
`; const form = overlay.querySelector('form'); form.addEventListener('click', (event) => event.stopPropagation()); overlay.addEventListener('click', () => closeUploadConflictDialog('skip')); overlay.querySelectorAll('[data-action="skip"]').forEach((button) => { button.addEventListener('click', () => closeUploadConflictDialog('skip')); }); overlay.querySelector('[data-action="overwrite"]').addEventListener('click', () => closeUploadConflictDialog('overwrite')); form.addEventListener('submit', (event) => { event.preventDefault(); closeUploadConflictDialog('overwrite-all'); }); setTimeout(() => { form.querySelector('.primary')?.focus(); }, 0); return overlay; } function closeUploadConflictDialog(action) { const dialog = state.uploadConflictDialog; if (!dialog) return; state.uploadConflictDialog = null; dialog.resolve(action); render(); } function showMessageDialog(title, message, detail = '') { return showUiDialog({ type: 'message', title, message, detail, confirmLabel: 'OK' }); } function showConfirmDialog(title, message, detail = '', options = {}) { return showUiDialog({ type: 'confirm', title, message, detail, confirmLabel: options.confirmLabel || 'OK', cancelLabel: options.cancelLabel || 'Abbrechen', danger: Boolean(options.danger) }); } function showPromptDialog(title, label, value = '') { return showUiDialog({ type: 'prompt', title, message: label, value, confirmLabel: 'OK', cancelLabel: 'Abbrechen' }); } function showUiDialog(options) { return new Promise((resolve) => { state.uiDialog = { ...options, resolve }; render(); }); } function renderUiDialog() { const dialog = state.uiDialog; const overlay = document.createElement('div'); overlay.className = 'modal-overlay'; const isPrompt = dialog.type === 'prompt'; const isConfirm = dialog.type === 'confirm'; const isChoice = dialog.type === 'choice'; const listItems = dialog.items || []; const listMarkup = listItems.length ? ` ` : ''; const rowsMarkup = (dialog.rows || []).length ? `
${dialog.rows.map(([label, value]) => `
${escapeHtml(label)}
${escapeHtml(value)}
`).join('')}
` : ''; overlay.innerHTML = `
${escapeHtml(dialog.title)}
`; const form = overlay.querySelector('form'); form.addEventListener('click', (event) => event.stopPropagation()); overlay.addEventListener('click', () => closeUiDialog(cancelDialogValue(dialog))); overlay.querySelectorAll('[data-action="cancel"]').forEach((button) => { button.addEventListener('click', () => closeUiDialog(cancelDialogValue(dialog))); }); overlay.querySelectorAll('[data-choice]').forEach((button) => { button.addEventListener('click', () => closeUiDialog({ value: button.dataset.choice, applyAll: Boolean(form.elements.applyAll?.checked) })); }); form.addEventListener('submit', (event) => { event.preventDefault(); if (isPrompt) { closeUiDialog(form.elements.value.value); return; } if (isChoice) { form.querySelector('[data-choice].primary')?.click(); return; } closeUiDialog(isConfirm ? true : undefined); }); setTimeout(() => { const focusTarget = isPrompt ? form.elements.value : (form.querySelector('.primary') || form.querySelector('[data-choice]')); focusTarget?.focus(); if (isPrompt) { focusTarget.select(); } }, 0); return overlay; } function cancelDialogValue(dialog) { if (dialog.type === 'confirm') return false; if (dialog.type === 'choice') return { value: 'cancel', applyAll: false }; if (dialog.type === 'prompt') return null; return undefined; } function closeUiDialog(value) { const dialog = state.uiDialog; if (!dialog) return; state.uiDialog = null; dialog.resolve(value); render(); } function permissionMatrixMarkup(mode) { const digits = modeToDigits(mode); const rows = [ ['owner', 'Besitzer-Berechtigungen', digits[0]], ['group', 'Gruppen-Berechtigungen', digits[1]], ['public', 'Öffentliche Berechtigungen', digits[2]] ]; return rows.map(([scope, label, digit]) => `
${label} ${permissionCheck(scope, 'read', 'Lesen', digit & 4)} ${permissionCheck(scope, 'write', 'Schreiben', digit & 2)} ${permissionCheck(scope, 'execute', 'Ausführen', digit & 1)}
`).join(''); } function permissionCheck(scope, bit, label, checked) { return ` `; } function bindPermissionMatrix(form) { const changeMode = form.elements.changeMode; const modeInput = form.elements.mode; const permissionInputs = [...form.querySelectorAll('[data-permission]')]; const setModeDisabled = () => { modeInput.disabled = !changeMode.checked; for (const input of permissionInputs) { input.disabled = !changeMode.checked; } }; changeMode.addEventListener('change', setModeDisabled); for (const input of permissionInputs) { input.addEventListener('change', () => { changeMode.checked = true; setModeDisabled(); modeInput.value = modeFromPermissionInputs(form); }); } modeInput.addEventListener('input', () => { changeMode.checked = true; setModeDisabled(); syncPermissionInputsFromMode(form, modeInput.value); }); setModeDisabled(); } function modeFromPermissionInputs(form) { const scopes = ['owner', 'group', 'public']; const values = scopes.map((scope) => { let value = 0; if (form.querySelector(`[data-permission="${scope}.read"]`)?.checked) value += 4; if (form.querySelector(`[data-permission="${scope}.write"]`)?.checked) value += 2; if (form.querySelector(`[data-permission="${scope}.execute"]`)?.checked) value += 1; return String(value); }); return values.join(''); } function syncPermissionInputsFromMode(form, mode) { if (!/^[0-7]{3,4}$/.test(mode)) return; const digits = modeToDigits(mode); for (const [index, scope] of ['owner', 'group', 'public'].entries()) { const digit = digits[index]; const map = { read: 4, write: 2, execute: 1 }; for (const [bit, value] of Object.entries(map)) { const input = form.querySelector(`[data-permission="${scope}.${bit}"]`); if (input) input.checked = Boolean(digit & value); } } } function normalizeMode(mode) { const value = String(mode || ''); if (!/^[0-7]{3,4}$/.test(value)) return '755'; return value.length === 4 ? value.slice(1) : value; } function modeToDigits(mode) { const normalized = normalizeMode(mode); return normalized.split('').slice(-3).map((digit) => Number(digit)); } function closePermissionsDialog() { state.permissionsDialog = null; render(); } async function applyPermissionsDialog(form) { const dialog = state.permissionsDialog; if (!dialog) return; const options = { mode: form.elements.changeMode.checked ? form.elements.mode.value.trim() : '', owner: form.elements.changeOwner.checked ? form.elements.owner.value.trim() : '', group: form.elements.changeGroup.checked ? form.elements.group.value.trim() : '', recursive: form.elements.recursive.checked ? '1' : '0' }; if (!options.mode && !options.owner && !options.group) { showError(new Error('Keine Änderung angegeben.')); return; } if (options.mode && !/^[0-7]{3,4}$/.test(options.mode)) { showError(new Error('Berechtigungen müssen aus 3 oder 4 Oktalziffern bestehen.')); return; } const win = state.windows.find((item) => item.id === dialog.winId); closePermissionsDialog(); for (const item of dialog.entries) { await createJob('permissions', item.path, null, [win?.id], options); } } function showPropertiesForEntry(win, entry) { selectEntry(win, entry); openProperties(entry); } function showContextMenu(event, win, entry) { const rect = workspace.getBoundingClientRect(); state.contextMenu = { x: event.clientX - rect.left, y: event.clientY - rect.top, winId: win.id, entryPath: entry?.path || null }; render(); } function renderContextMenu() { const menu = document.createElement('div'); menu.className = 'context-menu'; menu.style.left = `${state.contextMenu.x}px`; menu.style.top = `${state.contextMenu.y}px`; const win = state.windows.find((item) => item.id === state.contextMenu.winId); const entry = currentItems(win).find((item) => item.path === state.contextMenu.entryPath) || null; const actions = contextMenuActions(win, entry); for (const item of actions) { if (item.separator) { const separator = document.createElement('div'); separator.className = 'context-separator'; separator.setAttribute('role', 'separator'); menu.appendChild(separator); } const button = document.createElement('button'); button.type = 'button'; button.className = `context-action ${item.danger ? 'danger' : ''}`; button.innerHTML = `${iconSvg(item.icon)}${escapeHtml(item.label)}${item.hint ? `${escapeHtml(item.hint)}` : ''}`; button.addEventListener('click', async () => { state.contextMenu = null; render(); try { await item.action(); } catch (error) { showError(error); } }); menu.appendChild(button); } // Keep tall menus inside the workspace instead of running off the bottom/right edge. requestAnimationFrame(() => { const bounds = workspace.getBoundingClientRect(); const rect = menu.getBoundingClientRect(); if (rect.bottom > bounds.bottom) { menu.style.top = `${Math.max(4, state.contextMenu ? state.contextMenu.y - rect.height : 4)}px`; } if (rect.right > bounds.right) { menu.style.left = `${Math.max(4, bounds.width - rect.width - 4)}px`; } }); setTimeout(() => { const close = () => { state.contextMenu = null; render(); document.removeEventListener('click', close); document.removeEventListener('keydown', keyClose); }; const keyClose = (event) => { if (event.key === 'Escape') close(); }; document.addEventListener('click', close); document.addEventListener('keydown', keyClose); }, 0); return menu; } async function pollJob(id) { try { const job = await api(apiUrl(`job.php?id=${encodeURIComponent(id)}`)); if (state.jobs.get(id)?.status === 'cancel_requested' && isJobActive(job)) { job.status = 'cancel_requested'; } recordJobSample(job); state.jobs.set(id, job); updateTransferPanel(); if (job.type === 'search') { updateSearchFromJob(job); } if (isJobActive(job)) { setTimeout(() => pollJob(id), 700); } else if (job.type === 'size') { finishSizeJob(job); } else { if (job.status === 'completed' && ['move', 'delete'].includes(job.type)) { updateFavoritesAfterJob(job); } await refreshAfterJob(job); if (['checksum', 'compare'].includes(job.type) && job.status === 'completed') { showJobResult(job); } else if (job.status === 'failed' && !['search'].includes(job.type)) { showError(new Error(`${jobTypeLabel(job.type)} fehlgeschlagen: ${job.error || job.message}`)); } scheduleTransferAutoHide(); } } catch (error) { recordDebug('job.poll.error', { id, error: serializeError(error) }); showError(error); } } function ensureDirectorySize(entry) { if (state.sizeResults.has(entry.path) || state.sizeJobs.has(entry.path)) { return; } state.sizeJobs.set(entry.path, 'pending'); createSizeJob(entry).catch((error) => { state.sizeJobs.delete(entry.path); showError(error); }); } function finishSizeJob(job) { state.sizeJobs.delete(job.source); if (job.status === 'completed' && job.result) { state.sizeResults.set(job.source, job.result); } recordDebug('size.finish', { id: job.id, source: job.source, status: job.status, result: job.result || null }); updatePropertiesWindows(); } async function refreshAfterJob(job) { const refresh = state.jobRefresh.get(job.id); if (refresh?.done) { return; } if (refresh) { refresh.done = true; } const windowIds = refresh?.windowIds || []; recordDebug('job.refresh', { id: job.id, status: job.status, windowIds }); await reloadExplorerWindows(windowIds); if (refresh) { state.jobRefresh.delete(job.id); } } function selectEntry(win, entry, scrollBody = null, event = null) { if (state.suppressClickPath === entry.path) { state.suppressClickPath = null; restoreExplorerScroll(win, scrollBody); return; } applyExplorerSelection(win, entry, event); state.selectedEntry = entry; focusWindow(win); updateSelectedRows(); updatePropertiesWindows(); restoreExplorerScroll(win, scrollBody); } function applyExplorerSelection(win, entry, event = null) { const entries = visibleEntries(win); const current = selectedPathSet(win); const toggle = Boolean(event?.ctrlKey || event?.metaKey); const range = Boolean(event?.shiftKey && win.data.selectionAnchorPath); if (range) { const anchorIndex = entries.findIndex((item) => item.path === win.data.selectionAnchorPath); const entryIndex = entries.findIndex((item) => item.path === entry.path); if (anchorIndex >= 0 && entryIndex >= 0) { const [start, end] = anchorIndex < entryIndex ? [anchorIndex, entryIndex] : [entryIndex, anchorIndex]; const paths = entries.slice(start, end + 1).map((item) => item.path); win.data.selectedPaths = toggle ? [...new Set([...current, ...paths])] : paths; } else { win.data.selectedPaths = [entry.path]; win.data.selectionAnchorPath = entry.path; } } else if (toggle) { if (current.has(entry.path)) { current.delete(entry.path); } else { current.add(entry.path); } win.data.selectedPaths = [...current]; win.data.selectionAnchorPath = entry.path; } else { win.data.selectedPaths = [entry.path]; win.data.selectionAnchorPath = entry.path; } win.data.selectedPath = entry.path; if (!win.data.selectedPaths.length) { win.data.selectedPath = null; win.data.selectionAnchorPath = null; } } function reconcileExplorerSelection(win) { const available = new Set(currentItems(win).map((entry) => entry.path)); win.data.selectedPaths = (win.data.selectedPaths || []).filter((path) => available.has(path)); if (!available.has(win.data.selectedPath)) { win.data.selectedPath = win.data.selectedPaths[0] || null; } if (!available.has(win.data.selectionAnchorPath)) { win.data.selectionAnchorPath = win.data.selectedPath; } if (state.selectedEntry && !available.has(state.selectedEntry.path) && state.focusedId === win.id) { state.selectedEntry = null; } } function selectedPathSet(win) { return new Set(win?.data?.selectedPaths || (win?.data?.selectedPath ? [win.data.selectedPath] : [])); } function selectedEntries(win) { const paths = selectedPathSet(win); return currentItems(win).filter((entry) => paths.has(entry.path)); } function shouldSuppressItemActivation() { if (Date.now() <= state.suppressItemActivationUntil) { recordDebug('item.activation.suppressed', { until: state.suppressItemActivationUntil }); return true; } return false; } function focusWindow(win) { state.focusedId = win.id; win.zIndex = ++state.zIndex; for (const windowEl of workspace.querySelectorAll('.window')) { windowEl.classList.toggle('focused', windowEl.dataset.windowId === win.id); } const current = workspace.querySelector(`.window[data-window-id="${win.id}"]`); if (current) { current.style.zIndex = win.zIndex; } } function updateSelectedRows() { for (const win of state.windows.filter((item) => item.kind === 'explorer')) { const selected = selectedPathSet(win); for (const row of workspace.querySelectorAll(`.window[data-window-id="${win.id}"] .file-row`)) { row.classList.toggle('selected', selected.has(row.dataset.path)); } updateStatusbar(win); } } function handleTypeAheadKey(event) { if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return; if (state.contextMenu || state.settingsPanelVisible) return; if (isTypingTarget(document.activeElement)) return; if (event.key.length !== 1) return; const key = event.key.toLocaleLowerCase(); if (!/^[\p{L}\p{N}]$/u.test(key)) return; const win = state.windows.find((item) => item.id === state.focusedId && item.kind === 'explorer'); if (!win || !visibleEntries(win).length) return; const now = Date.now(); const sameWindow = state.typeAhead.windowId === win.id; const withinWindow = now - state.typeAhead.at < 1000; const sequence = sameWindow && withinWindow ? (state.typeAhead.sequence || '') : ''; // Gleicher Buchstabe kurz nach einander = nächstes Vorkommen dieses Buchstabens // (z. B. "AA" springt zum zweiten A-Eintrag), statt die Folge zu verdoppeln. const repeated = sameWindow && withinWindow && state.typeAhead.key === key && sequence.length <= 1; let next = repeated ? key : sequence + key; if (!repeated && next.length > 16) next = key; const entries = visibleEntries(win); const selectedIndex = entries.findIndex((entry) => entry.path === win.data.selectedPath); const startIndex = Math.max(0, selectedIndex + 1); const match = findTypeAheadMatch(entries, next, startIndex, repeated); if (!match) { // Unvollständiger Pfad ohne Treffer: Auswahl bleibt, Folge wird verworfen if (sequence) state.typeAhead = { key, sequence: '', windowId: win.id, at: now }; return; } event.preventDefault(); state.typeAhead = { key, sequence: next, windowId: win.id, at: now }; win.data.selectedPath = match.path; win.data.selectedPaths = [match.path]; win.data.selectionAnchorPath = match.path; state.selectedEntry = match; focusWindow(win); updateSelectedRows(); updatePropertiesWindows(); scrollEntryIntoView(win, match.path); recordDebug('typeahead.match', { sequence: next, path: match.path }); } function findTypeAheadMatch(entries, sequence, startIndex, preferNextOccurrence = false) { // Erst: Präfix-Treffer ab der aktuellen Position (mit Wraparound). // Zweit: Teiltreffer (z. B. "amy" findet "Amy Spring"), damit Tippfolgen auch bei // Präfix-Konkurrenz zum richtigen Eintrag springen. for (let pass = 0; pass < 2; pass += 1) { for (let offset = 0; offset < entries.length; offset += 1) { const index = (startIndex + offset) % entries.length; const entry = entries[index]; const name = entry.name?.toLocaleLowerCase(); if (!name) continue; const isMatch = pass === 0 ? name.startsWith(sequence) : name.includes(sequence) && !(preferNextOccurrence && sequence.length <= 1); if (isMatch) return entry; } } return null; } function scrollEntryIntoView(win, path) { const row = workspace.querySelector(`.window[data-window-id="${win.id}"] .file-row[data-path="${cssEscape(path)}"]`); row?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); } function isTypingTarget(element) { if (!element) return false; const tag = element.tagName; return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || element.isContentEditable; } function updatePropertiesWindows() { for (const win of state.windows.filter((item) => item.kind === 'properties')) { const body = workspace.querySelector(`.window[data-window-id="${win.id}"] .window-body`); if (body) { renderProperties(body); } } } function startItemPointerDrag(event, win, entry) { if (event.button !== 0 || !entry) return; const items = dragItemsForEntry(win, entry); recordDebug('pointer.start', { windowId: win.id, path: entry.path, type: entry.type, count: items.length, x: event.clientX, y: event.clientY }); state.pointerDrag = { sourceWindowId: win.id, path: entry.path, name: entry.name, type: entry.type, items, paths: items.map((item) => item.path), startX: event.clientX, startY: event.clientY, active: false, targetWindowId: null, targetPath: null }; const move = (moveEvent) => updateItemPointerDrag(moveEvent); const up = (upEvent) => finishItemPointerDrag(upEvent, move, up); document.addEventListener('pointermove', move); document.addEventListener('pointerup', up, { once: true }); try { event.currentTarget.setPointerCapture(event.pointerId); } catch {} } function updateItemPointerDrag(event) { const drag = state.pointerDrag; if (!drag) return; const distance = Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY); if (!drag.active && distance < 6) { return; } drag.active = true; event.preventDefault(); document.body.classList.add('u-nav-dragging'); markDraggingRows(drag.paths, true); updatePointerDropTarget(event); } async function finishItemPointerDrag(event, move, up) { document.removeEventListener('pointermove', move); document.removeEventListener('pointerup', up); const drag = state.pointerDrag; clearPointerDropTarget(); document.body.classList.remove('u-nav-dragging'); if (!drag) return; markDraggingRows(drag.paths, false); if (!drag.active) { state.pointerDrag = null; return; } event.preventDefault(); state.suppressClickPath = drag.path; state.suppressItemActivationUntil = Date.now() + 450; const target = findPointerDropTarget(event, drag); state.pointerDrag = null; recordDebug('pointer.finish', { source: drag.path, sources: drag.paths, target: target ? { windowId: target.windowId, path: target.path, rowPath: target.row?.dataset?.path || null } : null, copy: event.altKey, x: event.clientX, y: event.clientY }); if (!target) { return; } try { const jobs = drag.items.map((item) => ({ item, destination: joinPath(target.path, item.name) })); recordDebug('pointer.destination', { source: drag.path, sources: drag.paths, targetPath: target.path, destinations: jobs.map((job) => job.destination), targetIsRow: Boolean(target.row), copy: event.altKey }); validatePointerDropJobs(jobs, target.path); await runTransfers(event.altKey ? 'copy' : 'move', drag.items, target.path, [drag.sourceWindowId, target.windowId]); } catch (error) { showError(error); } } function dragItemsForEntry(win, entry) { const selected = selectedPathSet(win); if (selected.has(entry.path)) { const entries = selectedEntries(win); if (entries.length) return entries; } return [entry]; } function validatePointerDropJobs(jobs, targetPath) { const destinations = new Set(); for (const { item, destination } of jobs) { if (destinations.has(destination)) { throw new Error('Mehrere Quellen würden am Ziel denselben Namen verwenden.'); } destinations.add(destination); if (destination === item.path || targetPath === item.path) { throw new Error('Quelle und Ziel sind identisch.'); } if (item.type === 'directory' && isPathInside(targetPath, item.path)) { throw new Error('Ein Ordner kann nicht in sich selbst verschoben werden.'); } } } function updatePointerDropTarget(event) { clearPointerDropTarget(); const target = findPointerDropTarget(event); if (!target) return; state.pointerDrag.targetWindowId = target.windowId; state.pointerDrag.targetPath = target.path; const windowEl = workspace.querySelector(`.window[data-window-id="${target.windowId}"]`); windowEl?.querySelector('.drop-zone')?.classList.add('drag-over'); if (target.row) { target.row.classList.add('drop-target'); } } function clearPointerDropTarget() { for (const item of workspace.querySelectorAll('.drop-zone.drag-over')) { item.classList.remove('drag-over'); } for (const item of workspace.querySelectorAll('.file-row.drop-target')) { item.classList.remove('drop-target'); } for (const item of workspace.querySelectorAll('.tree-label.drop-target')) { item.classList.remove('drop-target'); } } function findPointerDropTarget(event, drag = state.pointerDrag) { let element; let elements = []; try { element = document.elementFromPoint(event.clientX, event.clientY); elements = document.elementsFromPoint ? document.elementsFromPoint(event.clientX, event.clientY) : [element]; } catch (error) { recordDebug('elementFromPoint.error', { x: event.clientX, y: event.clientY, error: serializeError(error) }); return null; } let windowEl; try { windowEl = element?.closest?.('.window'); } catch (error) { recordDebug('closest.window.error', { error: serializeError(error), element: element?.tagName }); return null; } if (!windowEl) return null; const win = state.windows.find((item) => item.id === windowEl.dataset.windowId); if (!win || win.kind !== 'explorer') return null; let row = null; let overEntry = false; for (const candidate of elements) { try { const treeTarget = candidate.closest?.('.tree-label[data-tree-open]'); if (treeTarget && treeTarget.closest?.('.window') === windowEl) { overEntry = true; } if (treeTarget && treeTarget.closest?.('.window') === windowEl && isValidPointerTargetPath(treeTarget.dataset.treeOpen, drag)) { row = treeTarget; break; } const candidateRow = candidate.closest?.('.file-row'); if (candidateRow && candidateRow.closest?.('.window') === windowEl) { overEntry = true; } if (!candidateRow || candidateRow.dataset.type !== 'directory') { continue; } if (drag?.paths?.includes(candidateRow.dataset.path)) { continue; } if (!isValidPointerTargetPath(candidateRow.dataset.path, drag)) { continue; } if (candidateRow.closest?.('.window') !== windowEl) { continue; } row = candidateRow; break; } catch (error) { recordDebug('closest.row.error', { error: serializeError(error), element: candidate?.tagName }); } } if (row) { return { windowId: win.id, path: row.dataset.path || row.dataset.treeOpen, row }; } if (overEntry) { return null; } return { windowId: win.id, path: win.data.path, row: null }; } function markDraggingRows(paths, dragging) { const pathSet = new Set(paths || []); for (const row of workspace.querySelectorAll('.file-row')) { if (pathSet.has(row.dataset.path)) { row.classList.toggle('dragging', dragging); } } } function isValidPointerTargetPath(path, drag = state.pointerDrag) { if (!drag) return false; return (drag.items || []).every((item) => { if (path === item.path) return false; return !(item.type === 'directory' && isPathInside(path, item.path)); }); } function lockExplorerScroll(win, body) { win.data.lockScroll = true; win.data.lockScrollTop = body.scrollTop; win.data.lockScrollLeft = body.scrollLeft; } function restoreExplorerScroll(win, body) { if (!body) { body = workspace.querySelector(`.window[data-window-id="${win.id}"] .explorer-content`) || workspace.querySelector(`.window[data-window-id="${win.id}"] .window-body`); } if (!body) return; const top = win.data.lockScrollTop ?? win.data.scrollTop ?? 0; const left = win.data.lockScrollLeft ?? win.data.scrollLeft ?? 0; const restore = () => { body.scrollTop = top; body.scrollLeft = left; }; restore(); requestAnimationFrame(restore); setTimeout(restore, 0); setTimeout(() => { restore(); win.data.lockScroll = false; win.data.scrollTop = body.scrollTop; win.data.scrollLeft = body.scrollLeft; }, 120); } function startDragWindow(event, win) { if (event.target.closest('button') || win.maximized) return; event.preventDefault(); const startX = event.clientX; const startY = event.clientY; const originX = win.x; const originY = win.y; const pointerId = event.pointerId; event.currentTarget.setPointerCapture(pointerId); const move = (moveEvent) => { win.x = clamp(originX + moveEvent.clientX - startX, 0, Math.max(0, workspace.clientWidth - 120)); win.y = clamp(originY + moveEvent.clientY - startY, 0, Math.max(0, workspace.clientHeight - 80)); render(); }; const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); }; window.addEventListener('pointermove', move); window.addEventListener('pointerup', up); } function startResizeWindow(event, win) { event.preventDefault(); event.stopPropagation(); const startX = event.clientX; const startY = event.clientY; const originWidth = win.width; const originHeight = win.height; const move = (moveEvent) => { win.width = Math.max(320, originWidth + moveEvent.clientX - startX); win.height = Math.max(280, originHeight + moveEvent.clientY - startY); render(); }; const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); }; window.addEventListener('pointermove', move); window.addEventListener('pointerup', up); } async function api(url, options) { const response = await fetchChecked(url, options); const text = await response.text(); try { return JSON.parse(text); } catch (error) { recordDebug('api.json.error', { url, status: response.status, contentType: response.headers.get('content-type'), body: text.slice(0, 2000), error: serializeError(error) }); throw error; } } async function fetchChecked(url, options) { recordDebug('fetch.request', { url, method: options?.method || 'GET' }); const response = await fetch(url, options); recordDebug('fetch.response', { url, status: response.status, ok: response.ok, contentType: response.headers.get('content-type') }); if (!response.ok) { let message = `${response.status} ${response.statusText}`; const text = await response.text(); try { message = JSON.parse(text).error || message; } catch {} recordDebug('fetch.error.body', { url, status: response.status, body: text.slice(0, 2000) }); throw new Error(message); } return response; } function windowTitle(win) { if (win.kind === 'explorer') { return `Explorer · ${win.data.path || ''}`; } if (win.kind === 'preview') { return `${win.data.editing ? 'Editor' : 'Vorschau'} · ${win.data.entry?.name || ''}`; } return win.title; } function parentPath(value) { const parts = String(value || '').split('/').filter(Boolean); if (parts.length <= 1) return '/'; return `/${parts.slice(0, -1).join('/')}`; } function dirname(value) { const parts = String(value || '').split('/').filter(Boolean); if (parts.length <= 1) return '/'; return `/${parts.slice(0, -1).join('/')}`; } function basename(value) { const parts = String(value || '').split('/').filter(Boolean); return parts[parts.length - 1] || ''; } function extensionOf(name) { const value = String(name || ''); const index = value.lastIndexOf('.'); return index >= 0 ? value.slice(index + 1).toLowerCase() : ''; } function isPreviewable(entry) { if (entry?.type !== 'file') return false; const name = String(entry.name || entry.path || '').toLowerCase(); // Files without an extension (e.g. /boot/config/go) are checked by the server for text content. return previewFilenames.has(name) || previewExtensions.has(extensionOf(name)) || !name.slice(1).includes('.'); } function joinPath(parent, name) { return `${String(parent || '').replace(/\/+$/, '')}/${String(name || '').replace(/^\/+/, '')}`; } function normalizePath(value) { const parts = String(value || '').split('/').filter(Boolean); return `/${parts.join('/')}`; } function isPathInside(path, parent) { const normalizedPath = normalizePath(path); const normalizedParent = normalizePath(parent); return normalizedPath.startsWith(`${normalizedParent.replace(/\/$/, '')}/`); } function formatBytes(bytes) { const value = Number(bytes || 0); if (value < 1024) return `${value} B`; if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`; if (value < 1024 * 1024 * 1024) return `${(value / 1024 / 1024).toFixed(1)} MB`; return `${(value / 1024 / 1024 / 1024).toFixed(1)} GB`; } // Outside the user shares (system root) a size scan can wake every disk, so it only runs on request. function isSystemRootPath(path) { return normalizePath(rootForPath(path)?.path || '') === '/'; } function directorySizeLabel(entry) { const result = state.sizeResults.get(entry.path); if (!result) { return state.sizeJobs.has(entry.path) ? 'Berechne...' : 'Noch nicht berechnet'; } const files = Number(result.files || 0); const directories = Math.max(0, Number(result.directories || 0) - 1); return `${formatBytes(result.size)} · ${files} Dateien · ${directories} Ordner`; } function formatPrincipal(name, id) { if (name == null && id == null) return '-'; if (name == null || String(name) === String(id)) return String(id); if (id == null) return String(name); return `${name} (${id})`; } function iconSvg(name) { const paths = uiIcons[name] || uiIcons.close; return ``; } function escapeHtml(value) { return String(value ?? '').replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]); } function escapeAttr(value) { return escapeHtml(value); } function cssEscape(value) { if (window.CSS?.escape) { return window.CSS.escape(String(value)); } return String(value).replace(/["\\]/g, '\\$&'); } function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); } function apiUrl(path) { return `${API_BASE.replace(/\/$/, '')}/${path.replace(/^\//, '')}`; } function appendCsrf(body) { const token = getCsrfToken(); if (!token) { recordDebug('csrf.missing', {}); return; } body.append('csrf_token', token); recordDebug('csrf.attached', { length: token.length }); } function getCsrfToken() { return window.csrf_token || document.querySelector('input[name="csrf_token"]')?.value || document.querySelector('meta[name="csrf_token"]')?.content || document.querySelector('meta[name="csrf-token"]')?.content || ''; } function recordDebug(label, data = {}) { if (!state.config?.debug) { return null; } const item = { id: state.nextDebugId++, time: new Date().toLocaleTimeString(), label, data }; state.debug.push(item); if (state.debug.length > 80) { state.debug.splice(0, state.debug.length - 80); } updateTransferPanel(); return item; } function updateTransferPanel() { renderTransferPanel(); } function serializeError(error) { if (!error) return null; if (error instanceof Error || typeof error === 'object') { return { name: error.name, message: error.message || String(error), stack: error.stack }; } return { message: String(error) }; } // --------------------------------------------------------------------------- // Explorer features: history, filter/search, clipboard, keyboard, favorites, // archives, storage info, checksums and window tiling. // --------------------------------------------------------------------------- const ARCHIVE_PATTERN = /\.(zip|tar|tar\.gz|tgz|tar\.bz2|tbz2|tar\.xz|txz)$/i; const THUMBNAIL_PATTERN = /\.(jpe?g|png|gif|webp)$/i; function currentItems(win) { if (!win) return []; return win.data.search ? (win.data.search.results || []) : (win.data.entries || []); } function visibleEntries(win) { if (!win) return []; const filter = String(win.data.filter || '').trim().toLocaleLowerCase(); const items = currentItems(win).filter((entry) => win.data.search || !filter || String(entry.name || '').toLocaleLowerCase().includes(filter)); return sortEntries(items, win.data.sort || { key: 'name', dir: 1 }); } function breadcrumbMarkup(path) { const root = rootForPath(path); if (!root) { return `${escapeHtml(path || '')}`; } const crumbs = [{ label: root.label || root.path, path: normalizePath(root.path) }]; const relative = normalizePath(path).slice(normalizePath(root.path).length).split('/').filter(Boolean); for (const part of relative) { crumbs.push({ label: part, path: joinPath(crumbs.at(-1).path, part) }); } return crumbs.map((crumb, index) => { const last = index === crumbs.length - 1; return `${index ? `${iconSvg('chevronRight')}` : ''}`; }).join(''); } function statusbarMarkup(win) { const data = win.data; const all = currentItems(win); const visible = visibleEntries(win); const selected = selectedEntries(win); const parts = []; if (data.search) { parts.push(`${all.length} Treffer`); } else { parts.push(visible.length === all.length ? `${all.length} Elemente` : `${visible.length} von ${all.length} Elementen`); } if (selected.length) { const bytes = selected.filter((item) => item.type === 'file').reduce((sum, item) => sum + Number(item.size || 0), 0); parts.push(`${selected.length} ausgewählt${bytes ? ` (${formatBytes(bytes)})` : ''}`); } if (state.clipboard) { parts.push(`${state.clipboard.items.length} in Zwischenablage (${state.clipboard.mode === 'cut' ? 'Ausschneiden' : 'Kopieren'})`); } const storage = data.storage; const free = storage && storage.free != null && storage.total ? `${formatBytes(storage.free)} frei von ${formatBytes(storage.total)}` : ''; const where = storage?.locations?.length ? `Liegt auf: ${storage.locations.map((item) => item.name).join(', ')}` : ''; return ` ${escapeHtml(parts.join(' · '))} ${where ? `${iconSvg('disk')} ${escapeHtml(where)}` : ''}${free ? `${escapeHtml(free)}` : ''} `; } function updateStatusbar(win) { const bar = workspace.querySelector(`.window[data-window-id="${win.id}"] .statusbar`); if (bar) bar.innerHTML = statusbarMarkup(win); } async function loadExplorerStorage(win) { const path = win.data.path; try { const result = await api(apiUrl(`storage.php?path=${encodeURIComponent(path)}`)); if (win.data.path !== path) return; win.data.storage = result; state.storageInfo.set(path, result); updateStatusbar(win); } catch (error) { recordDebug('storage.error', { path, error: serializeError(error) }); } } function ensureStorageInfo(path) { if (state.storageInfo.has(path)) return; state.storageInfo.set(path, null); api(apiUrl(`storage.php?path=${encodeURIComponent(path)}`)) .then((result) => { state.storageInfo.set(path, result); updatePropertiesWindows(); }) .catch(() => state.storageInfo.set(path, { locations: [], free: null, total: null, failed: true })); } function storageLocationLabel(path) { const info = state.storageInfo.get(path); if (!info) return 'Wird ermittelt…'; if (!info.locations?.length) return info.failed ? 'Unbekannt' : '–'; return info.locations.map((item) => item.name).join(', '); } function storageFreeLabel(path) { const info = state.storageInfo.get(path); if (!info) return 'Wird ermittelt…'; if (info.free == null || !info.total) return '–'; const perDevice = (info.locations || []).filter((item) => item.free != null && item.total) .map((item) => `${item.name}: ${formatBytes(item.free)}`); return `${formatBytes(info.free)} von ${formatBytes(info.total)}${perDevice.length > 1 ? ` (${perDevice.join(', ')})` : ''}`; } // --- history ----------------------------------------------------------------------- function pushHistory(win, path) { const data = win.data; data.history = data.history || []; if (normalizePath(data.history[data.historyIndex]) === normalizePath(path)) return; data.history = data.history.slice(0, data.historyIndex + 1); data.history.push(path); if (data.history.length > 100) data.history.shift(); data.historyIndex = data.history.length - 1; } function canGoHistory(win, delta) { const index = (win.data.historyIndex ?? -1) + delta; return index >= 0 && index < (win.data.history || []).length; } function goHistory(win, delta) { if (!canGoHistory(win, delta)) return; const previous = win.data.path; win.data.historyIndex += delta; loadExplorer(win, win.data.history[win.data.historyIndex], { fromHistory: true, select: delta < 0 && isPathInside(previous, win.data.history[win.data.historyIndex]) ? childOnPath(win.data.history[win.data.historyIndex], previous) : null }); } function goUp(win) { const root = rootForPath(win.data.path); if (!root || normalizePath(root.path) === normalizePath(win.data.path)) return; const current = win.data.path; loadExplorer(win, parentPath(current), { select: current }); } function childOnPath(parent, descendant) { const rest = normalizePath(descendant).slice(normalizePath(parent).length).split('/').filter(Boolean); return rest.length ? joinPath(parent, rest[0]) : null; } // --- filter & recursive search -------------------------------------------------------- function searchBannerMarkup(search) { const running = search.status === 'running'; const count = (search.results || []).length; const info = running ? `Suche läuft… ${count} Treffer, ${search.scanned || 0} Einträge geprüft` : `${count} Treffer${search.truncated ? ' (gekürzt, bitte Suche verfeinern)' : ''}${search.status === 'cancelled' ? ' · abgebrochen' : ''}${search.status === 'failed' ? ` · Fehler: ${search.error || ''}` : ''}`; return `
${iconSvg('search')} Suche nach „${escapeHtml(search.query)}“ in ${escapeHtml(search.root)} — ${escapeHtml(info)} ${running ? '' : ''}
`; } async function startSearch(win, query) { if (!query) { closeSearch(win); render(); return; } closeSearch(win); win.data.search = { query, root: win.data.path, status: 'running', results: [], scanned: 0, jobId: null }; win.data.selectedPaths = []; win.data.selectedPath = null; win.data.focusFilter = true; render(); try { const job = await createJob('search', win.data.path, null, [], { query }, { silent: true }); if (win.data.search && win.data.search.query === query) { win.data.search.jobId = job.id; updateSearchFromJob(job); } } catch (error) { if (win.data.search) { win.data.search.status = 'failed'; win.data.search.error = error.message; } render(); } } function closeSearch(win) { const search = win.data.search; if (!search) return; if (search.jobId && search.status === 'running') { cancelJob(search.jobId); } win.data.search = null; win.data.selectedPaths = []; win.data.selectedPath = null; } function updateSearchFromJob(job) { for (const win of state.windows.filter((item) => item.kind === 'explorer' && item.data.search?.jobId === job.id)) { const search = win.data.search; const before = (search.results || []).length; search.results = job.result?.results || search.results || []; search.scanned = job.result?.scanned || search.scanned; search.truncated = Boolean(job.result?.truncated); search.status = isJobActive(job) ? 'running' : job.status; search.error = job.error; const typing = document.activeElement?.classList?.contains('filter-input'); if (search.results.length !== before || !isJobActive(job)) { win.data.focusFilter = typing; render(); } else { const banner = workspace.querySelector(`.window[data-window-id="${win.id}"] .search-banner span`); if (banner) banner.innerHTML = searchBannerMarkup(search).match(/([\s\S]*?)<\/span>/)[1]; } } } // --- favorites ------------------------------------------------------------------------ function isFavorite(path) { return (state.config?.favorites || []).some((item) => normalizePath(item) === normalizePath(path)); } async function toggleFavorite(path) { const favorites = state.config?.favorites || []; const next = isFavorite(path) ? favorites.filter((item) => normalizePath(item) !== normalizePath(path)) : [...favorites, path]; await saveFavorites(next); } // Renamed, moved or deleted favorite folders follow the change instead of going stale. function updateFavoritesAfterJob(job) { const favorites = state.config?.favorites || []; const source = normalizePath(job.source); let changed = false; const next = []; for (const favorite of favorites) { const path = normalizePath(favorite); if (path !== source && !isPathInside(path, source)) { next.push(favorite); continue; } changed = true; if (job.type === 'move' && job.destination) { next.push(normalizePath(job.destination) + path.slice(source.length)); } } if (changed) saveFavorites(next); } async function saveFavorites(next) { const body = new URLSearchParams(); body.set('favorites', JSON.stringify(next)); appendCsrf(body); try { state.config = await api(apiUrl('config.php'), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body }); render(); } catch (error) { showError(error); } } // --- new folder ------------------------------------------------------------------------- function isValidName(name) { return Boolean(name) && name !== '.' && name !== '..' && !name.includes('/') && name.length <= 255; } function freeName(win, base) { const names = new Set((win.data.entries || []).map((entry) => entry.name)); if (!names.has(base)) return base; for (let i = 2; i < 1000; i += 1) { if (!names.has(`${base} (${i})`)) return `${base} (${i})`; } return base; } async function createFolder(win, parent = win.data.path) { if (isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } const name = (await showPromptDialog('Neuer Ordner', 'Name des Ordners', freeName(win, 'Neuer Ordner')))?.trim(); if (!name) return; if (!isValidName(name)) { showError(new Error('Ungültiger Name. Ein Name darf keinen Schrägstrich enthalten und nicht "." oder ".." sein.')); return; } const body = new URLSearchParams(); body.set('path', parent); body.set('name', name); appendCsrf(body); try { const result = await api(apiUrl('mkdir.php'), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body }); await loadExplorer(win, win.data.path, { select: normalizePath(parent) === normalizePath(win.data.path) ? result.path : null }); for (const other of state.windows.filter((item) => item.kind === 'explorer' && item.id !== win.id && normalizePath(item.data.path) === normalizePath(parent))) { loadExplorer(other, other.data.path); } } catch (error) { showError(isConflictError(error) ? new Error(`"${name}" existiert hier bereits.`) : error); } } // --- thumbnails ------------------------------------------------------------------------------ function thumbnailMarkup(entry) { if (entry.type !== 'file' || state.config?.thumbnails === false || state.config?.thumbnailSupport === false) return ''; if (!THUMBNAIL_PATTERN.test(entry.name || '')) return ''; const version = encodeURIComponent(`${entry.modifiedAt || ''}-${entry.size || 0}`); return ` ${fileTypeIcon(entry, true)} `; } // --- clipboard, transfers, conflicts ---------------------------------------------------------- function isCut(path) { return state.clipboard?.mode === 'cut' && state.clipboard.items.some((item) => item.path === path); } function setClipboard(win, mode, entry = null) { const items = entry && !selectedPathSet(win).has(entry.path) ? [entry] : selectedEntries(win); if (!items.length) return; if (mode === 'cut' && isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } state.clipboard = { mode, items: items.map(({ path, name, type }) => ({ path, name, type })) }; render(); } async function pasteClipboard(win, targetDir = win.data.path) { const clipboard = state.clipboard; if (!clipboard?.items.length) return; if (isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } if (clipboard.mode === 'cut') { state.clipboard = null; } const sourceWindows = state.windows.filter((item) => item.kind === 'explorer' && clipboard.items.some((entry) => normalizePath(dirname(entry.path)) === normalizePath(item.data.path))).map((item) => item.id); await runTransfers(clipboard.mode === 'cut' ? 'move' : 'copy', clipboard.items, targetDir, [win.id, ...sourceWindows, ...explorerIdsShowing(targetDir)]); } function explorerIdsShowing(path) { return state.windows.filter((item) => item.kind === 'explorer' && normalizePath(item.data.path) === normalizePath(path)).map((item) => item.id); } function isConflictError(error) { return /already exists/i.test(error?.message || ''); } // Starts one job per item. Copies into the same folder get a "(2)" name automatically, // otherwise a name clash asks: replace, keep both or skip (optionally for all remaining). async function runTransfers(type, items, targetDir, windowIds = []) { if (isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } let decisionForAll = null; for (const [index, item] of items.entries()) { const destination = joinPath(targetDir, item.name); const sameFolder = normalizePath(dirname(item.path)) === normalizePath(targetDir); if (type === 'move' && sameFolder) continue; if (item.type === 'directory' && (normalizePath(targetDir) === normalizePath(item.path) || isPathInside(targetDir, item.path))) { showError(new Error(`"${item.name}" kann nicht in sich selbst ${type === 'copy' ? 'kopiert' : 'verschoben'} werden.`)); continue; } let conflict = type === 'copy' && sameFolder ? 'rename' : 'fail'; for (let attempt = 0; attempt < 2; attempt += 1) { try { await createJob(type, item.path, destination, windowIds, conflict === 'fail' ? {} : { conflict }); break; } catch (error) { if (!isConflictError(error) || attempt > 0) { showError(error); break; } let decision = decisionForAll; if (!decision) { const answer = await showUiDialog({ type: 'choice', title: 'Name existiert bereits', message: `Im Zielordner gibt es bereits "${item.name}".`, rows: [['Quelle', item.path], ['Ziel', destination], ...(items.length > 1 ? [['Element', `${index + 1} von ${items.length}`]] : [])], detail: 'Ersetzen überschreibt das vorhandene Element endgültig.', choices: [ { value: 'skip', label: 'Überspringen' }, { value: 'overwrite', label: 'Ersetzen', danger: true }, { value: 'rename', label: 'Beide behalten', primary: true } ], applyAllLabel: items.length - index > 1 ? 'Für alle weiteren Konflikte übernehmen' : '', cancelLabel: 'Abbrechen' }); if (answer.value === 'cancel') return; decision = answer.value; if (answer.applyAll) decisionForAll = decision; } if (decision === 'skip') break; conflict = decision; } } } } // --- keyboard --------------------------------------------------------------------------------- function focusedExplorer() { return state.windows.find((item) => item.id === state.focusedId && item.kind === 'explorer') || null; } function activateEntry(win, entry) { if (!entry) return; if (entry.type === 'directory') { loadExplorer(win, entry.path); } else if (win.data.search) { loadExplorer(win, dirname(entry.path), { select: entry.path }); } else if (isPreviewable(entry)) { openPreview(entry, win.id); } } function handleExplorerKeydown(event) { if (event.defaultPrevented) return; if (state.uiDialog || state.permissionsDialog || state.uploadConflictDialog || state.contextMenu) return; const win = focusedExplorer(); if (!win) return; const typing = isTypingTarget(document.activeElement); const mod = event.ctrlKey || event.metaKey; const key = event.key; const lower = key.length === 1 ? key.toLowerCase() : key; const consume = () => { event.preventDefault(); event.stopPropagation(); }; if (mod && lower === 'f') { consume(); workspace.querySelector(`.window[data-window-id="${win.id}"] .filter-input`)?.focus(); return; } if (typing) return; const entries = visibleEntries(win); const selected = selectedEntries(win); if (mod && event.shiftKey && lower === 'n') { consume(); createFolder(win); } else if (mod && lower === 'a') { consume(); win.data.selectedPaths = entries.map((entry) => entry.path); win.data.selectedPath = entries[0]?.path || null; win.data.selectionAnchorPath = win.data.selectedPath; updateSelectedRows(); } else if (mod && (lower === 'c' || lower === 'x')) { if (!selected.length) return; consume(); setClipboard(win, lower === 'x' ? 'cut' : 'copy'); } else if (mod && lower === 'v') { if (!state.clipboard) return; consume(); pasteClipboard(win).catch(showError); } else if (event.altKey && key === 'ArrowLeft') { consume(); goHistory(win, -1); } else if (event.altKey && key === 'ArrowRight') { consume(); goHistory(win, 1); } else if ((event.altKey && key === 'ArrowUp') || (key === 'Backspace' && !mod)) { consume(); goUp(win); } else if (key === 'Delete' || (mod && key === 'Backspace')) { if (!selected.length) return; consume(); deleteEntries(win).catch(showError); } else if (key === 'F2') { if (selected.length !== 1) return; consume(); renameEntry(win, selected[0]).catch(showError); } else if (key === 'Enter') { if (selected.length !== 1) return; consume(); activateEntry(win, selected[0]); } else if (key === 'Escape') { if (win.data.search) { consume(); closeSearch(win); render(); } else if (selected.length) { consume(); win.data.selectedPaths = []; win.data.selectedPath = null; updateSelectedRows(); } else if (state.clipboard) { consume(); state.clipboard = null; render(); } } else if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown'].includes(key) && !event.altKey) { if (!entries.length) return; consume(); moveSelection(win, entries, key, event.shiftKey); } else { handleTypeAheadKey(event); } } function gridColumns(win) { const rows = [...workspace.querySelectorAll(`.window[data-window-id="${win.id}"] .icon-grid .file-row`)]; if (rows.length < 2) return 1; const top = rows[0].offsetTop; const count = rows.findIndex((row) => row.offsetTop !== top); return count === -1 ? rows.length : count; } function moveSelection(win, entries, key, extend) { const icons = (win.data.view || 'list') === 'icons' && !win.data.search; const columns = icons ? gridColumns(win) : 1; const page = icons ? columns * 4 : 15; const current = entries.findIndex((entry) => entry.path === win.data.selectedPath); let next = current; if (current === -1) { next = key === 'End' ? entries.length - 1 : 0; } else if (key === 'ArrowDown') { next = current + columns; } else if (key === 'ArrowUp') { next = current - columns; } else if (key === 'ArrowRight') { next = icons ? current + 1 : current; } else if (key === 'ArrowLeft') { next = icons ? current - 1 : current; } else if (key === 'Home') { next = 0; } else if (key === 'End') { next = entries.length - 1; } else if (key === 'PageDown') { next = current + page; } else if (key === 'PageUp') { next = current - page; } next = clamp(next, 0, entries.length - 1); const entry = entries[next]; applyExplorerSelection(win, entry, extend ? { shiftKey: true } : null); if (!extend) win.data.selectionAnchorPath = entry.path; state.selectedEntry = entry; updateSelectedRows(); updatePropertiesWindows(); scrollEntryIntoView(win, entry.path); } function handleClipboardPaste(event) { if (isTypingTarget(document.activeElement) || state.uiDialog) return; const win = focusedExplorer(); const files = [...(event.clipboardData?.files || [])]; if (!win || !files.length || win.data.search) return; event.preventDefault(); if (isReadOnly()) { showError(new Error('Read-only mode ist aktiv.')); return; } uploadFileList(win, files, win.data.path).catch(showError); } // --- window tiling ------------------------------------------------------------------------------ function tileExplorers() { let explorers = state.windows.filter((item) => item.kind === 'explorer'); if (explorers.length === 0) { openExplorer(); explorers = state.windows.filter((item) => item.kind === 'explorer'); } if (explorers.length === 1) { openExplorer(explorers[0].data.path); explorers = state.windows.filter((item) => item.kind === 'explorer'); } const gap = 8; const width = Math.floor((workspace.clientWidth - gap * (explorers.length + 1)) / explorers.length); const height = workspace.clientHeight - gap * 2; explorers.forEach((win, index) => { win.maximized = false; win.x = gap + index * (width + gap); win.y = gap; win.width = Math.max(320, width); win.height = Math.max(240, height); win.data.treeVisible = width > 700 ? win.data.treeVisible : false; }); render(); } function openInNewExplorer(path) { openExplorer(path); } // --- jobs: labels, progress, cancel, results ------------------------------------------------------ function isJobActive(job) { return ['queued', 'running', 'cancel_requested'].includes(job?.status); } function jobTypeLabel(type) { return ({ move: 'Verschieben', copy: 'Kopieren', delete: 'Löschen', size: 'Größe', permissions: 'Rechte ändern', fixperms: 'Unraid-Rechte reparieren', search: 'Suche', checksum: 'Prüfsumme', compare: 'Vergleich', extract: 'Entpacken', compress: 'Komprimieren' })[type] || type; } function jobStatusLabel(status) { return ({ queued: 'Wartet', running: 'Läuft', cancel_requested: 'Wird abgebrochen', completed: 'Fertig', failed: 'Fehler', cancelled: 'Abgebrochen' })[status] || status; } function recordJobSample(job) { if (!job?.bytesTotal) return; const now = Date.now(); const sample = state.jobSamples.get(job.id); if (sample && now > sample.at) { const rate = (Number(job.bytesDone || 0) - sample.bytes) / ((now - sample.at) / 1000); sample.rate = sample.rate == null ? rate : sample.rate * 0.6 + rate * 0.4; } state.jobSamples.set(job.id, { at: now, bytes: Number(job.bytesDone || 0), rate: sample?.rate ?? null }); } function formatDuration(seconds) { if (!Number.isFinite(seconds) || seconds < 0) return ''; if (seconds < 60) return `${Math.ceil(seconds)} s`; if (seconds < 3600) return `${Math.floor(seconds / 60)} min ${Math.ceil(seconds % 60)} s`; return `${Math.floor(seconds / 3600)} h ${Math.floor((seconds % 3600) / 60)} min`; } function renderJobCard(job) { const active = isJobActive(job); const name = basename(job.source || '') || job.source || ''; const target = job.destination ? ` → ${basename(dirname(job.destination)) || '/'}` : ''; const details = [jobStatusLabel(job.status)]; if (job.bytesTotal) { details.push(`${formatBytes(job.bytesDone)} / ${formatBytes(job.bytesTotal)}`); const rate = state.jobSamples.get(job.id)?.rate; if (active && rate > 0) { details.push(`${formatBytes(rate)}/s`); details.push(`noch ${formatDuration((job.bytesTotal - job.bytesDone) / rate)}`); } } if (job.message && !['Fertig', 'Queued'].includes(job.message) && job.status !== 'completed') details.push(job.message); const hasResult = job.status === 'completed' && ['checksum', 'compare'].includes(job.type); return `
${escapeHtml(jobTypeLabel(job.type))}: ${escapeHtml(name)}${escapeHtml(target)} ${active ? `` : ''} ${hasResult ? `` : ''}
${escapeHtml(details.join(' · '))}
`; } async function cancelJob(id) { if (!id) return; const job = state.jobs.get(id); if (job && !isJobActive(job)) return; const body = new URLSearchParams(); body.set('id', id); appendCsrf(body); try { const result = await api(apiUrl('job.php?action=cancel'), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body }); if (isJobActive(result)) { state.jobs.set(id, { ...(state.jobs.get(id) || result), status: 'cancel_requested' }); } updateTransferPanel(); } catch (error) { showError(error); } } function showJobResult(job) { if (!job?.result) return; if (job.type === 'checksum') { showUiDialog({ type: 'message', title: 'Prüfsumme', message: basename(job.source), rows: [['Größe', formatBytes(job.result.size)], ['MD5', job.result.md5], ['SHA-256', job.result.sha256]], code: `${job.result.md5} ${basename(job.source)}\n${job.result.sha256} ${basename(job.source)}`, confirmLabel: 'Schließen' }); } else if (job.type === 'compare') { const result = job.result; const message = result.identical ? 'Die Dateien sind identisch.' : result.sizeA !== result.sizeB ? 'Die Dateien sind unterschiedlich groß.' : `Die Dateien unterscheiden sich ab Byte ${Number(result.firstDifference).toLocaleString()}.`; showUiDialog({ type: 'message', title: 'Dateivergleich', message, rows: [[basename(job.source), formatBytes(result.sizeA)], [basename(job.target), formatBytes(result.sizeB)]], confirmLabel: 'Schließen' }); } } // --- archives, checksums, permissions ------------------------------------------------------------ function isArchive(entry) { return entry?.type === 'file' && ARCHIVE_PATTERN.test(entry.name || ''); } function archiveStem(name) { return String(name).replace(ARCHIVE_PATTERN, '') || 'Archiv'; } async function extractArchive(win, entry, askTarget = false) { let parent = dirname(entry.path); if (askTarget) { const answer = await showPromptDialog('Entpacken nach', 'Zielordner', parent); if (!answer) return; parent = answer.replace(/\/$/, '') || '/'; } await createJob('extract', entry.path, joinPath(parent, archiveStem(entry.name)), [win.id, ...explorerIdsShowing(parent)]); } async function compressEntries(win, entry) { const items = entry && !selectedPathSet(win).has(entry.path) ? [entry] : selectedEntries(win); if (!items.length) return; const parent = dirname(items[0].path); const suggestion = items.length === 1 ? `${items[0].type === 'directory' ? items[0].name : archiveStem(items[0].name.replace(/\.[^.]+$/, '')) || items[0].name}.zip` : 'Archiv.zip'; let name = (await showPromptDialog('Als ZIP komprimieren', 'Name des Archivs', suggestion))?.trim(); if (!name) return; if (!/\.zip$/i.test(name)) name += '.zip'; if (!isValidName(name)) { showError(new Error('Ungültiger Archivname.')); return; } await createJob('compress', null, joinPath(parent, name), [win.id, ...explorerIdsShowing(parent)], { sources: JSON.stringify(items.map((item) => item.path)) }); } async function checksumEntry(entry) { await createJob('checksum', entry.path, null, [], {}); } async function compareEntries(win) { const files = selectedEntries(win).filter((item) => item.type === 'file'); if (files.length !== 2) { showError(new Error('Bitte genau zwei Dateien auswählen.')); return; } await createJob('compare', files[0].path, null, [], { target: files[1].path }); } async function fixPermissions(win, entry) { const items = selectedPathSet(win).has(entry.path) ? selectedEntries(win) : [entry]; const confirmed = await showUiDialog({ type: 'confirm', title: 'Unraid-Rechte reparieren', message: items.length === 1 ? `Rechte für "${items[0].name}" zurücksetzen?` : `Rechte für ${items.length} Elemente zurücksetzen?`, detail: 'Wie das Unraid-Werkzeug "New Permissions": Besitzer nobody:users, Ordner 777, Dateien 666 – für Ordner samt Inhalt.', items: items.map((item) => item.name), confirmLabel: 'Rechte reparieren' }); if (!confirmed) return; for (const item of items) { await createJob('fixperms', item.path, null, [win.id]); } } // --- context menu ---------------------------------------------------------------------------------- function contextMenuActions(win, entry) { const actions = []; const readOnly = isReadOnly(); const selected = entry && selectedPathSet(win).has(entry.path) ? selectedEntries(win) : (entry ? [entry] : []); const multiple = selected.length > 1; if (entry) { if (!multiple) { if (entry.type === 'directory') { actions.push({ label: 'Öffnen', icon: 'folder', hint: 'Enter', action: () => loadExplorer(win, entry.path) }); actions.push({ label: 'In neuem Explorer öffnen', icon: 'columns', action: () => openInNewExplorer(entry.path) }); } else if (isPreviewable(entry)) { actions.push({ label: 'Vorschau', icon: 'preview', hint: 'Enter', action: () => openPreview(entry, win.id) }); } else if (entry.type === 'file') { actions.push({ label: 'Als Text öffnen', icon: 'file', action: () => openPreview(entry, win.id, { force: true }) }); } if (win.data.search) { actions.push({ label: 'Speicherort öffnen', icon: 'folder', action: () => loadExplorer(win, dirname(entry.path), { select: entry.path }) }); } actions.push({ label: 'Eigenschaften', icon: 'info', action: () => showPropertiesForEntry(win, entry) }); } actions.push({ label: 'Herunterladen', icon: 'download', action: () => downloadEntries(win, entry) }); actions.push({ label: 'Kopieren', icon: 'copy', hint: 'Strg+C', separator: true, action: () => setClipboard(win, 'copy', entry) }); if (!readOnly) { actions.push({ label: 'Ausschneiden', icon: 'scissors', hint: 'Strg+X', action: () => setClipboard(win, 'cut', entry) }); if (state.clipboard && entry.type === 'directory' && !multiple) { actions.push({ label: 'In diesen Ordner einfügen', icon: 'paste', action: () => pasteClipboard(win, entry.path) }); } if (!multiple) { actions.push({ label: 'Umbenennen', icon: 'edit', hint: 'F2', action: () => renameEntry(win, entry) }); } actions.push({ label: 'Kopieren nach…', icon: 'copy', action: () => promptTransfer(win, entry, 'copy') }); actions.push({ label: 'Verschieben nach…', icon: 'move', action: () => promptTransfer(win, entry, 'move') }); if (state.config?.archiveSupport !== false) { actions.push({ label: 'Als ZIP komprimieren…', icon: 'archive', separator: true, action: () => compressEntries(win, entry) }); } if (!multiple && isArchive(entry)) { actions.push({ label: 'Hier entpacken', icon: 'archive', action: () => extractArchive(win, entry) }); actions.push({ label: 'Entpacken nach…', icon: 'archive', action: () => extractArchive(win, entry, true) }); } } if (!multiple && entry.type === 'file') { actions.push({ label: 'Prüfsumme berechnen', icon: 'hash', separator: true, action: () => checksumEntry(entry) }); } if (selected.length === 2 && selected.every((item) => item.type === 'file')) { actions.push({ label: 'Dateien vergleichen', icon: 'compare', separator: multiple, action: () => compareEntries(win) }); } if (!multiple && entry.type === 'directory') { actions.push({ label: isFavorite(entry.path) ? 'Aus Favoriten entfernen' : 'Zu Favoriten hinzufügen', icon: 'star', action: () => toggleFavorite(entry.path) }); } if (!readOnly) { actions.push({ label: 'Berechtigungen…', icon: 'shield', separator: true, action: () => openPermissionsDialog(win, entry) }); actions.push({ label: 'Unraid-Rechte reparieren', icon: 'wrench', action: () => fixPermissions(win, entry) }); actions.push({ label: multiple ? `${selected.length} Elemente löschen` : 'Löschen', icon: 'delete', hint: 'Entf', danger: true, separator: true, action: () => deleteEntries(win, entry) }); } } else { if (!readOnly && !win.data.search) { actions.push({ label: 'Neuer Ordner', icon: 'folderPlus', hint: 'Strg+Shift+N', action: () => createFolder(win) }); if (state.clipboard) { actions.push({ label: `Einfügen (${state.clipboard.items.length})`, icon: 'paste', hint: 'Strg+V', action: () => pasteClipboard(win) }); } } actions.push({ label: isFavorite(win.data.path) ? 'Ordner aus Favoriten entfernen' : 'Ordner zu Favoriten hinzufügen', icon: 'star', separator: !readOnly, action: () => toggleFavorite(win.data.path) }); actions.push({ label: 'Aktuellen Ordner herunterladen', icon: 'download', action: () => downloadEntries(win, null) }); actions.push({ label: 'Neu laden', icon: 'refresh', action: () => loadExplorer(win, win.data.path) }); } return actions; } // Unraid normally tells us its theme (data-theme from the .page). If it does not, // look at the page background around the navigator so custom/unknown themes still match. function applyHostTheme() { if (!appShell || appShell.dataset.theme) return; let element = appShell.parentElement; while (element) { const match = getComputedStyle(element).backgroundColor.match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?/); if (match && (match[4] === undefined || Number(match[4]) > 0.5)) { const [r, g, b] = match.slice(1, 4).map(Number); const luminance = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255; appShell.dataset.theme = luminance < 0.5 ? 'dark' : 'light'; return; } element = element.parentElement; } } // --------------------------------------------------------------------------- // Text editor: line numbers, cursor status, indentation, go-to-line, checks. // --------------------------------------------------------------------------- function isCodeView(data) { return !data.loading && !data.error && (data.editing || (data.type === 'text' && typeof data.content === 'string')); } function lineCount(text) { return String(text ?? '').split('\n').length; } function lineNumbers(text) { const count = lineCount(text); let out = ''; for (let i = 1; i <= count; i += 1) out += `${i}\n`; return out; } function editorStatusMarkup(data, position = null) { const text = data.editing ? (data.draft ?? data.content ?? '') : (data.content ?? ''); const parts = []; if (position) parts.push(`Zeile ${position.line}, Spalte ${position.column}`); parts.push(`${lineCount(text)} Zeilen`); parts.push(data.encoding === 'windows-1252' ? 'Windows-1252' : (data.encoding === 'unknown' ? 'Kodierung unbekannt (nur lesen)' : 'UTF-8')); parts.push(data.lineEnding === 'crlf' ? 'CRLF' : 'LF'); const changed = data.editing && (data.draft ?? '') !== (data.content ?? ''); return `${escapeHtml(parts.join(' · '))}${changed ? 'Geändert' : ''}${data.editing ? 'Strg+S speichern · Strg+G Zeile · Tab einrücken' : ''}`; } function editorIndentUnit(data, text) { const name = String(data.entry?.name || '').toLowerCase(); if (name === 'makefile' || name === 'gnumakefile' || /\.(mk|mak|make|tsv|go)$/.test(name)) return '\t'; if (/^\t/m.test(text) && !/\.(ya?ml)$/.test(name)) return '\t'; return /\.(py|pyw)$/.test(name) ? ' ' : ' '; } function cursorPosition(editor) { const before = editor.value.slice(0, editor.selectionStart); const lines = before.split('\n'); return { line: lines.length, column: lines.at(-1).length + 1 }; } // Uses the browser's insertText so Ctrl+Z keeps working after programmatic edits. function replaceEditorRange(editor, start, end, text) { editor.focus(); editor.setSelectionRange(start, end); if (!document.execCommand?.('insertText', false, text)) { editor.setRangeText(text, start, end, 'end'); editor.dispatchEvent(new Event('input')); } } function bindCodeEditor(body, editor, win) { const data = win.data; const gutter = body.querySelector('.line-gutter'); const status = body.querySelector('.editor-status'); let lastCount = lineCount(editor.value); const updateStatus = () => { if (status) status.innerHTML = editorStatusMarkup(data, cursorPosition(editor)); }; editor.addEventListener('input', () => { data.draft = editor.value; const count = lineCount(editor.value); if (count !== lastCount && gutter) { gutter.textContent = lineNumbers(editor.value); lastCount = count; } updateStatus(); }); editor.addEventListener('scroll', () => { if (gutter) gutter.scrollTop = editor.scrollTop; }); for (const type of ['keyup', 'click', 'select']) { editor.addEventListener(type, updateStatus); } editor.addEventListener('keydown', (event) => { const mod = event.ctrlKey || event.metaKey; const key = event.key.toLowerCase(); if (mod && key === 's') { event.preventDefault(); savePreview(win, editor.value); } else if (mod && key === 'g') { event.preventDefault(); showPromptDialog('Gehe zu Zeile', `Zeile (1–${lineCount(editor.value)})`, String(cursorPosition(editor).line)).then((value) => { if (value) goToEditorLine(win, Number.parseInt(value, 10)); }); } else if (event.key === 'Tab' && !mod && !event.altKey) { event.preventDefault(); indentEditorSelection(editor, editorIndentUnit(data, editor.value), event.shiftKey); } else if (event.key === 'Enter' && !mod && !event.altKey && !event.shiftKey) { // Keep the indentation of the current line (handy for YAML and scripts). const start = editor.selectionStart; const lineStart = editor.value.lastIndexOf('\n', start - 1) + 1; const indent = editor.value.slice(lineStart, start).match(/^[\t ]*/)[0]; if (indent) { event.preventDefault(); replaceEditorRange(editor, start, editor.selectionEnd, `\n${indent}`); } } }); requestAnimationFrame(() => { editor.focus(); if (data.pendingLine) { goToEditorLine(win, data.pendingLine); data.pendingLine = null; } updateStatus(); }); } function indentEditorSelection(editor, unit, outdent) { const value = editor.value; const start = editor.selectionStart; const end = editor.selectionEnd; const multiLine = value.slice(start, end).includes('\n'); if (!outdent && !multiLine) { replaceEditorRange(editor, start, end, unit); return; } const blockStart = value.lastIndexOf('\n', start - 1) + 1; const blockEnd = end > start && value[end - 1] === '\n' ? end - 1 : end; const lines = value.slice(blockStart, blockEnd).split('\n'); const changed = lines.map((line) => { if (!outdent) return unit + line; if (line.startsWith('\t')) return line.slice(1); return line.replace(new RegExp(`^ {1,${Math.max(1, unit === '\t' ? 4 : unit.length)}}`), ''); }); const replacement = changed.join('\n'); replaceEditorRange(editor, blockStart, blockEnd, replacement); editor.setSelectionRange(blockStart, blockStart + replacement.length); } function goToEditorLine(win, line) { const editor = workspace.querySelector(`.window[data-window-id="${win.id}"] .preview-editor`); if (!editor || !Number.isFinite(line)) return; const lines = editor.value.split('\n'); const target = clamp(line, 1, lines.length); const offset = lines.slice(0, target - 1).reduce((sum, item) => sum + item.length + 1, 0); editor.focus(); editor.setSelectionRange(offset, offset + lines[target - 1].length); const lineHeight = Number.parseFloat(getComputedStyle(editor).lineHeight) || 17; editor.scrollTop = Math.max(0, (target - 3) * lineHeight); editor.dispatchEvent(new Event('select')); } // Cheap syntax checks before saving: JSON must parse, YAML must not indent with tabs. function validateEditorContent(data, content) { const ext = extensionOf(data.entry?.name || ''); if (['json', 'geojson'].includes(ext) && content.trim()) { try { JSON.parse(content); } catch (error) { const match = /position (\d+)/i.exec(error.message); const line = match ? content.slice(0, Number(match[1])).split('\n').length : null; return { message: 'Die Datei ist kein gültiges JSON.', detail: `${error.message}${line ? ` (Zeile ${line})` : ''}`, line }; } } if (['yaml', 'yml'].includes(ext)) { const index = content.split('\n').findIndex((line) => /^\s*\t/.test(line)); if (index >= 0) { return { message: 'YAML erlaubt keine Tabulatoren zum Einrücken.', detail: `Zeile ${index + 1} ist mit einem Tab eingerückt. Docker Compose & Co. lehnen solche Dateien ab.`, line: index + 1 }; } } return null; }