Files
tueit_Transkriptor/docs/plans/2026-04-01-transcript-modal-delete.md
T

384 lines
13 KiB
Markdown

# Transcript Modal & Delete Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Add transcript delete and a markdown-rendering modal viewer, removing the existing preview section.
**Architecture:** Two new REST endpoints (GET + DELETE `/transcripts/{filename}`) with path-confinement security. Frontend gains a full-screen modal using marked.js + DOMPurify for safe rendering; the static preview div is removed entirely. Each list item gets a trash icon that stops event propagation so it doesn't trigger the modal.
**Tech Stack:** FastAPI (existing), marked.js 14 + DOMPurify 3 via CDN, vanilla JS/CSS (no new build step)
---
### Task 1: Backend — GET /transcripts/{filename}
**Files:**
- Modify: `api/router.py`
- Modify: `output.py`
- Test: `tests/test_api.py`
**Step 1: Write the failing test**
Add to `tests/test_api.py`:
```python
def test_get_transcript_returns_content(tmp_path, monkeypatch):
f = tmp_path / "2026-01-01-0900-test.md"
f.write_text("# Hello\n\ncontent here\n")
from unittest.mock import patch
with patch("api.router.current_user", return_value={"username": "", "output_dir": str(tmp_path), "is_admin": False}):
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
r = client.get("/transcripts/2026-01-01-0900-test.md",
headers={"Authorization": "Bearer fake"})
assert r.status_code == 200
assert "Hello" in r.text
def test_get_transcript_rejects_path_traversal(tmp_path):
from unittest.mock import patch
with patch("api.router.current_user", return_value={"username": "", "output_dir": str(tmp_path), "is_admin": False}):
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
r = client.get("/transcripts/..%2Fsecret.md",
headers={"Authorization": "Bearer fake"})
assert r.status_code == 404
```
**Step 2: Run to verify it fails**
```bash
pytest tests/test_api.py::test_get_transcript_returns_content tests/test_api.py::test_get_transcript_rejects_path_traversal -v
```
Expected: FAIL — 404 or 405 (route doesn't exist yet)
**Step 3: Add `read_transcript` to `output.py`**
```python
def read_transcript(output_dir: str, filename: str) -> str | None:
"""Return file content if filename is a plain .md file inside output_dir."""
if os.path.basename(filename) != filename or not filename.endswith(".md"):
return None
path = os.path.join(output_dir, filename)
if not os.path.exists(path):
return None
with open(path, encoding="utf-8") as f:
return f.read()
```
**Step 4: Add GET endpoint to `api/router.py`**
Add after the existing `get_transcripts` endpoint:
```python
@router.get("/transcripts/{filename}")
async def get_transcript(filename: str, user: dict = Depends(current_user)):
from output import read_transcript
from fastapi.responses import PlainTextResponse
user_dir = os.path.join(user["output_dir"], user["username"])
content = read_transcript(user_dir, filename)
if content is None:
raise HTTPException(status_code=404, detail="Nicht gefunden")
return PlainTextResponse(content)
```
**Step 5: Run tests**
```bash
pytest tests/test_api.py::test_get_transcript_returns_content tests/test_api.py::test_get_transcript_rejects_path_traversal -v
```
Expected: PASS
**Step 6: Commit**
```bash
git add output.py api/router.py tests/test_api.py
git commit -m "feat: GET /transcripts/{filename} — serve transcript content"
```
---
### Task 2: Backend — DELETE /transcripts/{filename}
**Files:**
- Modify: `api/router.py`
- Test: `tests/test_api.py`
**Step 1: Write the failing tests**
Add to `tests/test_api.py`:
```python
def test_delete_transcript_removes_file(tmp_path):
f = tmp_path / "2026-01-01-0900-test.md"
f.write_text("content")
from unittest.mock import patch
with patch("api.router.current_user", return_value={"username": "", "output_dir": str(tmp_path), "is_admin": False}):
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
r = client.delete("/transcripts/2026-01-01-0900-test.md",
headers={"Authorization": "Bearer fake"})
assert r.status_code == 200
assert not f.exists()
def test_delete_transcript_rejects_path_traversal(tmp_path):
from unittest.mock import patch
with patch("api.router.current_user", return_value={"username": "", "output_dir": str(tmp_path), "is_admin": False}):
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
r = client.delete("/transcripts/..%2Fsecret.md",
headers={"Authorization": "Bearer fake"})
assert r.status_code == 404
```
**Step 2: Run to verify they fail**
```bash
pytest tests/test_api.py::test_delete_transcript_removes_file tests/test_api.py::test_delete_transcript_rejects_path_traversal -v
```
Expected: FAIL — route doesn't exist
**Step 3: Add DELETE endpoint to `api/router.py`**
```python
@router.delete("/transcripts/{filename}")
async def delete_transcript(filename: str, user: dict = Depends(current_user)):
user_dir = os.path.join(user["output_dir"], user["username"])
if os.path.basename(filename) != filename or not filename.endswith(".md"):
raise HTTPException(status_code=404, detail="Nicht gefunden")
path = os.path.join(user_dir, filename)
if not os.path.exists(path):
raise HTTPException(status_code=404, detail="Nicht gefunden")
os.unlink(path)
return {"ok": True}
```
**Step 4: Run tests**
```bash
pytest tests/test_api.py::test_delete_transcript_removes_file tests/test_api.py::test_delete_transcript_rejects_path_traversal -v
```
Expected: PASS
**Step 5: Commit**
```bash
git add api/router.py tests/test_api.py
git commit -m "feat: DELETE /transcripts/{filename} — delete transcript with path-confinement check"
```
---
### Task 3: Frontend — Remove preview section, add modal + marked.js + DOMPurify
**Files:**
- Modify: `frontend/index.html`
- Modify: `frontend/app.js`
No automated tests; manual verification checklist at end.
**Step 1: Remove preview section from `index.html`**
Delete this block from `<main>`:
```html
<section class="preview-section">
<label>Vorschau</label>
<div id="preview">Noch keine Aufnahme verarbeitet.</div>
</section>
```
Delete these CSS rules (search for them by selector):
- `.preview-section`
- `#preview`
- `#preview.has-content`
**Step 2: Add script tags — replace existing `<script src="/app.js">` line**
```html
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
<script src="/app.js"></script>
```
**Step 3: Add modal HTML + CSS**
Add this block inside `<main>` before `</main>` closing tag (it's a fixed overlay, position doesn't matter):
```html
<div id="modal" class="modal hidden" role="dialog" aria-modal="true">
<div class="modal-backdrop"></div>
<div class="modal-panel">
<div class="modal-header">
<span id="modal-title" class="modal-title"></span>
<div class="modal-actions">
<button id="modal-open-btn" class="modal-btn" title="Im Editor öffnen">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path d="M14 3h7v7h-2V6.41l-9.29 9.3-1.42-1.42L17.59 5H14V3zm-1 2H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8h-2v8H5V7h8V5z"/>
</svg>
</button>
<button id="modal-close-btn" class="modal-btn" title="Schließen"></button>
</div>
</div>
<div id="modal-body" class="modal-body"></div>
</div>
</div>
```
Add CSS inside `<style>`:
```css
.modal { position: fixed; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center; }
.modal.hidden { display: none; }
.modal-backdrop { position: absolute; inset: 0; background: rgba(0,0,0,0.7); }
.modal-panel {
position: relative; z-index: 1;
background: var(--surface); border: 1px solid var(--border); border-radius: 10px;
width: min(800px, 95vw); max-height: 85vh;
display: flex; flex-direction: column;
}
.modal-header {
display: flex; align-items: center; justify-content: space-between;
padding: 14px 18px; border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.modal-title { font-size: 0.9rem; font-weight: 600; }
.modal-actions { display: flex; gap: 8px; }
.modal-btn {
background: none; border: 1px solid var(--border); color: var(--muted);
border-radius: 6px; padding: 4px 8px; cursor: pointer; font-family: inherit;
font-size: 0.85rem; display: flex; align-items: center;
transition: border-color 0.15s, color 0.15s;
}
.modal-btn:hover { border-color: var(--red); color: var(--red); }
.modal-body {
padding: 20px 24px; overflow-y: auto; flex: 1;
font-size: 0.9rem; line-height: 1.7; color: var(--text);
}
.modal-body h1,.modal-body h2,.modal-body h3 { margin: 1em 0 0.4em; font-weight: 600; }
.modal-body h1 { font-size: 1.3rem; }
.modal-body h2 { font-size: 1.1rem; }
.modal-body p { margin: 0 0 0.8em; }
.modal-body ul,.modal-body ol { padding-left: 1.5em; margin: 0 0 0.8em; }
.modal-body code { background: var(--surface2); padding: 2px 5px; border-radius: 3px; font-size: 0.85em; }
.modal-body pre { background: var(--surface2); padding: 12px; border-radius: 6px; overflow-x: auto; margin: 0 0 0.8em; }
.modal-body pre code { background: none; padding: 0; }
.modal-body hr { border: none; border-top: 1px solid var(--border); margin: 1em 0; }
.del-btn {
background: none; border: none; color: var(--muted); cursor: pointer;
padding: 4px; border-radius: 4px; display: flex; align-items: center;
transition: color 0.15s; flex-shrink: 0;
}
.del-btn:hover { color: var(--red); }
```
**Step 4: Update `app.js`**
Remove these variable declarations at the top:
```javascript
const preview = document.getElementById('preview');
```
Add these variable declarations at the top:
```javascript
const modal = document.getElementById('modal');
const modalTitle = document.getElementById('modal-title');
const modalBody = document.getElementById('modal-body');
const modalOpenBtn = document.getElementById('modal-open-btn');
const modalCloseBtn = document.getElementById('modal-close-btn');
let _modalPath = null;
```
Add these functions and event listeners (after the `logoutBtn` listener):
```javascript
function openModal(filename, path) {
_modalPath = path;
modalTitle.textContent = filename.replace(/\.md$/, '').replace(/^\d{4}-\d{2}-\d{2}-\d{4}-/, '');
modalBody.innerHTML = '';
modal.classList.remove('hidden');
apiFetch(`/transcripts/${encodeURIComponent(filename)}`)
.then(r => r.text())
.then(md => {
modalBody.innerHTML = DOMPurify.sanitize(marked.parse(md));
});
}
function closeModal() {
modal.classList.add('hidden');
_modalPath = null;
}
modalCloseBtn.addEventListener('click', closeModal);
modal.querySelector('.modal-backdrop').addEventListener('click', closeModal);
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
modalOpenBtn.addEventListener('click', () => {
if (_modalPath) apiFetch('/open', { method: 'POST', body: JSON.stringify({ path: _modalPath }) });
});
```
In `loadTranscripts`, replace the existing `div.addEventListener` block and the `div.append(name, meta)` line with:
```javascript
div.addEventListener('click', () => openModal(t.filename, t.path));
const delBtn = document.createElement('button');
delBtn.className = 'del-btn';
delBtn.title = 'Löschen';
delBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M9 3h6l1 1h4v2H4V4h4l1-1zm-3 5h12l-1 13H7L6 8zm5 2v9h2v-9h-2zm-3 0v9h2v-9H8zm8 0v9h2v-9h-2z"/></svg>';
delBtn.addEventListener('click', async (e) => {
e.stopPropagation();
await apiFetch(`/transcripts/${encodeURIComponent(t.filename)}`, { method: 'DELETE' });
loadTranscripts();
});
div.append(name, meta, delBtn);
```
Remove the WS handler block that references preview:
```javascript
if (msg.event === 'transcribed' || msg.event === 'refined') {
const text = msg.raw || msg.markdown || '';
preview.textContent = text;
preview.classList.add('has-content');
}
```
Also remove the `setStatus('idle')` + `preview.*` lines from the click handler's `reset` branch — keep only the `setStatus('idle')` call.
**Step 5: Manual verification checklist**
Restart app (`kill $(pgrep -f main.py) && .venv/bin/python main.py &`), open browser:
- [ ] No "Vorschau" section visible
- [ ] Clicking a transcript item opens modal with rendered markdown
- [ ] Title in modal header shows human-readable name (date prefix stripped)
- [ ] Clicking backdrop or ✕ closes modal
- [ ] Pressing Escape closes modal
- [ ] "Im Editor öffnen" triggers xdg-open
- [ ] Trash icon deletes file and refreshes list
- [ ] Trash click does NOT open the modal
**Step 6: Commit**
```bash
git add frontend/index.html frontend/app.js
git commit -m "feat: transcript modal with markdown rendering, delete button, remove preview section"
```
---
### Task 4: Run full test suite
```bash
pytest -v
```
Expected: all tests pass. Fix any regressions before pushing.
```bash
git push
```