diff --git a/README.md b/README.md index c58329b..19a77e3 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,10 @@ http://127.0.0.1:8088 - Namenskonflikte beim Kopieren/Verschieben: Ersetzen, Beide behalten oder Überspringen (auch für alle) - Transfers mit Bytes, Geschwindigkeit, Restzeit und Abbrechen - Löschen ohne Papierkorb, wie in Unraid üblich – mit deutlicher Rückfrage -- Vorschaubilder für JPG/PNG/GIF/WebP (on the fly, ohne Cache-Dateien), Vorschau und Texteditor +- Vorschaubilder für JPG/PNG/GIF/WebP (on the fly, ohne Cache-Dateien), Vorschau für Bilder, PDF, Audio, Video +- Texteditor mit Zeilennummern für über 200 Formate (Konfiguration, Skripte, Quellcode, Unraid-Dateien wie `.plg`, + `.cfg`, `go`); Dateien ohne bekannte Endung werden am Inhalt als Text erkannt. Zeilenenden (CRLF/LF) und die + Kodierung (UTF-8 oder Windows-1252) bleiben beim Speichern erhalten; JSON und YAML werden vor dem Speichern geprüft - ZIP erstellen, ZIP/TAR(.gz/.bz2/.xz) entpacken (mit Schutz gegen Pfade außerhalb des Ziels) - Prüfsummen (MD5, SHA-256) und Dateivergleich - Unraid: physischer Ort (disk/cache-Pool) und freier Speicher, „Unraid-Rechte reparieren“ (nobody:users, 777/666) diff --git a/build-plugin.sh b/build-plugin.sh index f5c7094..5833607 100755 --- a/build-plugin.sh +++ b/build-plugin.sh @@ -5,7 +5,7 @@ set -eu export COPYFILE_DISABLE=1 PLUGIN="u-navigator" -VERSION="2026.11.21.r005" +VERSION="2026.11.21.r006" PKG_DIR="packages" WORK_DIR=".plugin-build" PKG_NAME="${PLUGIN}-${VERSION}.tgz" diff --git a/packages/u-navigator-2026.11.21.r006.tgz b/packages/u-navigator-2026.11.21.r006.tgz new file mode 100644 index 0000000..0d059bc Binary files /dev/null and b/packages/u-navigator-2026.11.21.r006.tgz differ diff --git a/plugin-root/usr/local/emhttp/plugins/u-navigator/api/preview.php b/plugin-root/usr/local/emhttp/plugins/u-navigator/api/preview.php index 55f64d7..3083c75 100644 --- a/plugin-root/usr/local/emhttp/plugins/u-navigator/api/preview.php +++ b/plugin-root/usr/local/emhttp/plugins/u-navigator/api/preview.php @@ -12,6 +12,10 @@ if (!is_file($resolved['path'])) { $name = basename($resolved['path']); $extension = strtolower(pathinfo($resolved['path'], PATHINFO_EXTENSION)); $type = unav_preview_type($extension, $name); +// Unknown extension (e.g. Unraid's /boot/config/go): open it as text if the content looks like text. +if ($type === null && unav_looks_like_text($resolved['path'])) { + $type = 'text'; +} if ($type === null) { unav_error(415, 'Preview is not available for this file type'); } @@ -26,11 +30,11 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!array_key_exists('content', $data)) { unav_error(400, 'Missing file content'); } - $content = (string)$data['content']; - if (strlen($content) > UNAV_TEXT_PREVIEW_MAX_BYTES) { + $text = (string)$data['content']; + if (strlen($text) > UNAV_TEXT_PREVIEW_MAX_BYTES) { unav_error(413, 'Die bearbeitete Datei ist größer als 1 MB'); } - if (strpos($content, "\0") !== false) { + if (strpos($text, "\0") !== false) { unav_error(415, 'Binärdaten können nicht im Texteditor gespeichert werden'); } $expectedRevision = trim((string)($data['revision'] ?? '')); @@ -56,6 +60,14 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { fclose($handle); unav_error(409, 'Die Datei wurde außerhalb von U-Navigator geändert. Bitte vor dem Speichern neu laden.'); } + // Keep the file's encoding: Windows-1252 files are written back as Windows-1252. + $encoding = unav_text_encoding($current); + $content = $encoding === 'windows-1252' ? unav_encode_cp1252($text) : $text; + if ($content === null) { + flock($handle, LOCK_UN); + fclose($handle); + unav_error(422, 'Der Text enthält Zeichen, die in der Kodierung der Datei (Windows-1252) nicht möglich sind.'); + } rewind($handle); if (!ftruncate($handle, 0) || !unav_write_all($handle, $content) || !fflush($handle)) { flock($handle, LOCK_UN); @@ -70,7 +82,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { 'size' => strlen($content), 'modifiedAt' => gmdate('c', filemtime($resolved['path']) ?: time()), 'revision' => hash('sha256', $content), - 'content' => $content, + 'content' => $text, + 'encoding' => $encoding ?? 'utf-8', ]); } @@ -118,8 +131,17 @@ if (in_array($type, ['text', 'markdown', 'csv'], true)) { if (strpos($content, "\0") !== false) { unav_error(415, 'Preview is not available for binary files'); } - $payload['content'] = $content; + $encoding = unav_text_encoding($content); $payload['revision'] = hash('sha256', $content); + $payload['encoding'] = $encoding ?? 'unknown'; + if ($encoding === 'windows-1252') { + $content = unav_decode_cp1252($content); + } elseif ($encoding === null) { + // Not valid UTF-8 and no converter available: show it, but never write it back. + $content = unav_lossy_utf8($content); + $payload['editable'] = false; + } + $payload['content'] = $content; } unav_json($payload); @@ -139,14 +161,39 @@ function unav_write_all($handle, string $content): bool { function unav_preview_type(string $extension, string $name): ?string { $base = strtolower($name); - if (in_array($base, ['dockerfile', 'makefile'], true)) { + $textNames = ['dockerfile', 'containerfile', 'makefile', 'gnumakefile', 'vagrantfile', 'gemfile', 'rakefile', 'procfile', + 'jenkinsfile', 'caddyfile', 'brewfile', 'go', 'hosts', 'fstab', 'crontab', 'exports', 'passwd', 'group', 'shells', + 'authorized_keys', 'known_hosts', 'config', 'license', 'licence', 'readme', 'changelog', 'authors', 'copying', + 'notice', 'todo', 'version', 'codeowners']; + if (in_array($base, $textNames, true)) { return 'text'; } - $text = ['txt', 'log', 'rd', 'rst', 'yaml', 'yml', 'json', 'xml', 'ini', 'cfg', 'conf', 'env', 'toml', 'sql', 'nfo', 'srt', 'sub', 'vtt', 'm3u', 'm3u8', 'pls', 'sh', 'bash', 'zsh', 'php', 'js', 'ts', 'tsx', 'jsx', 'css', 'html', 'py', 'go', 'rs', 'java', 'c', 'cpp', 'h', 'hpp', 'bat', 'ps1', 'properties', 'service', 'timer', 'mount', 'rules', 'cron', 'plg', 'page']; + $text = [ + // plain text, logs, docs + 'txt', 'text', 'log', 'out', 'err', 'nfo', 'diz', 'rd', 'rst', 'adoc', 'asciidoc', 'org', 'tex', 'bib', 'rtf', + // configuration + 'cfg', 'conf', 'config', 'cnf', 'cf', 'ini', 'inf', 'env', 'properties', 'prefs', 'toml', 'yaml', 'yml', + 'json', 'jsonc', 'json5', 'ndjson', 'jsonl', 'geojson', 'xml', 'xsd', 'xsl', 'xslt', 'plist', 'hcl', 'tf', 'tfvars', + 'nix', 'rc', 'list', 'lst', 'tmpl', 'tpl', 'j2', 'jinja', 'jinja2', 'twig', 'mustache', 'hbs', 'lock', 'sum', 'mod', + 'editorconfig', 'gitignore', 'gitattributes', 'gitmodules', 'dockerignore', 'npmrc', 'yarnrc', 'nvmrc', 'htaccess', + 'htpasswd', 'bashrc', 'bash_profile', 'profile', 'zshrc', 'vimrc', 'tmux', 'screenrc', 'inputrc', 'wgetrc', 'curlrc', + // Unraid / Linux system files + 'plg', 'page', 'cron', 'crontab', 'service', 'timer', 'socket', 'target', 'mount', 'automount', 'path', 'network', + 'netdev', 'link', 'rules', 'desktop', 'repo', 'sources', 'exports', 'fstab', 'hosts', 'pub', 'pem', 'csr', 'asc', + 'md5', 'sha1', 'sha256', 'sha512', 'sfv', 'cue', 'm3u', 'm3u8', 'pls', 'xspf', 'opml', + 'ics', 'vcf', 'srt', 'sub', 'vtt', 'ass', 'ssa', 'nzb', + // scripts and source code + 'sh', 'bash', 'zsh', 'fish', 'ksh', 'csh', 'awk', 'sed', 'php', 'phtml', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', + 'vue', 'svelte', 'css', 'scss', 'sass', 'less', 'html', 'htm', 'xhtml', 'py', 'pyw', 'rb', 'pl', 'pm', 'lua', 'tcl', + 'go', 'rs', 'java', 'kt', 'kts', 'scala', 'groovy', 'gradle', 'swift', 'c', 'cc', 'cpp', 'cxx', 'h', 'hh', 'hpp', + 'cs', 'vb', 'fs', 'dart', 'r', 'jl', 'ex', 'exs', 'erl', 'hs', 'ml', 'clj', 'lisp', 'el', 'vim', 'sql', 'graphql', + 'gql', 'proto', 'bat', 'cmd', 'ps1', 'psm1', 'psd1', 'vbs', 'ahk', 'cmake', 'mk', 'mak', 'make', 'in', 'am', 'ac', + 'm4', 'spec', 'diff', 'patch', 'dockerfile', 'containerfile', 'compose', + ]; if (in_array($extension, $text, true)) { return 'text'; } - if ($extension === 'md') { + if (in_array($extension, ['md', 'markdown', 'mdown', 'mkd', 'mdx'], true)) { return 'markdown'; } if (in_array($extension, ['csv', 'tsv'], true)) { @@ -191,3 +238,51 @@ function unav_preview_mime(string $extension, string $type): string { ]; return $map[$extension] ?? ($type === 'text' ? 'text/plain; charset=utf-8' : 'application/octet-stream'); } + +// First 8 KB without NUL bytes and mostly printable/UTF-8 → treat as text. +function unav_looks_like_text(string $path): bool { + $size = @filesize($path); + if ($size === false || $size > UNAV_TEXT_PREVIEW_MAX_BYTES) { + return false; + } + if ($size === 0) { + return true; + } + $sample = (string)@file_get_contents($path, false, null, 0, 8192); + if ($sample === '' || str_contains($sample, "\0")) { + return false; + } + if (preg_match('//u', $sample) || preg_match('//u', substr($sample, 0, -3))) { + return true; + } + $control = preg_match_all('/[\x01-\x08\x0E-\x1F\x7F]/', $sample); + return $control / strlen($sample) < 0.02; +} + +function unav_text_encoding(string $bytes): ?string { + if (preg_match('//u', $bytes)) { + return 'utf-8'; + } + return (function_exists('mb_convert_encoding') || function_exists('iconv')) ? 'windows-1252' : null; +} + +function unav_decode_cp1252(string $bytes): string { + if (function_exists('mb_convert_encoding')) { + return mb_convert_encoding($bytes, 'UTF-8', 'Windows-1252'); + } + return (string)iconv('Windows-1252', 'UTF-8//IGNORE', $bytes); +} + +function unav_encode_cp1252(string $text): ?string { + $bytes = function_exists('mb_convert_encoding') + ? mb_convert_encoding($text, 'Windows-1252', 'UTF-8') + : @iconv('UTF-8', 'Windows-1252', $text); + if (!is_string($bytes) || unav_decode_cp1252($bytes) !== $text) { + return null; + } + return $bytes; +} + +function unav_lossy_utf8(string $bytes): string { + return (string)preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '?', $bytes); +} diff --git a/server/public/app.js b/server/public/app.js index 9c969fa..eb142f7 100644 --- a/server/public/app.js +++ b/server/public/app.js @@ -91,8 +91,32 @@ const uiIcons = { tree: '', upload: '' }; -const previewExtensions = new Set(['txt', 'log', 'md', 'rd', 'rst', 'yaml', 'yml', 'json', 'xml', 'csv', 'tsv', 'ini', 'cfg', 'conf', 'env', 'toml', 'sql', 'nfo', 'srt', 'sub', 'vtt', 'm3u', 'm3u8', 'pls', 'sh', 'bash', 'zsh', 'php', 'js', 'ts', 'tsx', 'jsx', 'css', 'html', 'py', 'go', 'rs', 'java', 'c', 'cpp', 'h', 'hpp', 'bat', 'ps1', 'properties', 'service', 'timer', 'mount', 'rules', 'cron', 'plg', 'page', 'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'pdf', 'mp3', 'flac', 'm4a', 'ogg', 'wav', 'mp4', 'mkv', 'webm', 'mov']); -const previewFilenames = new Set(['dockerfile', 'makefile']); +// 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()); @@ -190,8 +214,8 @@ function openProperties(entry = state.selectedEntry) { }); } -function openPreview(entry, sourceWindowId = state.focusedId) { - if (!entry || !isPreviewable(entry)) { +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; } @@ -874,7 +898,10 @@ function renderPreview(body, win) { ${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', () => { @@ -889,23 +916,19 @@ function renderPreview(body, win) { }); const editor = body.querySelector('.preview-editor'); if (editor) { - editor.addEventListener('input', () => { - data.draft = editor.value; - }); - editor.addEventListener('keydown', (event) => { - if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { - event.preventDefault(); - savePreview(win, editor.value); - } - }); - requestAnimationFrame(() => editor.focus()); + bindCodeEditor(body, editor, win); } body.querySelector('[data-action="preview-save"]')?.addEventListener('click', () => savePreview(win, editor?.value ?? data.draft ?? '')); } function renderPreviewContent(data) { if (data.editing) { - return ``; + const value = data.draft ?? data.content ?? ''; + return ` +
+ + +
`; } if (data.type === 'markdown') { return `
${renderMarkdown(data.content || '')}
`; @@ -925,7 +948,11 @@ function renderPreviewContent(data) { if (data.type === 'video') { return `
`; } - return `
${escapeHtml(data.content || '')}
`; + return ` +
+ +
${escapeHtml(data.content || '')}
+
`; } function previewNavigation(data) { @@ -962,6 +989,10 @@ async function loadPreview(win, entry) { 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 { @@ -972,10 +1003,23 @@ async function loadPreview(win, entry) { 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', content); + body.set('content', win.data.lineEnding === 'crlf' ? content.replace(/\r?\n/g, '\r\n') : content); body.set('revision', win.data.revision || ''); appendCsrf(body); try { @@ -984,7 +1028,7 @@ async function savePreview(win, content) { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body }); - win.data.content = result.content; + 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; @@ -3115,7 +3159,8 @@ function extensionOf(name) { function isPreviewable(entry) { if (entry?.type !== 'file') return false; const name = String(entry.name || entry.path || '').toLowerCase(); - return previewFilenames.has(name) || previewExtensions.has(extensionOf(name)); + // 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) { @@ -4060,6 +4105,8 @@ function contextMenuActions(win, entry) { 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 }) }); @@ -4130,3 +4177,178 @@ function applyHostTheme() { 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; +} diff --git a/server/public/styles.css b/server/public/styles.css index 1ec0773..68e2996 100644 --- a/server/public/styles.css +++ b/server/public/styles.css @@ -1806,3 +1806,87 @@ .u-nav .transfer-panel-header .link-button { margin-left: auto; } + +/* --- code editor / text view with line numbers ------------------------------- */ +.u-nav .preview-body.with-status { + grid-template-rows: auto minmax(0, 1fr) auto; +} + +.u-nav .code-view { + background: var(--surface-2); + border: 1px solid var(--line); + border-radius: 7px; + display: grid; + grid-template-columns: auto minmax(0, 1fr); + min-height: 0; + overflow: auto; +} + +.u-nav .code-view.editing { + border-color: var(--accent); + overflow: hidden; +} + +.u-nav .code-view .line-gutter { + background: var(--surface-3); + border-right: 1px solid var(--line); + color: var(--muted); + font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + margin: 0; + min-width: 3.2em; + overflow: hidden; + padding: 10px 8px 10px 6px; + position: sticky; + left: 0; + text-align: right; + user-select: none; + white-space: pre; +} + +.u-nav .code-view .preview-text, +.u-nav .code-view .preview-editor { + background: transparent; + border: 0; + border-radius: 0; + box-shadow: none; + font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + min-height: 0; + padding: 10px; +} + +/* View mode: gutter and text grow with the content; the code-view itself scrolls. */ +.u-nav .code-view:not(.editing) { + align-items: start; +} + +.u-nav .code-view .preview-text { + overflow: visible; +} + +.u-nav .code-view.editing .line-gutter, +.u-nav .code-view.editing .preview-editor { + height: 100%; +} + +.u-nav .code-view .preview-editor { + overflow: auto; + white-space: pre; +} + +.u-nav .editor-status { + align-items: center; + color: var(--muted); + display: flex; + font-size: 12px; + gap: 12px; + min-height: 20px; +} + +.u-nav .editor-status .muted { + margin-left: auto; +} + +.u-nav .editor-dirty { + color: var(--accent); + font-weight: 600; +} diff --git a/tests/php/api_test.php b/tests/php/api_test.php index 70e62e9..f729fa0 100644 --- a/tests/php/api_test.php +++ b/tests/php/api_test.php @@ -179,6 +179,24 @@ check('raw svg is sandboxed', (bool)preg_grep('/^Content-Security-Policy: sandbo $r = call('POST', 'config.php', ['favorites' => json_encode([$share, $outside, $share . '/missing'])]); check('favorites keep only folders inside roots', ($r['json']['favorites'] ?? null) === [$share], json_encode($r['json']['favorites'] ?? null)); +// text editor: types, sniffing, encodings +file_put_contents($share . '/go', "#!/bin/bash\n/usr/local/sbin/emhttp &\n"); +$r = call('GET', 'preview.php?path=' . urlencode($share . '/go')); +check('file without extension opens as editable text', ($r['json']['type'] ?? '') === 'text' && ($r['json']['editable'] ?? false) === true); +file_put_contents($share . '/compose.yaml', "services:\n app:\n image: x\n"); +$r = call('GET', 'preview.php?path=' . urlencode($share . '/compose.yaml')); +check('yaml is editable', ($r['json']['editable'] ?? false) === true); +file_put_contents($share . '/blob.dat', random_bytes(64) . "\0"); +$r = call('GET', 'preview.php?path=' . urlencode($share . '/blob.dat')); +check('binary files are not opened as text', $r['status'] === 415); +file_put_contents($share . '/latin.cfg', "Gr\xfc\xdfe=1\r\n"); +$r = call('GET', 'preview.php?path=' . urlencode($share . '/latin.cfg')); +check('windows-1252 is decoded for the editor', ($r['json']['content'] ?? '') === "Grüße=1\r\n" && ($r['json']['encoding'] ?? '') === 'windows-1252'); +$r = call('POST', 'preview.php?path=' . urlencode($share . '/latin.cfg'), ['content' => "Grüße=2\r\n", 'revision' => $r['json']['revision']]); +check('windows-1252 is written back in its encoding', $r['status'] === 200 && file_get_contents($share . '/latin.cfg') === "Gr\xfc\xdfe=2\r\n"); +$r = call('POST', 'preview.php?path=' . urlencode($share . '/latin.cfg'), ['content' => "€ ok, ✓ nicht\r\n", 'revision' => $r['json']['revision']]); +check('characters outside windows-1252 are refused', $r['status'] === 422 && file_get_contents($share . '/latin.cfg') === "Gr\xfc\xdfe=2\r\n"); + // whole system root (opt-in) $r = call('GET', 'list.php?path=/'); check('system root is hidden by default', $r['status'] === 403); diff --git a/u-navigator.plg b/u-navigator.plg index f5909da..7fd4ea0 100644 --- a/u-navigator.plg +++ b/u-navigator.plg @@ -1,7 +1,7 @@ - + @@ -18,6 +18,8 @@ &description; ### &version; +- Editor: Zeilennummern, Zeile/Spalte, Auto-Einrückung, Tab/Umschalt+Tab, Strg+G, Prüfung von JSON und YAML vor dem Speichern. +- Über 200 Textformate bearbeitbar, Dateien ohne Endung (z. B. /boot/config/go) werden erkannt; Windows-1252 und CRLF bleiben erhalten. - Option „Ganzes System (ab /)“ in den Einstellungen; Systemordner, /boot und Mountpunkte bleiben geschützt. - Folgt dem Unraid-Theme (black/gray dunkel, white/azure hell) statt nur der Systemeinstellung. - Neuer Ordner, Tastaturbedienung, Kopieren/Ausschneiden/Einfügen, Zurück/Vorwärts, anklickbare Pfadleiste. @@ -29,7 +31,7 @@ https://git.casaderoll.de/michael/Unraid-Navigator/raw/branch/main/packages/&package; -c0dd54cb308a2de3542429300705ecde +2caa35c0a8a86448b9546255f9c3c5ca diff --git a/u-navigator.plg.in b/u-navigator.plg.in index 07db4af..165b2b2 100644 --- a/u-navigator.plg.in +++ b/u-navigator.plg.in @@ -18,6 +18,8 @@ &description; ### &version; +- Editor: Zeilennummern, Zeile/Spalte, Auto-Einrückung, Tab/Umschalt+Tab, Strg+G, Prüfung von JSON und YAML vor dem Speichern. +- Über 200 Textformate bearbeitbar, Dateien ohne Endung (z. B. /boot/config/go) werden erkannt; Windows-1252 und CRLF bleiben erhalten. - Option „Ganzes System (ab /)“ in den Einstellungen; Systemordner, /boot und Mountpunkte bleiben geschützt. - Folgt dem Unraid-Theme (black/gray dunkel, white/azure hell) statt nur der Systemeinstellung. - Neuer Ordner, Tastaturbedienung, Kopieren/Ausschneiden/Einfügen, Zurück/Vorwärts, anklickbare Pfadleiste.