diff --git a/.gitignore b/.gitignore index 78288e4..4b44321 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ data/ .env .venv/ +venv/ __pycache__/ *.pyc *.tmp diff --git a/README.md b/README.md index 9939cab..d372bad 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # htmlet -Host a single HTML file at a clean public URL. Upload `page.html`, get back +Host HTML pages at clean public URLs. Upload `page.html`, get back `https://your-domain/html-1` — it renders in the browser as real HTML. +Group pages into folders and share one folder link so visitors can choose a page. Uploading needs an API key. Viewing is public. @@ -25,7 +26,9 @@ pages persist in the `htmlet-data` Docker volume (created automatically). ## Use **Web UI** — open the site, sign in with your key, drop an `.html` file, get the -live URL. The page list lets you replace or delete pages. +live URL. Create a folder, select it beside each page, then copy its public +`/f/` link. Visitors can search and open pages from that link. Deleting +a folder leaves its pages and individual URLs intact. **curl** @@ -42,8 +45,26 @@ curl -X PUT --data-binary @page.html -H "X-API-Key: $KEY" $SRV/api/files/landing # List / delete curl -H "X-API-Key: $KEY" $SRV/api/files curl -X DELETE -H "X-API-Key: $KEY" $SRV/api/files/landing + +# Create a folder, add pages, share its URL +curl -X POST -H "X-API-Key: $KEY" -H 'Content-Type: application/json' \ + -d '{"slug":"project"}' $SRV/api/folders +curl -X PUT -H "X-API-Key: $KEY" $SRV/api/folders/project/pages/landing +curl -H "X-API-Key: $KEY" $SRV/api/folders +# Share $SRV/f/project (public, no key needed) ``` +Each page belongs to at most one folder. Adding it to another folder moves it. +`DELETE /api/folders//pages/` removes membership; +`DELETE /api/folders/` removes only the folder. Existing flat page URLs +and upload commands keep working. Folder metadata persists in `folders.sqlite3` +inside the configured data directory. + +The CLI offers the same workflow: `htmlet folder create project`, +`htmlet folder add project landing`, and `htmlet folder list`. Use +`htmlet folder remove project landing` or `htmlet folder delete project` to +ungroup pages. + **Agents (Claude Code / Codex)** — [skills/htmlet/](skills/htmlet/SKILL.md) is an [Agent Skill](https://agentskills.io) that teaches an agent to publish its HTML output (reports, dashboards, demos) to your htmlet server and hand back the live diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..9fd527b --- /dev/null +++ b/TODO.md @@ -0,0 +1,6 @@ +- [x] Map page storage, API, UI, auth, and public serving. +- [x] Add persistent folders and protected management API. +- [x] Add public folder page picker and browser management UI. +- [x] Update docs/CLI; verify API, CLI, and JavaScript syntax. + +Unresolved questions: None. diff --git a/app/folder_routes.py b/app/folder_routes.py new file mode 100644 index 0000000..732affb --- /dev/null +++ b/app/folder_routes.py @@ -0,0 +1,115 @@ +"""Protected folder management and public folder page picker.""" + +from __future__ import annotations + +from html import escape +from pathlib import Path + +from fastapi import APIRouter, Depends, HTTPException, Request +from fastapi.responses import HTMLResponse + +from . import folders, storage +from .config import settings +from .models import DeleteResult, FileRef, FolderCreate, FolderEntry, FolderList +from .security import is_valid_slug, require_auth, validate_slug + +api = APIRouter( + prefix="/api/folders", tags=["folders"], dependencies=[Depends(require_auth)] +) +public = APIRouter() +_TEMPLATE = Path(__file__).parent / "templates" / "folder.html" + + +def _entry(request: Request, folder: folders.Folder) -> FolderEntry: + base = settings.base_url or str(request.base_url).rstrip("/") + pages = [] + for slug in folder.pages: + path = storage.path_if_exists(slug) + if path is not None: + pages.append( + FileRef(slug=slug, url=f"{base}/{slug}", size=path.stat().st_size) + ) + return FolderEntry(slug=folder.slug, url=f"{base}/f/{folder.slug}", pages=pages) + + +def _required_folder(slug: str) -> folders.Folder: + folder = folders.get(slug) + if folder is None: + raise HTTPException(404, "folder not found") + return folder + + +@api.post("", status_code=201) +def create_folder(body: FolderCreate, request: Request) -> FolderEntry: + validate_slug(body.slug) + if not folders.create(body.slug): + raise HTTPException(409, f"folder '{body.slug}' already exists") + return _entry(request, folders.Folder(body.slug, [])) + + +@api.get("") +def list_folders(request: Request) -> FolderList: + return FolderList( + folders=[_entry(request, folder) for folder in folders.list_all()] + ) + + +@api.delete("/{slug}") +def delete_folder(slug: str) -> DeleteResult: + validate_slug(slug) + if not folders.delete(slug): + raise HTTPException(404, "folder not found") + return DeleteResult(deleted=slug) + + +@api.put("/{slug}/pages/{page_slug}") +def add_folder_page(slug: str, page_slug: str, request: Request) -> FolderEntry: + validate_slug(slug) + validate_slug(page_slug) + if not storage.exists(page_slug): + raise HTTPException(404, "page not found") + if not folders.assign(slug, page_slug): + raise HTTPException(404, "folder not found") + return _entry(request, _required_folder(slug)) + + +@api.delete("/{slug}/pages/{page_slug}") +def remove_folder_page(slug: str, page_slug: str, request: Request) -> FolderEntry: + validate_slug(slug) + validate_slug(page_slug) + if not folders.remove(slug, page_slug): + raise HTTPException(404, "page not in folder") + return _entry(request, _required_folder(slug)) + + +@public.get("/f/{slug}", response_class=HTMLResponse, include_in_schema=False) +def serve_folder(slug: str) -> HTMLResponse: + if not is_valid_slug(slug): + raise HTTPException(404, "folder not found") + folder = _required_folder(slug) + pages = [page for page in folder.pages if storage.exists(page)] + items = "".join( + f'
  • ' + f'{escape(page)}
  • ' + for page in pages + ) + if not items: + items = '
  • No pages in this folder yet.
  • ' + content = ( + _TEMPLATE.read_text(encoding="utf-8") + .replace("{{FOLDER}}", escape(slug)) + .replace("{{COUNT}}", str(len(pages))) + .replace("{{PAGES}}", items) + ) + return HTMLResponse( + content, + headers={ + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "Content-Security-Policy": ( + "default-src 'none'; style-src 'unsafe-inline'; " + "script-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'" + ), + }, + ) diff --git a/app/folders.py b/app/folders.py new file mode 100644 index 0000000..2b83bd3 --- /dev/null +++ b/app/folders.py @@ -0,0 +1,107 @@ +"""SQLite folder membership; page bytes remain in the existing flat store.""" + +from __future__ import annotations + +import sqlite3 +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass + +from .config import settings + + +@dataclass(frozen=True) +class Folder: + slug: str + pages: list[str] + + +@contextmanager +def _connect() -> Iterator[sqlite3.Connection]: + connection = sqlite3.connect(settings.data_dir / "folders.sqlite3", timeout=10) + try: + connection.execute("PRAGMA foreign_keys = ON") + with connection: + yield connection + finally: + connection.close() + + +def initialize() -> None: + with _connect() as db: + db.execute("CREATE TABLE IF NOT EXISTS folders (slug TEXT PRIMARY KEY)") + db.execute( + "CREATE TABLE IF NOT EXISTS folder_pages (" + "page_slug TEXT PRIMARY KEY, folder_slug TEXT NOT NULL " + "REFERENCES folders(slug) ON DELETE CASCADE)" + ) + db.execute( + "CREATE INDEX IF NOT EXISTS folder_pages_folder ON folder_pages(folder_slug)" + ) + + +def create(slug: str) -> bool: + with _connect() as db: + cursor = db.execute("INSERT OR IGNORE INTO folders(slug) VALUES (?)", (slug,)) + return cursor.rowcount == 1 + + +def get(slug: str) -> Folder | None: + with _connect() as db: + if not db.execute("SELECT 1 FROM folders WHERE slug = ?", (slug,)).fetchone(): + return None + pages = [ + row[0] + for row in db.execute( + "SELECT page_slug FROM folder_pages WHERE folder_slug = ? " + "ORDER BY page_slug", + (slug,), + ) + ] + return Folder(slug, pages) + + +def list_all() -> list[Folder]: + with _connect() as db: + slugs = [row[0] for row in db.execute("SELECT slug FROM folders ORDER BY slug")] + rows = db.execute( + "SELECT folder_slug, page_slug FROM folder_pages ORDER BY page_slug" + ).fetchall() + pages: dict[str, list[str]] = {slug: [] for slug in slugs} + for folder_slug, page_slug in rows: + pages[folder_slug].append(page_slug) + return [Folder(slug, pages[slug]) for slug in slugs] + + +def delete(slug: str) -> bool: + with _connect() as db: + cursor = db.execute("DELETE FROM folders WHERE slug = ?", (slug,)) + return cursor.rowcount == 1 + + +def assign(folder_slug: str, page_slug: str) -> bool: + with _connect() as db: + if not db.execute( + "SELECT 1 FROM folders WHERE slug = ?", (folder_slug,) + ).fetchone(): + return False + db.execute( + "INSERT INTO folder_pages(page_slug, folder_slug) VALUES (?, ?) " + "ON CONFLICT(page_slug) DO UPDATE SET folder_slug = excluded.folder_slug", + (page_slug, folder_slug), + ) + return True + + +def remove(folder_slug: str, page_slug: str) -> bool: + with _connect() as db: + cursor = db.execute( + "DELETE FROM folder_pages WHERE folder_slug = ? AND page_slug = ?", + (folder_slug, page_slug), + ) + return cursor.rowcount == 1 + + +def remove_page(page_slug: str) -> None: + with _connect() as db: + db.execute("DELETE FROM folder_pages WHERE page_slug = ?", (page_slug,)) diff --git a/app/main.py b/app/main.py index c86be83..e450741 100644 --- a/app/main.py +++ b/app/main.py @@ -12,11 +12,14 @@ from fastapi import APIRouter, Depends, FastAPI, HTTPException, Query, Request, Response from fastapi.responses import HTMLResponse, PlainTextResponse +from fastapi.staticfiles import StaticFiles from starlette.concurrency import run_in_threadpool from starlette.datastructures import UploadFile -from . import storage +from . import folders, storage from .config import settings +from .folder_routes import api as folders_api +from .folder_routes import public as public_folders from .models import ( DeleteResult, FileEntry, @@ -82,6 +85,7 @@ def _load_favicon() -> bytes | None: @asynccontextmanager async def lifespan(_: FastAPI) -> AsyncIterator[None]: settings.validate() + folders.initialize() yield @@ -94,6 +98,7 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]: redoc_url=None, openapi_url="/api/openapi.json", ) +app.mount("/static", StaticFiles(directory=Path(__file__).parent / "static")) # Public API routes (no auth): login/logout/session. public_api = APIRouter(prefix="/api", tags=["auth"]) @@ -413,12 +418,15 @@ def delete_file(slug: str) -> DeleteResult: validate_slug(slug) if not storage.delete(slug): raise HTTPException(404, "not found") + folders.remove_page(slug) return DeleteResult(deleted=slug) # Register the API routers BEFORE the catch-all below so /api/* is never shadowed. app.include_router(public_api) app.include_router(files_api) +app.include_router(folders_api) +app.include_router(public_folders) # --------------------------------------------------------------------------- # diff --git a/app/models.py b/app/models.py index ea27630..5221287 100644 --- a/app/models.py +++ b/app/models.py @@ -42,6 +42,20 @@ class FileList(BaseModel): files: list[FileEntry] +class FolderCreate(BaseModel): + slug: str + + +class FolderEntry(BaseModel): + slug: str + url: str + pages: list[FileRef] + + +class FolderList(BaseModel): + folders: list[FolderEntry] + + class DeleteResult(BaseModel): deleted: str diff --git a/app/static/index.js b/app/static/index.js new file mode 100644 index 0000000..1b13fb1 --- /dev/null +++ b/app/static/index.js @@ -0,0 +1,371 @@ +(function () { + const $ = (id) => document.getElementById(id); + const sessionEl = $("session"), signout = $("signout"), + loginView = $("loginView"), loginKey = $("loginKey"), loginBtn = $("loginBtn"), loginStatus = $("loginStatus"), + appView = $("appView"), + tabPublish = $("tabPublish"), tabPrompts = $("tabPrompts"), + promptsView = $("promptsView"), promptList = $("promptList"), + form = $("form"), drop = $("drop"), fileInput = $("file"), + dzEmpty = $("dzEmpty"), dzFile = $("dzFile"), dzName = $("dzName"), dzSize = $("dzSize"), dzClear = $("dzClear"), + slug = $("slug"), statusEl = $("status"), + result = $("result"), link = $("resultLink"), openLink = $("openLink"), + pagesEl = $("pages"), refresh = $("refresh"), rep = $("rep"), + foldersEl = $("folders"), folderForm = $("folderForm"), folderSlug = $("folderSlug"); + + let selectedFile = null, repSlug = null; + let folders = []; + let authed = false, activeTab = "publish"; + + // Every API call carries X-HS-Auth so cookie auth is honored (and CSRF isn't). + const api = (path, opts = {}) => { + opts.headers = Object.assign({ "X-HS-Auth": "1" }, opts.headers || {}); + return fetch(path, opts); + }; + const fmtSize = (n) => n < 1024 ? n + " B" : n < 1048576 ? (n / 1024).toFixed(1) + " KB" : (n / 1048576).toFixed(1) + " MB"; + function setStatus(m, isErr) { statusEl.textContent = m || ""; statusEl.classList.toggle("err", !!isErr); } + function setLoginStatus(m, isErr) { loginStatus.textContent = m || ""; loginStatus.classList.toggle("err", !!isErr); } + + function friendly(st, data, ctx) { + const m = { + 400: "Check the slug — letters, numbers, - and _ only.", + 401: "Session expired — sign in again.", + 409: "That slug is taken — use Replace on the existing page.", + 413: "That file is over the size limit.", + 507: "Storage is full (file limit reached).", + }; + return m[st] || (data && data.detail ? "Error: " + data.detail : (ctx || "Request") + " failed (" + st + ")."); + } + function onAuthLost() { showLogin(); setLoginStatus("Session expired — sign in again.", true); } + + // --- views --------------------------------------------------------------- + // Two tabs share the masthead. "Publish" shows the login form or the app + // depending on auth; "Prompts" is always reachable, signed in or not. + function applyView() { + const onPrompts = activeTab === "prompts"; + promptsView.hidden = !onPrompts; + tabPublish.classList.toggle("active", !onPrompts); + tabPrompts.classList.toggle("active", onPrompts); + tabPublish.setAttribute("aria-selected", String(!onPrompts)); + tabPrompts.setAttribute("aria-selected", String(onPrompts)); + sessionEl.hidden = !authed; + loginView.hidden = onPrompts || authed; + appView.hidden = onPrompts || !authed; + } + function selectTab(tab) { + activeTab = tab; + applyView(); + if (tab === "publish" && !authed) loginKey.focus(); + } + tabPublish.addEventListener("click", () => selectTab("publish")); + tabPrompts.addEventListener("click", () => selectTab("prompts")); + + function showLogin() { + authed = false; + setStatus(""); result.hidden = true; + applyView(); + if (activeTab === "publish") loginKey.focus(); + } + function showApp() { + authed = true; + setLoginStatus(""); + applyView(); + loadPages(); + } + + (async function init() { + try { + const res = await api("/api/session"); + const data = await res.json(); + data.authenticated ? showApp() : showLogin(); + } catch (_) { showLogin(); } + })(); + + // --- login / logout ------------------------------------------------------ + loginView.addEventListener("submit", async (e) => { + e.preventDefault(); + const key = loginKey.value.trim(); + if (!key) return setLoginStatus("Enter your API key.", true); + loginBtn.disabled = true; setLoginStatus("Signing in…"); + try { + const res = await api("/api/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key }) }); + if (res.ok) { loginKey.value = ""; showApp(); } + else if (res.status === 401) setLoginStatus("That key didn't match.", true); + else setLoginStatus("Sign in failed (" + res.status + ").", true); + } catch (_) { setLoginStatus("Network error — is the server reachable?", true); } + finally { loginBtn.disabled = false; } + }); + + signout.addEventListener("click", async () => { + try { await api("/api/logout", { method: "POST" }); } catch (_) {} + selectedFile = null; setFile(null); slug.value = ""; + showLogin(); + }); + + // --- drop zone ----------------------------------------------------------- + function setFile(f) { + selectedFile = f || null; + if (f) { + dzName.textContent = f.name; dzSize.textContent = fmtSize(f.size); + dzEmpty.hidden = true; dzFile.hidden = false; + if (!slug.value) { + const base = f.name.replace(/\.html?$/i, ""); + if (/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(base)) slug.value = base; + } + } else { + dzEmpty.hidden = false; dzFile.hidden = true; fileInput.value = ""; + } + } + drop.addEventListener("click", (e) => { if (e.target !== dzClear) fileInput.click(); }); + drop.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); fileInput.click(); } }); + fileInput.addEventListener("change", (e) => { if (e.target.files[0]) setFile(e.target.files[0]); }); + dzClear.addEventListener("click", (e) => { e.stopPropagation(); setFile(null); }); + ["dragenter", "dragover"].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add("drag"); })); + drop.addEventListener("dragleave", (e) => { if (!drop.contains(e.relatedTarget)) drop.classList.remove("drag"); }); + drop.addEventListener("drop", (e) => { e.preventDefault(); drop.classList.remove("drag"); const f = e.dataTransfer.files[0]; if (f) setFile(f); }); + + // --- publish ------------------------------------------------------------- + function showResult(url) { link.textContent = url; link.href = url; openLink.href = url; result.hidden = false; } + $("copy").addEventListener("click", async () => { + try { await navigator.clipboard.writeText(link.textContent); setStatus("Copied to clipboard."); } + catch (_) { setStatus("Couldn't copy — select the URL manually.", true); } + }); + + form.addEventListener("submit", async (e) => { + e.preventDefault(); + if (!selectedFile) return setStatus("Choose an HTML file first.", true); + $("submit").disabled = true; setStatus("Publishing…"); result.hidden = true; + const fd = new FormData(); + fd.append("file", selectedFile, selectedFile.name); + if (slug.value.trim()) fd.append("slug", slug.value.trim()); + try { + const res = await api("/api/upload", { method: "POST", body: fd }); + const data = await res.json().catch(() => ({})); + if (res.status === 401) return onAuthLost(); + if (!res.ok) { setStatus(friendly(res.status, data, "Upload"), true); return; } + setStatus("Published."); showResult(data.url); + setFile(null); slug.value = ""; + loadPages(); + } catch (_) { setStatus("Network error — is the server reachable?", true); } + finally { $("submit").disabled = false; } + }); + + // --- manage -------------------------------------------------------------- + function folderRow(item) { + const row = document.createElement("div"); row.className = "folder-row"; + const a = document.createElement("a"); a.className = "folder-link"; a.href = item.url; + a.target = "_blank"; a.rel = "noopener"; a.textContent = item.slug + " ↗"; + const count = document.createElement("span"); count.className = "folder-count"; + count.textContent = item.pages.length + (item.pages.length === 1 ? " page" : " pages"); + const copy = document.createElement("button"); copy.type = "button"; copy.className = "mini"; copy.textContent = "Copy link"; + copy.addEventListener("click", async () => { + try { await navigator.clipboard.writeText(item.url); setStatus("Folder link copied."); } + catch (_) { setStatus("Couldn't copy — open folder link to copy it.", true); } + }); + const del = document.createElement("button"); del.type = "button"; del.className = "mini danger"; del.textContent = "Delete"; + del.addEventListener("click", () => delFolder(item)); + row.append(a, count, copy, del); + return row; + } + + function renderFolders() { + foldersEl.replaceChildren(); + if (!folders.length) { foldersEl.innerHTML = '

    No folders yet.

    '; return; } + folders.forEach((item) => foldersEl.appendChild(folderRow(item))); + } + + async function setPageFolder(pageSlug, current, next) { + const path = next ? "/api/folders/" + encodeURIComponent(next) + "/pages/" + encodeURIComponent(pageSlug) + : "/api/folders/" + encodeURIComponent(current) + "/pages/" + encodeURIComponent(pageSlug); + try { + const res = await api(path, { method: next ? "PUT" : "DELETE" }); + const data = await res.json().catch(() => ({})); + if (res.status === 401) return onAuthLost(); + if (!res.ok) { setStatus(friendly(res.status, data, "Move page"), true); return loadPages(); } + setStatus(next ? "Page moved to " + next + "." : "Page removed from folder."); + loadPages(); + } catch (_) { setStatus("Network error.", true); loadPages(); } + } + + function rowEl(item) { + const row = document.createElement("div"); + row.className = "prow"; row.dataset.slug = item.slug; + const dot = document.createElement("span"); dot.className = "dot"; + const a = document.createElement("a"); a.className = "pslug"; a.href = item.url; + a.target = "_blank"; a.rel = "noopener"; a.textContent = item.slug; + const size = document.createElement("span"); size.className = "psize"; size.textContent = fmtSize(item.size); + const acts = document.createElement("span"); acts.className = "pactions"; + const current = folders.find((folder) => folder.pages.some((page) => page.slug === item.slug)); + const select = document.createElement("select"); select.className = "folder-select"; + select.setAttribute("aria-label", "Folder for " + item.slug); + const none = new Option("No folder", ""); select.add(none); + folders.forEach((folder) => select.add(new Option(folder.slug, folder.slug))); + select.value = current ? current.slug : ""; + select.addEventListener("change", () => setPageFolder(item.slug, current ? current.slug : "", select.value)); + const rb = document.createElement("button"); rb.type = "button"; rb.className = "mini"; rb.textContent = "Replace"; + rb.addEventListener("click", () => { repSlug = item.slug; rep.value = ""; rep.click(); }); + const db = document.createElement("button"); db.type = "button"; db.className = "mini danger"; db.textContent = "Delete"; + db.addEventListener("click", () => delPage(item.slug, row)); + acts.append(select, rb, db); + row.append(dot, a, size, acts); + return row; + } + + async function loadPages() { + pagesEl.innerHTML = '

    Loading…

    '; + try { + const [res, folderRes] = await Promise.all([api("/api/files?limit=1000"), api("/api/folders")]); + if (res.status === 401 || folderRes.status === 401) { onAuthLost(); return; } + const data = await res.json().catch(() => ({})); + const folderData = await folderRes.json().catch(() => ({})); + if (!res.ok || !folderRes.ok) { pagesEl.innerHTML = '

    Couldn\'t load pages or folders.

    '; return; } + folders = folderData.folders || []; + renderFolders(); + const files = data.files || []; + if (!files.length) { pagesEl.innerHTML = '

    No pages yet — upload one above.

    '; return; } + pagesEl.innerHTML = ""; + files.forEach((item) => pagesEl.appendChild(rowEl(item))); + if (data.total > files.length) { + const p = document.createElement("p"); p.className = "pmsg"; + p.textContent = "Showing " + files.length + " of " + data.total + "."; + pagesEl.appendChild(p); + } + } catch (_) { pagesEl.innerHTML = '

    Network error.

    '; } + } + + rep.addEventListener("change", async (e) => { + const f = e.target.files[0]; + const target = repSlug; repSlug = null; + if (!f || !target) return; + setStatus("Updating " + target + "…"); + try { + const res = await api("/api/files/" + encodeURIComponent(target), { method: "PUT", headers: { "Content-Type": "text/html" }, body: f }); + const data = await res.json().catch(() => ({})); + if (res.status === 401) return onAuthLost(); + if (!res.ok) { setStatus(friendly(res.status, data, "Update"), true); return; } + setStatus("Updated " + target + "."); + const row = [...pagesEl.querySelectorAll(".prow")].find((item) => item.dataset.slug === target); + if (row) { row.classList.add("flash"); setTimeout(() => row.classList.remove("flash"), 1200); } + loadPages(); + } catch (_) { setStatus("Network error.", true); } + }); + + async function delPage(s, row) { + if (!confirm('Delete "' + s + '"? This removes the page permanently.')) return; + setStatus("Deleting " + s + "…"); + try { + const res = await api("/api/files/" + encodeURIComponent(s), { method: "DELETE" }); + const data = await res.json().catch(() => ({})); + if (res.status === 401) return onAuthLost(); + if (!res.ok) { setStatus(friendly(res.status, data, "Delete"), true); return; } + setStatus("Deleted " + s + "."); + loadPages(); + } catch (_) { setStatus("Network error.", true); } + } + + refresh.addEventListener("click", loadPages); + + folderForm.addEventListener("submit", async (e) => { + e.preventDefault(); + const name = folderSlug.value.trim(); + if (!name) return; + try { + const res = await api("/api/folders", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ slug: name }) }); + const data = await res.json().catch(() => ({})); + if (res.status === 401) return onAuthLost(); + if (!res.ok) return setStatus(friendly(res.status, data, "Create folder"), true); + folderSlug.value = ""; setStatus("Folder created. Assign pages below, then share its link."); loadPages(); + } catch (_) { setStatus("Network error.", true); } + }); + + async function delFolder(item) { + if (!confirm('Delete folder "' + item.slug + '"? Its pages will remain available.')) return; + try { + const res = await api("/api/folders/" + encodeURIComponent(item.slug), { method: "DELETE" }); + const data = await res.json().catch(() => ({})); + if (res.status === 401) return onAuthLost(); + if (!res.ok) return setStatus(friendly(res.status, data, "Delete folder"), true); + setStatus("Folder deleted; pages remain available."); loadPages(); + } catch (_) { setStatus("Network error.", true); } + } + + // --- prompts ------------------------------------------------------------- + const PROMPTS = [ + { + tag: "Explain", + title: "Explain unfamiliar code", + desc: "Turn a subsystem into a page you read once.", + body: `I don't understand how our rate limiter actually works. Read the relevant code and produce a single HTML explainer page: a diagram of the token-bucket flow, the 3–4 key code snippets annotated, and a "gotchas" section at the bottom. Optimize it for someone reading it once.`, + }, + { + tag: "Organize", + title: "Prioritize a backlog", + desc: "Draggable Now / Next / Later / Cut board.", + body: `I need to reprioritize these 30 Linear tickets. Make me an HTML file with each ticket as a draggable card across Now / Next / Later / Cut columns. Pre-sort them by your best guess. Add a "copy as markdown" button that exports the final ordering with a one-line rationale per bucket.`, + }, + { + tag: "Build", + title: "Edit a config safely", + desc: "Form editor that warns on broken dependencies.", + body: `Here's our feature flag config. Build a form-based editor for it, group flags by area, show dependencies between them, warn me if I enable a flag whose prerequisite is off. Add a "copy diff" button that gives me just the changed keys.`, + }, + { + tag: "Build", + title: "Tune a prompt", + desc: "Side-by-side editor with live template preview.", + body: `I'm tuning this system prompt. Make a side-by-side editor: editable prompt on the left with the variable slots highlighted, three sample inputs on the right that re-render the filled template live. Add a character/token counter and a copy button.`, + }, + { + tag: "Explore", + title: "Compare directions", + desc: "Six labeled variations, side by side.", + body: `I'm not sure what direction to take the onboarding screen. Generate 6 distinctly different approaches — vary layout, tone, and density — and lay them out as a single HTML file in a grid so I can compare them side by side. Label each with the tradeoff it's making.`, + }, + { + tag: "Plan", + title: "Plan a feature", + desc: "Readable plan with mockups and snippets.", + body: `Create a thorough implementation plan in a HTML file, be sure to make some mockups, show data flow and add important code snippets I might want to review. Make it easy to read and digest.`, + }, + { + tag: "Review", + title: "Review a PR", + desc: "Annotated diff, findings by severity.", + body: `Help me review this PR by creating an HTML artifact that describes it. I'm not very familiar with the streaming/backpressure logic so focus on that. Render the actual diff with inline margin annotations, color-code findings by severity and whatever else might be needed to convey the concept well.`, + }, + { + tag: "Prototype", + title: "Tweak an animation", + desc: "Live sliders for a checkout-button effect.", + body: `I want to prototype a new checkout button, when clicked it does a play animation and then turns purple quickly. Create a HTML file with several sliders and options for me to try different options on this animation, give me a copy button to copy the parameters that worked well.`, + }, + ]; + + function copyPrompt(text, btn) { + navigator.clipboard.writeText(text).then(() => { + btn.textContent = "Copied"; btn.classList.add("ok"); + setTimeout(() => { btn.textContent = "Copy"; btn.classList.remove("ok"); }, 1200); + }).catch(() => { + btn.textContent = "Copy failed"; + setTimeout(() => { btn.textContent = "Copy"; }, 1200); + }); + } + + function renderPrompts() { + promptList.innerHTML = ""; + PROMPTS.forEach((p) => { + const card = document.createElement("div"); card.className = "pcard"; + const top = document.createElement("div"); top.className = "pcard-top"; + const tag = document.createElement("span"); tag.className = "ptag"; tag.textContent = p.tag; + const btn = document.createElement("button"); btn.type = "button"; btn.className = "mini"; btn.textContent = "Copy"; + btn.addEventListener("click", () => copyPrompt(p.body, btn)); + top.append(tag, btn); + const title = document.createElement("h3"); title.className = "pcard-title"; title.textContent = p.title; + const desc = document.createElement("p"); desc.className = "pcard-desc"; desc.textContent = p.desc; + const body = document.createElement("div"); body.className = "pcard-body"; body.textContent = p.body; + card.append(top, title, desc, body); + promptList.appendChild(card); + }); + } + + renderPrompts(); +})(); diff --git a/app/templates/folder.html b/app/templates/folder.html new file mode 100644 index 0000000..1f5f2e8 --- /dev/null +++ b/app/templates/folder.html @@ -0,0 +1,43 @@ + + + + + + +{{FOLDER}} · htmlet + + + +
    + <htmlet> +

    {{FOLDER}}

    +

    {{COUNT}} pages · choose one to open

    + +
      {{PAGES}}
    +
    + + + diff --git a/app/templates/index.html b/app/templates/index.html index 4371cd9..844e4c7 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -159,6 +159,18 @@ .pslug:hover { text-decoration: underline; } .psize { font-family: var(--mono); font-size: 12.5px; color: var(--ink-2); white-space: nowrap; } .pactions { display: flex; gap: 8px; flex: none; } + .folder-form { display: flex; gap: 8px; margin-top: 16px; } + .folder-form .keyinput { flex: 1; min-width: 0; } + .folder-list { margin-top: 14px; } + .folder-row { display: flex; align-items: center; gap: 10px; padding: 9px 4px; border-top: 1px solid var(--rule); } + .folder-link { font-family: var(--mono); font-size: 14px; color: var(--accent); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .folder-count { font-family: var(--mono); font-size: 12px; color: var(--ink-2); white-space: nowrap; } + .folder-select { max-width: 128px; border: 1px solid var(--rule); border-radius: 7px; padding: 6px; background: #fff; color: var(--ink); font: 12px var(--sans); } + @media (max-width: 560px) { + .prow { flex-wrap: wrap; } + .pactions { width: 100%; justify-content: flex-end; } + .folder-row { flex-wrap: wrap; } + } .foot { font-family: var(--mono); font-size: 12px; color: var(--ink-2); @@ -281,6 +293,18 @@ Open ↗ +
    +
    +

    Folders

    +
    +

    Share one folder link so others can choose a page.

    +
    + + +
    +
    +
    +

    Your pages

    @@ -302,308 +326,6 @@

    Your pages

    - + diff --git a/client/htmlet.py b/client/htmlet.py index 1714037..c885b9d 100644 --- a/client/htmlet.py +++ b/client/htmlet.py @@ -23,6 +23,7 @@ import secrets import sys import urllib.error +import urllib.parse import urllib.request from pathlib import Path @@ -42,13 +43,18 @@ def _key(args: argparse.Namespace) -> str: def _request( - method: str, url: str, *, data: bytes | None = None, key: str | None = None + method: str, + url: str, + *, + data: bytes | None = None, + key: str | None = None, + content_type: str = "text/html; charset=utf-8", ) -> tuple[int, bytes]: req = urllib.request.Request(url, data=data, method=method) if key: req.add_header("X-API-Key", key) if data is not None: - req.add_header("Content-Type", "text/html; charset=utf-8") + req.add_header("Content-Type", content_type) try: with urllib.request.urlopen(req) as resp: return resp.status, resp.read() @@ -136,6 +142,35 @@ def cmd_genkey(args: argparse.Namespace) -> None: print(secrets.token_hex(args.bytes)) +def cmd_folder(args: argparse.Namespace) -> None: + server, key = _server(args), _key(args) + folder = urllib.parse.quote(getattr(args, "folder", ""), safe="") + page = urllib.parse.quote(getattr(args, "page", ""), safe="") + if args.folder_command == "list": + status, body = _request("GET", f"{server}/api/folders", key=key) + result = _print_json_or_fail(status, body) + for item in result["folders"]: + print(f"{item['slug']:<24} {len(item['pages']):>4} pages {item['url']}") + return + if args.folder_command == "create": + status, body = _request( + "POST", + f"{server}/api/folders", + data=json.dumps({"slug": args.folder}).encode(), + key=key, + content_type="application/json", + ) + elif args.folder_command == "delete": + status, body = _request("DELETE", f"{server}/api/folders/{folder}", key=key) + else: + method = "PUT" if args.folder_command == "add" else "DELETE" + status, body = _request( + method, f"{server}/api/folders/{folder}/pages/{page}", key=key + ) + result = _print_json_or_fail(status, body) + print(result.get("url", result.get("deleted", args.page if page else args.folder))) + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="htmlet", description="htmlet CLI") parser.add_argument("--server", help="base URL (or HTMLET_SERVER)") @@ -172,6 +207,16 @@ def build_parser() -> argparse.ArgumentParser: "--bytes", type=int, default=32, help="entropy in bytes (default 32)" ) p_gen.set_defaults(func=cmd_genkey) + + p_folder = sub.add_parser("folder", help="manage shareable page folders") + folder_sub = p_folder.add_subparsers(dest="folder_command", required=True) + for command in ("create", "delete", "add", "remove", "list"): + action = folder_sub.add_parser(command) + if command != "list": + action.add_argument("folder") + if command in {"add", "remove"}: + action.add_argument("page") + action.set_defaults(func=cmd_folder) return parser diff --git a/pyproject.toml b/pyproject.toml index c972d80..e1cfe15 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,9 @@ packages = ["app", "client"] [tool.hatch.build.targets.wheel.force-include] "app/templates/index.html" = "app/templates/index.html" +"app/templates/folder.html" = "app/templates/folder.html" "app/static/favicon.svg" = "app/static/favicon.svg" +"app/static/index.js" = "app/static/index.js" diff --git a/skills/htmlet/SKILL.md b/skills/htmlet/SKILL.md index aed9723..6817eb0 100644 --- a/skills/htmlet/SKILL.md +++ b/skills/htmlet/SKILL.md @@ -90,6 +90,24 @@ curl -fsS -X DELETE -H "X-API-Key: $HTMLET_KEY" "$HTMLET_SERVER/api/files/my-rep # → {"deleted":"my-report"} ``` +## Share a folder + +Create a folder and add existing pages. One page belongs to at most one folder; +adding it elsewhere moves it. Folder and page slugs follow the same rules. + +```bash +curl -fsS -X POST -H "X-API-Key: $HTMLET_KEY" \ + -H 'Content-Type: application/json' -d '{"slug":"project"}' \ + "$HTMLET_SERVER/api/folders" +curl -fsS -X PUT -H "X-API-Key: $HTMLET_KEY" \ + "$HTMLET_SERVER/api/folders/project/pages/my-report" +# Share $HTMLET_SERVER/f/project — visitors can search and open its pages. +``` + +`GET /api/folders` lists folders and their pages (key required). Removing a page +from a folder keeps its public page URL. Deleting a folder keeps all its pages. +Folder links are public, including the list of page names. + ## Errors | Status | Meaning | What to do | diff --git a/tests/test_folders.py b/tests/test_folders.py new file mode 100644 index 0000000..efc98f1 --- /dev/null +++ b/tests/test_folders.py @@ -0,0 +1,107 @@ +"""Folder API and share-link integration tests.""" + +from __future__ import annotations + +import tempfile +import unittest +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import patch + +from fastapi.testclient import TestClient + +from app.config import settings +from app.main import app + + +class FolderTests(unittest.TestCase): + def setUp(self) -> None: + stack = ExitStack() + self.addCleanup(stack.close) + root = stack.enter_context(tempfile.TemporaryDirectory()) + stack.enter_context(patch.object(settings, "data_dir", Path(root).resolve())) + stack.enter_context(patch.object(settings, "api_keys", {"a" * 32})) + self.client = stack.enter_context(TestClient(app)) + self.key = {"X-API-Key": "a" * 32} + + def test_auth_and_validation(self) -> None: + client = self.client + self.assertEqual(client.get("/api/folders").status_code, 401) + self.assertEqual( + client.post("/api/folders", json={"slug": "team"}).status_code, 401 + ) + self.assertEqual( + client.post( + "/api/folders", headers=self.key, json={"slug": "team"} + ).status_code, + 201, + ) + self.assertEqual( + client.post( + "/api/folders", headers=self.key, json={"slug": "team"} + ).status_code, + 409, + ) + self.assertEqual( + client.post( + "/api/folders", headers=self.key, json={"slug": "../bad"} + ).status_code, + 400, + ) + self.assertEqual( + client.put("/api/folders/team/pages/missing", headers=self.key).status_code, + 404, + ) + + def test_lifecycle_and_public_picker(self) -> None: + client = self.client + for folder in ("team", "other"): + self.assertEqual( + client.post( + "/api/folders", headers=self.key, json={"slug": folder} + ).status_code, + 201, + ) + for page in ("report", "notes"): + self.assertEqual( + client.put( + f"/api/files/{page}", headers=self.key, content=b"

    Hi

    " + ).status_code, + 200, + ) + self.assertEqual( + client.put( + f"/api/folders/team/pages/{page}", headers=self.key + ).status_code, + 200, + ) + picker = client.get("/f/team") + self.assertEqual(picker.status_code, 200) + self.assertIn('href="/report"', picker.text) + self.assertIn('href="/notes"', picker.text) + self.assertIn("Find a page", picker.text) + self.assertIn("folderForm", client.get("/").text) + self.assertEqual(client.get("/static/index.js").status_code, 200) + + self.assertEqual( + client.put("/api/folders/other/pages/report", headers=self.key).status_code, + 200, + ) + self.assertNotIn('href="/report"', client.get("/f/team").text) + self.assertIn('href="/report"', client.get("/f/other").text) + self.assertEqual( + client.delete("/api/files/report", headers=self.key).status_code, 200 + ) + self.assertEqual( + client.get("/api/folders", headers=self.key).json()["folders"][0]["pages"], + [], + ) + self.assertEqual( + client.delete("/api/folders/team", headers=self.key).status_code, 200 + ) + self.assertEqual(client.get("/f/team").status_code, 404) + self.assertEqual(client.get("/notes").status_code, 200) + + +if __name__ == "__main__": + unittest.main()