Add safe text editing to preview window

This commit is contained in:
Mikei386
2026-07-14 19:25:09 +02:00
parent af9e7703ea
commit b968a1c16f
6 changed files with 218 additions and 8 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
set -eu set -eu
PLUGIN="u-navigator" PLUGIN="u-navigator"
VERSION="2026.07.14.r016" VERSION="2026.07.14.r017"
PKG_DIR="packages" PKG_DIR="packages"
WORK_DIR=".plugin-build" WORK_DIR=".plugin-build"
PKG_NAME="${PLUGIN}-${VERSION}.tgz" PKG_NAME="${PLUGIN}-${VERSION}.tgz"
Binary file not shown.
@@ -15,6 +15,68 @@ if ($type === null) {
unav_error(415, 'Preview is not available for this file type'); unav_error(415, 'Preview is not available for this file type');
} }
$editable = in_array($type, ['text', 'markdown', 'csv'], true);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
unav_assert_writable();
if (!$editable) {
unav_error(415, 'Dieser Dateityp kann nicht bearbeitet werden');
}
$data = unav_request_data();
if (!array_key_exists('content', $data)) {
unav_error(400, 'Missing file content');
}
$content = (string)$data['content'];
if (strlen($content) > UNAV_TEXT_PREVIEW_MAX_BYTES) {
unav_error(413, 'Die bearbeitete Datei ist größer als 1 MB');
}
if (strpos($content, "\0") !== false) {
unav_error(415, 'Binärdaten können nicht im Texteditor gespeichert werden');
}
$expectedRevision = trim((string)($data['revision'] ?? ''));
if ($expectedRevision === '') {
unav_error(400, 'Missing file revision');
}
$handle = fopen($resolved['path'], 'r+b');
if ($handle === false || !flock($handle, LOCK_EX)) {
if (is_resource($handle)) {
fclose($handle);
}
unav_error(500, 'Could not lock file for editing');
}
rewind($handle);
$current = stream_get_contents($handle);
if ($current === false) {
flock($handle, LOCK_UN);
fclose($handle);
unav_error(500, 'Could not read file before saving');
}
if (!hash_equals($expectedRevision, hash('sha256', $current))) {
flock($handle, LOCK_UN);
fclose($handle);
unav_error(409, 'Die Datei wurde außerhalb von U-Navigator geändert. Bitte vor dem Speichern neu laden.');
}
rewind($handle);
if (!ftruncate($handle, 0) || !unav_write_all($handle, $content) || !fflush($handle)) {
flock($handle, LOCK_UN);
fclose($handle);
unav_error(500, 'Could not save file');
}
flock($handle, LOCK_UN);
fclose($handle);
clearstatcache(true, $resolved['path']);
unav_json([
'path' => $resolved['path'],
'size' => strlen($content),
'modifiedAt' => gmdate('c', filemtime($resolved['path']) ?: time()),
'revision' => hash('sha256', $content),
'content' => $content,
]);
}
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
unav_error(405, 'Method not allowed');
}
$size = filesize($resolved['path']); $size = filesize($resolved['path']);
if ($size === false) { if ($size === false) {
unav_error(500, 'Could not read file size'); unav_error(500, 'Could not read file size');
@@ -35,6 +97,7 @@ $payload = [
'size' => $size, 'size' => $size,
'extension' => $extension, 'extension' => $extension,
'type' => $type, 'type' => $type,
'editable' => $editable,
'mime' => $mime, 'mime' => $mime,
'rawUrl' => 'preview.php?raw=1&path=' . rawurlencode($resolved['path']), 'rawUrl' => 'preview.php?raw=1&path=' . rawurlencode($resolved['path']),
]; ];
@@ -51,10 +114,24 @@ if (in_array($type, ['text', 'markdown', 'csv'], true)) {
unav_error(415, 'Preview is not available for binary files'); unav_error(415, 'Preview is not available for binary files');
} }
$payload['content'] = $content; $payload['content'] = $content;
$payload['revision'] = hash('sha256', $content);
} }
unav_json($payload); unav_json($payload);
function unav_write_all($handle, string $content): bool {
$length = strlen($content);
$offset = 0;
while ($offset < $length) {
$written = fwrite($handle, substr($content, $offset));
if ($written === false || $written === 0) {
return false;
}
$offset += $written;
}
return true;
}
function unav_preview_type(string $extension, string $name): ?string { function unav_preview_type(string $extension, string $name): ?string {
$base = strtolower($name); $base = strtolower($name);
if (in_array($base, ['dockerfile', 'makefile'], true)) { if (in_array($base, ['dockerfile', 'makefile'], true)) {
+96 -5
View File
@@ -68,6 +68,7 @@ const uiIcons = {
move: '<path d="M5 12h14"></path><path d="m14 7 5 5-5 5"></path><path d="M5 7v10"></path>', move: '<path d="M5 12h14"></path><path d="m14 7 5 5-5 5"></path><path d="M5 7v10"></path>',
preview: '<path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12Z"></path><circle cx="12" cy="12" r="2.5"></circle>', preview: '<path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12Z"></path><circle cx="12" cy="12" r="2.5"></circle>',
refresh: '<path d="M20 6v5h-5"></path><path d="M4 18v-5h5"></path><path d="M19 11a7 7 0 0 0-12-4.9L4 9"></path><path d="M5 13a7 7 0 0 0 12 4.9l3-2.9"></path>', refresh: '<path d="M20 6v5h-5"></path><path d="M4 18v-5h5"></path><path d="M19 11a7 7 0 0 0-12-4.9L4 9"></path><path d="M5 13a7 7 0 0 0 12 4.9l3-2.9"></path>',
save: '<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z"></path><path d="M17 21v-8H7v8"></path><path d="M7 3v5h8"></path>',
shield: '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"></path><path d="m9 12 2 2 4-4"></path>', shield: '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"></path><path d="m9 12 2 2 4-4"></path>',
tree: '<path d="M4 5h6"></path><path d="M4 12h10"></path><path d="M4 19h14"></path><path d="M4 5v14"></path><circle cx="4" cy="5" r="1.5"></circle><circle cx="4" cy="12" r="1.5"></circle><circle cx="4" cy="19" r="1.5"></circle>', tree: '<path d="M4 5h6"></path><path d="M4 12h10"></path><path d="M4 19h14"></path><path d="M4 5v14"></path><circle cx="4" cy="5" r="1.5"></circle><circle cx="4" cy="12" r="1.5"></circle><circle cx="4" cy="19" r="1.5"></circle>',
upload: '<path d="M12 16V5"></path><path d="m8 9 4-4 4 4"></path><path d="M5 16v3h14v-3"></path>' upload: '<path d="M12 16V5"></path><path d="m8 9 4-4 4 4"></path><path d="M5 16v3h14v-3"></path>'
@@ -170,6 +171,10 @@ function openPreview(entry, sourceWindowId = state.focusedId) {
existing.data.entry = entry; existing.data.entry = entry;
existing.data.sourceWindowId = sourceWindowId; existing.data.sourceWindowId = sourceWindowId;
existing.data.content = ''; existing.data.content = '';
existing.data.editable = false;
existing.data.editing = false;
existing.data.draft = '';
existing.data.revision = '';
existing.data.loading = true; existing.data.loading = true;
existing.data.error = null; existing.data.error = null;
focusWindow(existing); focusWindow(existing);
@@ -187,6 +192,10 @@ function openPreview(entry, sourceWindowId = state.focusedId) {
entry, entry,
sourceWindowId, sourceWindowId,
content: '', content: '',
editable: false,
editing: false,
draft: '',
revision: '',
loading: true, loading: true,
error: null error: null
} }
@@ -268,8 +277,17 @@ function renderWindow(win) {
focusWindow(win); focusWindow(win);
render(); render();
}); });
titlebar.querySelector('[data-action="close"]').addEventListener('click', (event) => { titlebar.querySelector('[data-action="close"]').addEventListener('click', async (event) => {
event.stopPropagation(); 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.windows = state.windows.filter((item) => item.id !== win.id);
state.focusedId = state.windows.at(-1)?.id || null; state.focusedId = state.windows.at(-1)?.id || null;
render(); render();
@@ -635,22 +653,54 @@ function renderPreview(body, win) {
} }
const entry = data.entry; const entry = data.entry;
const navigation = previewNavigation(data); const navigation = previewNavigation(data);
const canEdit = data.editable && !isReadOnly();
body.innerHTML = ` body.innerHTML = `
<div class="preview-meta"> <div class="preview-meta">
<div class="preview-nav"> <div class="preview-nav">
<button class="icon" data-action="preview-prev" title="Vorherige Datei" aria-label="Vorherige Datei" ${navigation.previous ? '' : 'disabled'}>${iconSvg('arrowLeft')}</button> <button class="icon" data-action="preview-prev" title="Vorherige Datei" aria-label="Vorherige Datei" ${navigation.previous && !data.editing ? '' : 'disabled'}>${iconSvg('arrowLeft')}</button>
<button class="icon" data-action="preview-next" title="Nächste Datei" aria-label="Nächste Datei" ${navigation.next ? '' : 'disabled'}>${iconSvg('arrowRight')}</button> <button class="icon" data-action="preview-next" title="Nächste Datei" aria-label="Nächste Datei" ${navigation.next && !data.editing ? '' : 'disabled'}>${iconSvg('arrowRight')}</button>
</div> </div>
<strong>${escapeHtml(entry?.name || data.name || 'Vorschau')}</strong> <strong>${escapeHtml(entry?.name || data.name || 'Vorschau')}</strong>
<span>${escapeHtml(formatBytes(data.size || entry?.size || 0))}</span> <div class="preview-actions">
<span>${escapeHtml(formatBytes(data.size || entry?.size || 0))}</span>
${canEdit && !data.editing ? `<button data-action="preview-edit">${iconSvg('edit')}<span>Bearbeiten</span></button>` : ''}
${data.editing ? `<button data-action="preview-cancel"><span>Abbrechen</span></button><button class="primary" data-action="preview-save" ${data.saving || isReadOnly() ? 'disabled' : ''}>${iconSvg('save')}<span>${data.saving ? 'Speichert…' : 'Speichern'}</span></button>` : ''}
</div>
</div> </div>
${renderPreviewContent(data)} ${renderPreviewContent(data)}
`; `;
body.querySelector('[data-action="preview-prev"]')?.addEventListener('click', () => openPreview(navigation.previous, data.sourceWindowId)); 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-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) {
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());
}
body.querySelector('[data-action="preview-save"]')?.addEventListener('click', () => savePreview(win, editor?.value ?? data.draft ?? ''));
} }
function renderPreviewContent(data) { function renderPreviewContent(data) {
if (data.editing) {
return `<textarea class="preview-editor" aria-label="Datei bearbeiten" spellcheck="false">${escapeHtml(data.draft ?? data.content ?? '')}</textarea>`;
}
if (data.type === 'markdown') { if (data.type === 'markdown') {
return `<article class="preview-rendered">${renderMarkdown(data.content || '')}</article>`; return `<article class="preview-rendered">${renderMarkdown(data.content || '')}</article>`;
} }
@@ -702,6 +752,10 @@ async function loadPreview(win, entry) {
win.data.extension = result.extension; win.data.extension = result.extension;
win.data.rawUrl = result.rawUrl; win.data.rawUrl = result.rawUrl;
win.data.content = result.content; win.data.content = result.content;
win.data.editable = Boolean(result.editable);
win.data.editing = false;
win.data.draft = '';
win.data.revision = result.revision || '';
} catch (error) { } catch (error) {
win.data.error = error.message; win.data.error = error.message;
} finally { } finally {
@@ -710,6 +764,43 @@ async function loadPreview(win, entry) {
} }
} }
async function savePreview(win, content) {
if (win.data.saving || !win.data.editable || isReadOnly()) return;
win.data.saving = true;
render();
const body = new URLSearchParams();
body.set('content', 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 = 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) { function renderMarkdown(content) {
const blocks = []; const blocks = [];
let listItems = []; let listItems = [];
@@ -2644,7 +2735,7 @@ function windowTitle(win) {
return `Explorer · ${win.data.path || ''}`; return `Explorer · ${win.data.path || ''}`;
} }
if (win.kind === 'preview') { if (win.kind === 'preview') {
return `Vorschau · ${win.data.entry?.name || ''}`; return `${win.data.editing ? 'Editor' : 'Vorschau'} · ${win.data.entry?.name || ''}`;
} }
return win.title; return win.title;
} }
+42
View File
@@ -1264,6 +1264,27 @@
padding-bottom: 6px; padding-bottom: 6px;
} }
.u-nav .preview-actions {
align-items: center;
display: flex;
gap: 6px;
justify-content: flex-end;
white-space: nowrap;
}
.u-nav .preview-actions button {
align-items: center;
display: inline-flex;
font-size: 12px;
gap: 5px;
min-height: 28px;
}
.u-nav .preview-actions .unav-icon {
height: 14px;
width: 14px;
}
.u-nav .preview-nav { .u-nav .preview-nav {
display: inline-flex; display: inline-flex;
gap: 4px; gap: 4px;
@@ -1295,6 +1316,27 @@
white-space: pre; white-space: pre;
} }
.u-nav .preview-editor {
background: var(--surface-2);
border: 1px solid var(--accent);
border-radius: 7px;
color: var(--text);
font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
margin: 0;
min-height: 0;
outline: 0;
overflow: auto;
padding: 10px;
resize: none;
tab-size: 2;
white-space: pre;
width: 100%;
}
.u-nav .preview-editor:focus {
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 45%, transparent);
}
.u-nav .preview-rendered, .u-nav .preview-rendered,
.u-nav .preview-table-wrap, .u-nav .preview-table-wrap,
.u-nav .preview-media, .u-nav .preview-media,
+2 -2
View File
@@ -1,7 +1,7 @@
<!DOCTYPE PLUGIN [ <!DOCTYPE PLUGIN [
<!ENTITY name "u-navigator"> <!ENTITY name "u-navigator">
<!ENTITY author "Michael Roll"> <!ENTITY author "Michael Roll">
<!ENTITY version "2026.07.14.r016"> <!ENTITY version "2026.07.14.r017">
<!ENTITY package "&name;-&version;.tgz"> <!ENTITY package "&name;-&version;.tgz">
<!ENTITY pluginURL "https://git.casaderoll.de/michael/Unraid-Navigator/raw/branch/main/u-navigator.plg"> <!ENTITY pluginURL "https://git.casaderoll.de/michael/Unraid-Navigator/raw/branch/main/u-navigator.plg">
<!ENTITY support "https://git.casaderoll.de/michael/Unraid-Navigator"> <!ENTITY support "https://git.casaderoll.de/michael/Unraid-Navigator">
@@ -24,7 +24,7 @@
<FILE Name="/boot/config/plugins/&name;/&package;"> <FILE Name="/boot/config/plugins/&name;/&package;">
<URL>https://git.casaderoll.de/michael/Unraid-Navigator/raw/branch/main/packages/&package;</URL> <URL>https://git.casaderoll.de/michael/Unraid-Navigator/raw/branch/main/packages/&package;</URL>
<MD5>8c943cbf6a929bfb8e3249c901fb3869</MD5> <MD5>3fa2ea5659712c219ce073b7a16410c5</MD5>
</FILE> </FILE>
<FILE Run="/bin/bash"> <FILE Run="/bin/bash">