diff options
| author | historia <[not public]> | 2026-07-11 18:30:58 -0400 |
|---|---|---|
| committer | historia <[not public]> | 2026-07-11 18:30:58 -0400 |
| commit | 2bacbb08d1ac67c4f63ee535728cd4e8760e3211 (patch) | |
| tree | d8ee366b3d32b486eb05c5e10bc65cf194ae4c23 /internal/admin | |
| parent | 131cbbe586463a7232f332650af5f0b2c13dc7e9 (diff) | |
| download | thehouseoficarus-2bacbb08d1ac67c4f63ee535728cd4e8760e3211.tar.gz | |
feat(admin): unify context menu, add context menu to files tab
Diffstat (limited to 'internal/admin')
| -rw-r--r-- | internal/admin/api_files.go | 65 | ||||
| -rw-r--r-- | internal/admin/server.go | 1 | ||||
| -rw-r--r-- | internal/admin/static/ctxmenu.js | 47 | ||||
| -rw-r--r-- | internal/admin/static/editor.js | 106 | ||||
| -rw-r--r-- | internal/admin/templates/files.html | 130 | ||||
| -rw-r--r-- | internal/admin/templates/layout.html | 1 |
6 files changed, 251 insertions, 99 deletions
diff --git a/internal/admin/api_files.go b/internal/admin/api_files.go index 2a87dd3..496b08d 100644 --- a/internal/admin/api_files.go +++ b/internal/admin/api_files.go @@ -8,6 +8,71 @@ import ( "strings" ) +func (s *AdminServer) handleFileRename(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + var body struct { + Path string `json:"path"` + NewName string `json:"new_name"` + } + if err := readJSON(r, &body); err != nil || body.Path == "" || body.NewName == "" { + writeJSON(w, map[string]any{"error": "missing path or new_name"}) + return + } + + newName := strings.TrimSpace(body.NewName) + if newName == "" || newName == "." || newName == ".." || strings.ContainsAny(newName, "/\\") { + writeJSON(w, map[string]any{"error": "invalid file name"}) + return + } + for _, c := range newName { + if c < 32 || c == 127 { + writeJSON(w, map[string]any{"error": "file name contains invalid characters"}) + return + } + } + + relPath := strings.TrimPrefix(body.Path, "/") + relPath = strings.TrimPrefix(relPath, "data/") + oldAbs := filepath.Join(s.dataDir, relPath) + + oldContent, err := snapshotFile(oldAbs) + if err != nil { + writeJSON(w, map[string]any{"error": "file not found: " + relPath}) + return + } + + newAbs := filepath.Join(filepath.Dir(oldAbs), newName) + if _, err := os.Stat(newAbs); err == nil { + writeJSON(w, map[string]any{"error": "a file named " + newName + " already exists"}) + return + } + + if err := os.WriteFile(newAbs, oldContent, 0644); err != nil { + writeJSON(w, map[string]any{"error": "write error: " + err.Error()}) + return + } + if err := os.Remove(oldAbs); err != nil { + writeJSON(w, map[string]any{"error": "remove error: " + err.Error()}) + return + } + + newRelPath := filepath.Join(filepath.Dir(relPath), newName) + if filepath.Dir(relPath) == "." { + newRelPath = newName + } + s.undoStack.Push(ChangeDesc{ + Description: "Renamed file " + relPath + " to " + newRelPath, + FilePath: oldAbs, + NewFilePath: newAbs, + OldContent: oldContent, + NewContent: oldContent, + }) + writeJSON(w, map[string]any{"ok": true, "path": newRelPath}) +} + func (s *AdminServer) handleFiles(w http.ResponseWriter, r *http.Request) { relPath := r.URL.Query().Get("path") relPath = strings.TrimPrefix(relPath, "/") diff --git a/internal/admin/server.go b/internal/admin/server.go index f07bdd4..11efb5c 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -177,6 +177,7 @@ func NewServer(cfg *config.Config, useTLS bool, accountStore *player.AccountStor apiMux.HandleFunc("/api/undo/redo", s.doRedo) apiMux.HandleFunc("/api/next-room-id", s.handleNextRoomID) apiMux.HandleFunc("/api/files", s.handleFiles) + apiMux.HandleFunc("/api/files/rename", s.handleFileRename) apiMux.HandleFunc("/api/duplicate-rooms", s.handleDuplicateRooms) apiMux.HandleFunc("/api/rooms/resolve-duplicate", s.handleResolveDuplicate) apiMux.HandleFunc("/api/triggers", s.handleTriggers) diff --git a/internal/admin/static/ctxmenu.js b/internal/admin/static/ctxmenu.js new file mode 100644 index 0000000..96e92a9 --- /dev/null +++ b/internal/admin/static/ctxmenu.js @@ -0,0 +1,47 @@ +function openContextMenu(e, items) { + e.preventDefault(); + e.stopPropagation(); + closeContextMenu(); + + var overlay = document.createElement('div'); + overlay.className = 'cm-overlay'; + overlay.id = '_ctxMenuOverlay'; + overlay.onclick = function() { closeContextMenu(); }; + overlay.addEventListener('contextmenu', function(ev) { + ev.preventDefault(); + ev.stopPropagation(); + var cx = ev.clientX, cy = ev.clientY; + closeContextMenu(); + var el = document.elementFromPoint(cx, cy); + if (el) el.dispatchEvent(new MouseEvent('contextmenu', {bubbles:true, cancelable:true, clientX:cx, clientY:cy, button:2})); + }); + + var menu = document.createElement('div'); + menu.className = 'cm-menu'; + menu.id = '_ctxMenu'; + menu.style.left = e.clientX + 'px'; + menu.style.top = e.clientY + 'px'; + menu.oncontextmenu = function(ev) { ev.preventDefault(); }; + + function addBtn(label, cls, handler) { + var btn = document.createElement('button'); + btn.textContent = label; + if (cls) btn.className = cls; + btn.onclick = function() { closeContextMenu(); handler(); }; + menu.appendChild(btn); + } + + for (var i = 0; i < items.length; i++) { + addBtn(items[i].label, items[i].cls || '', items[i].handler); + } + + document.body.appendChild(overlay); + document.body.appendChild(menu); +} + +function closeContextMenu() { + var o = document.getElementById('_ctxMenuOverlay'); + var m = document.getElementById('_ctxMenu'); + if (o) o.remove(); + if (m) m.remove(); +} diff --git a/internal/admin/static/editor.js b/internal/admin/static/editor.js index d5fb5c7..fe0ef10 100644 --- a/internal/admin/static/editor.js +++ b/internal/admin/static/editor.js @@ -271,48 +271,17 @@ function createNewDir() { } function showDirContextMenu(e, dir) { - e.preventDefault(); - closeContextMenu(); if (dir === 'Root') return; - var overlay = document.createElement('div'); - overlay.className = 'cm-overlay'; - overlay.id = '_ctxMenuOverlay'; - overlay.onclick = function() { closeContextMenu(); }; - overlay.addEventListener('contextmenu', function(ev) { - ev.preventDefault(); - ev.stopPropagation(); - var cx = ev.clientX, cy = ev.clientY; - closeContextMenu(); - var el = document.elementFromPoint(cx, cy); - if (el) el.dispatchEvent(new MouseEvent('contextmenu', {bubbles:true, cancelable:true, clientX:cx, clientY:cy, button:2})); - }); - - var menu = document.createElement('div'); - menu.className = 'cm-menu'; - menu.id = '_ctxMenu'; - menu.style.left = e.clientX + 'px'; - menu.style.top = e.clientY + 'px'; - menu.oncontextmenu = function(ev) { ev.preventDefault(); }; - - function addBtn(label, cls, handler) { - var btn = document.createElement('button'); - btn.textContent = label; - if (cls) btn.className = cls; - btn.onclick = function() { closeContextMenu(); handler(); }; - menu.appendChild(btn); - } - - addBtn('Rename Directory', '', function() { renameDirInline(dir); }); - addBtn('Delete Directory', 'danger', function() { - API.post('/api/' + editorType + '/dirs', {action: 'delete', dir: dir}).then(function(r) { - notify('Deleted directory ' + dir + (r.moved ? ' (' + r.moved + ' files moved to root)' : ''), 'success'); - updateUndoBar(); - loadList(); - }).catch(function(e) { notify('Delete failed: ' + e.message, 'error'); }); - }); - - document.body.appendChild(overlay); - document.body.appendChild(menu); + openContextMenu(e, [ + {label: 'Rename Directory', handler: function() { renameDirInline(dir); }}, + {label: 'Delete Directory', cls: 'danger', handler: function() { + API.post('/api/' + editorType + '/dirs', {action: 'delete', dir: dir}).then(function(r) { + notify('Deleted directory ' + dir + (r.moved ? ' (' + r.moved + ' files moved to root)' : ''), 'success'); + updateUndoBar(); + loadList(); + }).catch(function(e) { notify('Delete failed: ' + e.message, 'error'); }); + }}, + ]); } function renameDirInline(dir) { @@ -325,44 +294,12 @@ function renameDirInline(dir) { } function showItemContextMenu(e, id) { - e.preventDefault(); - e.stopPropagation(); - closeContextMenu(); - - var overlay = document.createElement('div'); - overlay.className = 'cm-overlay'; - overlay.id = '_ctxMenuOverlay'; - overlay.onclick = function() { closeContextMenu(); }; - overlay.addEventListener('contextmenu', function(ev) { - ev.preventDefault(); - ev.stopPropagation(); - var cx = ev.clientX, cy = ev.clientY; - closeContextMenu(); - var el = document.elementFromPoint(cx, cy); - if (el) el.dispatchEvent(new MouseEvent('contextmenu', {bubbles:true, cancelable:true, clientX:cx, clientY:cy, button:2})); - }); - - var menu = document.createElement('div'); - menu.className = 'cm-menu'; - menu.id = '_ctxMenu'; - menu.style.left = e.clientX + 'px'; - menu.style.top = e.clientY + 'px'; - menu.oncontextmenu = function(ev) { ev.preventDefault(); }; - - function addBtn(label, cls, handler) { - var btn = document.createElement('button'); - btn.textContent = label; - if (cls) btn.className = cls; - btn.onclick = function() { closeContextMenu(); handler(); }; - menu.appendChild(btn); - } - - addBtn('Rename', '', function() { startInlineItemRename(id); }); - addBtn('Duplicate', '', function() { duplicateFromMenu(id); }); - addBtn('Remove', 'danger', function() { deleteItem(id); }); - - document.body.appendChild(overlay); - document.body.appendChild(menu); + var row = e.currentTarget; + openContextMenu(e, [ + {label: 'Rename', handler: function() { startInlineItemRename(id, row); }}, + {label: 'Duplicate', handler: function() { duplicateFromMenu(id); }}, + {label: 'Remove', cls: 'danger', handler: function() { deleteItem(id); }}, + ]); } function duplicateFromMenu(id) { @@ -409,15 +346,8 @@ function duplicateFromMenu(id) { }).catch(function(e) { notify('Duplicate failed: ' + e.message, 'error'); }); } -function closeContextMenu() { - var o = document.getElementById('_ctxMenuOverlay'); - var m = document.getElementById('_ctxMenu'); - if (o) o.remove(); - if (m) m.remove(); -} - -function startInlineItemRename(id) { - var el = document.querySelector('.item.active'); +function startInlineItemRename(id, row) { + var el = row; if (!el) return; var origHTML = el.innerHTML; el.innerHTML = '<input class="item-rename-input" value="' + escAttr(id) + '" maxlength="128">'; diff --git a/internal/admin/templates/files.html b/internal/admin/templates/files.html index b89a142..5a5106f 100644 --- a/internal/admin/templates/files.html +++ b/internal/admin/templates/files.html @@ -9,12 +9,14 @@ </div> </div> <script> -var currentPath = ''; +var currentDir = ''; +var currentFile = null; window._allFiles = []; function loadFiles(path) { - currentPath = path || ''; - API.get('/api/files' + (path ? '?path=' + encodeURIComponent(path) : '')).then(function(r){ + currentDir = path || ''; + currentFile = null; + return API.get('/api/files' + (path ? '?path=' + encodeURIComponent(path) : '')).then(function(r){ var files = r.files || r || []; window._allFiles = files; renderFileList(''); @@ -26,17 +28,17 @@ function renderFileList(filter){ var f = filter.toLowerCase(); var items = window._allFiles.filter(function(x){ return !f || x.name.toLowerCase().indexOf(f) >= 0; }); var html = '<div class="item" onclick="loadFiles(\'\')" style="color:#6cf">[root]</div>'; - if (currentPath) { - var parent = currentPath.split('/').slice(0,-1).join('/'); + if (currentDir) { + var parent = currentDir.split('/').slice(0,-1).join('/'); html += '<div class="item" onclick="loadFiles(\''+escJs(parent)+'\')" style="color:#6cf">[..]</div>'; } items.forEach(function(x){ if (x.dir) { - var sub = currentPath ? currentPath + '/' + x.name : x.name; + var sub = currentDir ? currentDir + '/' + x.name : x.name; html += '<div class="item" onclick="loadFiles(\''+escJs(sub)+'\')" style="color:#fc6">'+escHtml(x.name)+'/</div>'; } else { - var fp = currentPath ? currentPath + '/' + x.name : x.name; - html += '<div class="item" onclick="loadFileContent(\''+escJs(fp)+'\',\''+escJs(x.name)+'\')">'+escHtml(x.name)+'</div>'; + var fp = currentDir ? currentDir + '/' + x.name : x.name; + html += '<div class="item" data-path="'+escHtml(fp)+'" onclick="loadFileContent(\''+escJs(fp)+'\',\''+escJs(x.name)+'\')" oncontextmenu="showFileContextMenu(event,\''+escJs(fp)+'\',\''+escJs(x.name)+'\')">'+escHtml(x.name)+'</div>'; } }); el.innerHTML = html; @@ -45,7 +47,7 @@ function renderFileList(filter){ function filterFiles(val) { renderFileList(val); } function loadFileContent(path, name) { - currentPath = path; + currentFile = path; API.get('/api/files?path=' + encodeURIComponent(path)).then(function(r){ var content = r.content || r.raw || JSON.stringify(r,null,2); var html = '<h2>'+escHtml(name)+'</h2>'; @@ -66,13 +68,119 @@ function saveFile(path) { }).then(function(r) { if (!r.ok) throw new Error('Save failed'); return r.json(); - }).then(function() { + }).then(function(data) { + if (data && data.error) throw new Error(data.error); notify('File saved', 'success'); updateUndoBar(); }).catch(function(e) { notify('Save failed: '+e.message, 'error'); }); } -window.refreshPage = function() { loadFiles(currentPath); }; +function showFileContextMenu(e, path, name) { + openContextMenu(e, [ + {label: 'Rename', handler: function() { startInlineFileRename(path, name); }}, + {label: 'Duplicate', handler: function() { duplicateFile(path, name); }}, + {label: 'Delete', cls: 'danger', handler: function() { deleteFile(path); }}, + ]); +} + +function deleteFile(path) { + API.del('/api/files?path=' + encodeURIComponent(path)).then(function(r) { + notify('File deleted', 'success'); + updateUndoBar(); + if (currentFile === path) { + $('#editorMain').innerHTML = '<p style="color:#888;text-align:center;margin-top:60px">Select a file to edit</p>'; + currentFile = null; + } + loadFiles(currentDir); + }).catch(function(e) { notify('Delete failed: ' + e.message, 'error'); }); +} + +function duplicateFile(path, name) { + API.get('/api/files?path=' + encodeURIComponent(path)).then(function(r) { + var content = r.content || ''; + var dot = name.lastIndexOf('.'); + var base, ext; + if (dot > 0) { base = name.substring(0, dot); ext = name.substring(dot); } + else { base = name; ext = ''; } + + var baseName = base + '_copy'; + var newName = baseName + ext; + var counter = 2; + while (true) { + var exists = false; + for (var i = 0; i < window._allFiles.length; i++) { + if (window._allFiles[i].name === newName) { exists = true; break; } + } + if (!exists) break; + newName = baseName + '_' + counter + ext; + counter++; + } + + var newPath = currentDir ? currentDir + '/' + newName : newName; + fetch('/api/files?path=' + encodeURIComponent(newPath), { + method: 'PUT', + headers: {'Content-Type': 'text/plain'}, + body: content, + credentials: 'same-origin' + }).then(function(r) { + if (!r.ok) throw new Error('Duplicate failed'); + return r.json(); + }).then(function(data) { + if (data && data.error) throw new Error(data.error); + notify('Duplicated as ' + newName, 'success'); + updateUndoBar(); + loadFiles(currentDir).then(function() { loadFileContent(newPath, newName); }); + }).catch(function(e) { notify('Duplicate failed: ' + e.message, 'error'); }); + }).catch(function(e) { notify('Duplicate failed: ' + e.message, 'error'); }); +} + +function startInlineFileRename(path, name) { + var el = document.querySelector('#listEntries .item[data-path="' + escHtml(path) + '"]'); + if (!el) return; + var origHTML = el.innerHTML; + el.innerHTML = '<input class="item-rename-input" value="' + escHtml(name) + '" maxlength="255">'; + var input = el.querySelector('.item-rename-input'); + input.focus(); + input.select(); + + function finish(val) { + val = (val || '').trim(); + if (!val || val === name) { el.innerHTML = origHTML; return; } + if (val.indexOf('/') >= 0 || val.indexOf('\\') >= 0 || val === '.' || val === '..') { + notify('Invalid file name', 'error'); + el.innerHTML = origHTML; + return; + } + for (var i = 0; i < val.length; i++) { + var c = val.charCodeAt(i); + if (c < 32 || c === 127) { notify('Invalid file name', 'error'); el.innerHTML = origHTML; return; } + } + for (var j = 0; j < window._allFiles.length; j++) { + if (window._allFiles[j].name === val) { + notify('A file named "' + val + '" already exists.', 'error'); + el.innerHTML = origHTML; + return; + } + } + API.post('/api/files/rename', {path: path, new_name: val}).then(function(r) { + var newPath = r.path || (currentDir ? currentDir + '/' + val : val); + notify('Renamed to ' + val, 'success'); + updateUndoBar(); + loadFiles(currentDir).then(function() { loadFileContent(newPath, val); }); + }).catch(function(e) { + notify('Rename failed: ' + e.message, 'error'); + el.innerHTML = origHTML; + }); + } + + input.onkeydown = function(e) { + if (e.key === 'Enter') { input.blur(); } + else if (e.key === 'Escape') { el.innerHTML = origHTML; } + }; + input.onblur = function() { finish(input.value); }; +} + +window.refreshPage = function() { loadFiles(currentDir); }; function escHtml(s) { return String(s||'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); } function escJs(s) { return String(s||'').replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/"/g,'\\"'); } diff --git a/internal/admin/templates/layout.html b/internal/admin/templates/layout.html index fe4e0f9..f6bd405 100644 --- a/internal/admin/templates/layout.html +++ b/internal/admin/templates/layout.html @@ -6,6 +6,7 @@ <title>THOI Admin{{if .Page}} — {{.Page}}{{end}}</title> <link rel="stylesheet" href="/static/admin.css"> <script src="/static/admin.js"></script> +<script src="/static/ctxmenu.js"></script> <script src="/static/colorpicker.js"></script> </head> <body> |
