Tools site: Markdown editor, JSON editor, 24-hour pastebin

Single FastAPI container with a registry-driven single-page front end, so
new tools are one module plus one registry entry. Runs as one container behind a reverse proxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
neil 2026-11-01 23:32:22 -08:00
commit 9d910eb147
26 changed files with 2591 additions and 0 deletions

12
app/Dockerfile Normal file
View file

@ -0,0 +1,12 @@
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py ./
COPY tools ./tools
COPY static ./static
RUN useradd --system --uid 10001 tools && mkdir -p /data && chown tools /data
USER tools
ENV DATA_DIR=/data PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
# HOST/PORT come from compose; uvicorn trusts X-Forwarded-* only from loopback (the local proxy/tunnel).
CMD ["sh", "-c", "exec uvicorn main:app --host ${HOST:-127.0.0.1} --port ${PORT:-8090} --proxy-headers --forwarded-allow-ips 127.0.0.1 --no-server-header"]

92
app/main.py Normal file
View file

@ -0,0 +1,92 @@
"""tools.neilbantoc.dev: a small set of browser tools behind one FastAPI app.
Most tools run entirely in the browser (static/js/tools/*.js). A tool that needs a
server side adds a module under tools/ that exposes `router` (an APIRouter) and,
optionally, `startup()`/`shutdown()` coroutines. Every such module is mounted
automatically; see CLAUDE.md for the full recipe.
"""
import contextlib
import importlib
import pkgutil
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
import tools
STATIC = Path(__file__).parent / "static"
TOOL_MODULES = [
importlib.import_module(f"tools.{m.name}")
for m in pkgutil.iter_modules(tools.__path__)
if not m.name.startswith("_")
]
@contextlib.asynccontextmanager
async def lifespan(_app: FastAPI):
for mod in TOOL_MODULES:
if hasattr(mod, "startup"):
await mod.startup()
yield
for mod in TOOL_MODULES:
if hasattr(mod, "shutdown"):
await mod.shutdown()
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
app.add_middleware(GZipMiddleware, minimum_size=1024)
for mod in TOOL_MODULES:
app.include_router(mod.router)
class Assets(StaticFiles):
"""Static files that browsers revalidate on every load (cheap 304s), so a deploy shows up at once."""
async def get_response(self, path, scope):
resp = await super().get_response(path, scope)
resp.headers["Cache-Control"] = "no-cache"
return resp
app.mount("/assets", Assets(directory=STATIC), name="assets")
CSP = (
"default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; "
"script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"
)
@app.middleware("http")
async def security_headers(request: Request, call_next):
resp = await call_next(request)
resp.headers.setdefault("Content-Security-Policy", CSP)
resp.headers.setdefault("X-Content-Type-Options", "nosniff")
resp.headers.setdefault("Referrer-Policy", "same-origin")
return resp
@app.get("/healthz", include_in_schema=False)
def healthz():
return {"ok": True}
@app.get("/favicon.ico", include_in_schema=False)
def favicon():
return FileResponse(STATIC / "favicon.svg", media_type="image/svg+xml")
@app.api_route("/api/{rest:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"], include_in_schema=False)
def api_not_found(rest: str):
return JSONResponse({"detail": "not found"}, status_code=404)
@app.get("/{path:path}", include_in_schema=False)
def spa(path: str):
# Client-side routing: every other path is a page of the single-page app.
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})

2
app/requirements.txt Normal file
View file

@ -0,0 +1,2 @@
fastapi==0.115.*
uvicorn==0.32.*

279
app/static/css/style.css Normal file
View file

@ -0,0 +1,279 @@
/* ---------- tokens ---------- */
:root {
--bg: #f7f7f8;
--surface: #ffffff;
--surface-2: #f0f1f3;
--border: #dfe1e5;
--text: #1c1e21;
--muted: #646a73;
--accent: #3b6ef5;
--accent-text: #ffffff;
--accent-soft: #e6edfe;
--danger: #c93a3a;
--ok: #1f8a4c;
--sel: #dce6ff;
--tok-key: #8a3ab9;
--tok-string: #0b7a3e;
--tok-number: #1b5fd1;
--tok-bool: #b5560b;
--tok-null: #8a8f98;
--code-bg: #f3f4f6;
--shadow: 0 6px 24px rgba(15, 20, 30, 0.12);
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace;
--sans: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
--radius: 8px;
--topbar: 48px;
--sidebar: 216px;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme='light']) {
--bg: #131417;
--surface: #1b1d21;
--surface-2: #24272c;
--border: #33373e;
--text: #e6e7e9;
--muted: #9aa0a9;
--accent: #6b93ff;
--accent-text: #0d1220;
--accent-soft: #232f4d;
--danger: #ff7b7b;
--ok: #5fd08f;
--sel: #2a3a63;
--tok-key: #d39cf5;
--tok-string: #8bd49c;
--tok-number: #82aaff;
--tok-bool: #f4a85e;
--tok-null: #8a8f98;
--code-bg: #24272c;
--shadow: 0 6px 24px rgba(0, 0, 0, 0.45);
color-scheme: dark;
}
}
:root[data-theme='dark'] {
--bg: #131417;
--surface: #1b1d21;
--surface-2: #24272c;
--border: #33373e;
--text: #e6e7e9;
--muted: #9aa0a9;
--accent: #6b93ff;
--accent-text: #0d1220;
--accent-soft: #232f4d;
--danger: #ff7b7b;
--ok: #5fd08f;
--sel: #2a3a63;
--tok-key: #d39cf5;
--tok-string: #8bd49c;
--tok-number: #82aaff;
--tok-bool: #f4a85e;
--tok-null: #8a8f98;
--code-bg: #24272c;
--shadow: 0 6px 24px rgba(0, 0, 0, 0.45);
color-scheme: dark;
}
/* ---------- base ---------- */
*, *::before, *::after { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body { background: var(--bg); color: var(--text); font: 14px/1.5 var(--sans); -webkit-font-smoothing: antialiased; }
a { color: var(--accent); }
button, input, select, textarea { font: inherit; color: inherit; }
[hidden] { display: none !important; }
.mono { font-family: var(--mono); font-size: 13px; }
.muted { color: var(--muted); }
.small { font-size: 12px; }
.strong { font-weight: 600; }
.nowrap { white-space: nowrap; }
.spacer { flex: 1; }
.error-text { color: var(--danger); }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
/* ---------- shell ---------- */
.shell {
display: grid;
grid-template-columns: var(--sidebar) minmax(0, 1fr);
grid-template-rows: var(--topbar) minmax(0, 1fr);
grid-template-areas: 'top top' 'side main';
height: 100vh;
height: 100dvh;
}
.topbar {
grid-area: top;
display: flex;
align-items: center;
gap: 10px;
padding: 0 12px;
background: var(--surface);
border-bottom: 1px solid var(--border);
}
.brand { display: flex; align-items: center; gap: 8px; color: var(--text); text-decoration: none; font-weight: 650; font-size: 15px; }
.brand-mark { display: grid; place-items: center; width: 26px; height: 26px; border-radius: 7px; background: var(--accent); color: var(--accent-text); font-size: 14px; }
.topbar-title { color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
.topbar-title:not(:empty)::before { content: '/'; margin-right: 10px; opacity: 0.5; }
.icon-btn { display: inline-grid; place-items: center; width: 34px; height: 34px; border: 1px solid transparent; border-radius: var(--radius); background: transparent; cursor: pointer; font-size: 16px; }
.icon-btn:hover { background: var(--surface-2); }
.menu-btn { display: none; }
.sidebar { grid-area: side; overflow-y: auto; padding: 12px 10px; background: var(--surface); border-right: 1px solid var(--border); }
.nav-filter { width: 100%; padding: 7px 10px; margin-bottom: 10px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--bg); }
.nav-group { margin-top: 14px; }
.nav-heading { padding: 0 8px 4px; font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); }
.nav-item { display: flex; align-items: center; gap: 10px; padding: 6px 8px; border-radius: 6px; color: var(--text); text-decoration: none; }
.nav-item:hover { background: var(--surface-2); }
.nav-item.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
.nav-icon { display: inline-grid; place-items: center; min-width: 26px; height: 22px; border-radius: 5px; background: var(--surface-2); font: 600 11px var(--mono); color: var(--muted); }
.nav-item.active .nav-icon { background: var(--accent); color: var(--accent-text); }
.scrim { display: none; }
.view { grid-area: main; min-width: 0; min-height: 0; overflow: auto; }
.loading, .empty { padding: 48px 24px; text-align: center; color: var(--muted); }
.empty .btn { margin-top: 8px; }
/* ---------- home ---------- */
.home { max-width: 960px; margin: 0 auto; padding: 32px 24px 48px; }
.home h1 { margin: 0 0 4px; font-size: 26px; }
.home-filter { width: 100%; max-width: 380px; margin: 18px 0 20px; padding: 9px 12px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); }
.card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; }
.tool-card { display: flex; gap: 14px; padding: 16px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); color: var(--text); text-decoration: none; transition: border-color 0.12s, transform 0.12s; }
.tool-card:hover { border-color: var(--accent); transform: translateY(-1px); }
.tool-card-icon { flex: none; display: grid; place-items: center; width: 42px; height: 42px; border-radius: 9px; background: var(--accent-soft); color: var(--accent); font: 700 14px var(--mono); }
.tool-card-name { font-weight: 600; margin-bottom: 2px; }
.tool-card-desc { color: var(--muted); font-size: 13px; }
/* ---------- shared tool chrome ---------- */
.tool { display: flex; flex-direction: column; height: 100%; min-height: 0; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 8px 12px; background: var(--surface); border-bottom: 1px solid var(--border); }
.divider { width: 1px; height: 22px; margin: 0 4px; background: var(--border); }
.btn {
display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 11px;
border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--text);
cursor: pointer; text-decoration: none; font-size: 13px; white-space: nowrap;
}
.btn:hover { background: var(--surface-2); }
.btn:disabled { opacity: 0.6; cursor: default; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); font-weight: 600; }
.btn.primary:hover { filter: brightness(1.07); }
.btn.danger { color: var(--danger); }
.btn.small { height: 26px; padding: 0 8px; font-size: 12px; }
.select { height: 30px; padding: 0 6px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); font-size: 13px; }
.segmented { display: inline-flex; padding: 2px; border-radius: 7px; background: var(--surface-2); }
.segmented button { height: 26px; padding: 0 12px; border: 0; border-radius: 5px; background: transparent; color: var(--muted); cursor: pointer; font-size: 13px; }
.segmented button[aria-checked='true'] { background: var(--surface); color: var(--text); font-weight: 600; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12); }
.pane { min-width: 0; min-height: 0; overflow: auto; background: var(--surface); }
.statusbar { display: flex; align-items: center; gap: 4px; padding: 5px 12px; border-top: 1px solid var(--border); background: var(--surface); font-size: 12px; min-height: 28px; }
.statusbar.ok { color: var(--ok); }
.statusbar.error { color: var(--danger); }
.linklike { padding: 0; border: 0; background: none; color: inherit; font-weight: 600; text-decoration: underline; cursor: pointer; }
textarea { tab-size: 4; }
.toasts { position: fixed; right: 16px; bottom: 16px; z-index: 50; display: flex; flex-direction: column; gap: 8px; align-items: flex-end; pointer-events: none; }
.toast { max-width: min(420px, calc(100vw - 32px)); padding: 9px 14px; border-radius: var(--radius); background: var(--text); color: var(--bg); box-shadow: var(--shadow); font-size: 13px; animation: toast-in 0.15s ease-out; transition: opacity 0.3s, transform 0.3s; }
.toast.error { background: var(--danger); color: #fff; }
.toast.out { opacity: 0; transform: translateY(6px); }
@keyframes toast-in { from { opacity: 0; transform: translateY(6px); } }
/* ---------- split workspaces (markdown + json) ---------- */
.md-workspace, .json-workspace { flex: 1; min-height: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: var(--border); }
.md-workspace[data-mode='edit'], .md-workspace[data-mode='preview'],
.json-workspace[data-mode='text'], .json-workspace[data-mode='tree'] { grid-template-columns: 1fr; }
.md-workspace[data-mode='edit'] .md-preview-pane,
.md-workspace[data-mode='preview'] .md-edit-pane,
.json-workspace[data-mode='text'] .json-tree-pane,
.json-workspace[data-mode='tree'] .json-text-pane { display: none; }
/* markdown */
.md-edit-pane { display: flex; overflow: hidden; }
.md-input { flex: 1; width: 100%; padding: 16px 18px; border: 0; outline: none; resize: none; background: var(--surface); line-height: 1.6; }
.md-workspace[data-mode='edit'] .md-input { max-width: 900px; margin: 0 auto; }
.md-preview { padding: 16px 24px 48px; }
.md-workspace[data-mode='preview'] .md-preview { max-width: 820px; margin: 0 auto; padding: 32px 32px 80px; }
.prose { font-size: 15px; line-height: 1.65; overflow-wrap: break-word; }
.prose > :first-child { margin-top: 0; }
.prose h1, .prose h2, .prose h3, .prose h4 { margin: 1.4em 0 0.5em; line-height: 1.25; }
.prose h1 { font-size: 1.9em; padding-bottom: 0.25em; border-bottom: 1px solid var(--border); }
.prose h2 { font-size: 1.45em; padding-bottom: 0.2em; border-bottom: 1px solid var(--border); }
.prose h3 { font-size: 1.2em; }
.prose p, .prose ul, .prose ol, .prose blockquote, .prose pre, .prose table { margin: 0 0 1em; }
.prose ul, .prose ol { padding-left: 1.6em; }
.prose li + li { margin-top: 0.25em; }
.prose li > input[type='checkbox'] { margin: 0 0.4em 0 -1.3em; vertical-align: middle; }
.prose li:has(> input[type='checkbox']) { list-style: none; }
.prose code { padding: 0.15em 0.35em; border-radius: 4px; background: var(--code-bg); font: 0.88em var(--mono); }
.prose pre { padding: 12px 14px; border-radius: var(--radius); background: var(--code-bg); overflow: auto; }
.prose pre code { padding: 0; background: none; font-size: 13px; }
.prose blockquote { padding: 0 1em; border-left: 3px solid var(--border); color: var(--muted); }
.prose table { border-collapse: collapse; display: block; overflow-x: auto; }
.prose th, .prose td { padding: 6px 12px; border: 1px solid var(--border); }
.prose th { background: var(--surface-2); }
.prose img { max-width: 100%; }
.prose hr { border: 0; border-top: 1px solid var(--border); margin: 2em 0; }
/* json: text pane */
.json-text-pane { overflow: hidden; display: flex; }
.editor-wrap { flex: 1; display: flex; min-width: 0; }
.gutter { position: relative; flex: none; min-width: 44px; padding: 10px 8px 60px 6px; overflow: hidden; background: var(--surface-2); color: var(--muted); text-align: right; line-height: 20px; user-select: none; }
.gutter-nums { white-space: pre; }
.gutter-error { position: absolute; left: 0; right: 0; height: 20px; margin-top: 10px; background: color-mix(in srgb, var(--danger) 25%, transparent); border-left: 3px solid var(--danger); }
.json-input { flex: 1; min-width: 0; padding: 10px 12px; border: 0; outline: none; resize: none; background: var(--surface); line-height: 20px; white-space: pre; overflow: auto; }
/* json: tree pane */
.json-tree-pane { display: flex; flex-direction: column; overflow: hidden; }
.tree-bar { display: flex; align-items: center; gap: 6px; padding: 6px 10px; border-bottom: 1px solid var(--border); }
.path-chip { max-width: 55%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 2px 8px; border: 1px solid var(--border); border-radius: 5px; background: var(--surface-2); cursor: pointer; font-size: 12px; }
.json-tree { flex: 1; overflow: auto; padding: 6px 0 40px; line-height: 22px; }
.json-tree.stale { opacity: 0.45; }
.tree-row { position: relative; display: flex; align-items: center; padding-left: calc(var(--depth) * 18px + 6px); padding-right: 64px; white-space: nowrap; cursor: default; }
.tree-row:hover { background: var(--surface-2); }
.tree-row.selected { background: var(--sel); }
.tree-row.closing { cursor: default; }
.tree-row.closing:hover { background: none; }
.twisty, .twisty-space { flex: none; width: 18px; }
.twisty { height: 18px; padding: 0; border: 0; background: none; color: var(--muted); cursor: pointer; font-size: 11px; }
.t-key { color: var(--tok-key); }
.t-index { color: var(--muted); }
.t-punct, .t-count { color: var(--muted); white-space: pre; }
.t-count { font-style: italic; font-size: 12px; }
.t-val { overflow: hidden; text-overflow: ellipsis; }
.t-string { color: var(--tok-string); }
.t-number { color: var(--tok-number); }
.t-boolean { color: var(--tok-bool); }
.t-null { color: var(--tok-null); }
.t-key, .t-val { cursor: text; border-radius: 3px; }
.t-key:hover, .t-val:hover { outline: 1px dashed var(--border); }
.row-actions { position: absolute; right: 8px; display: none; gap: 2px; }
.tree-row:hover > .row-actions, .tree-row.selected > .row-actions { display: flex; }
.mini { width: 22px; height: 20px; padding: 0; border: 1px solid var(--border); border-radius: 4px; background: var(--surface); color: var(--muted); cursor: pointer; line-height: 1; }
.mini:hover { color: var(--text); }
.inline-edit { height: 22px; padding: 0 4px; border: 1px solid var(--accent); border-radius: 3px; background: var(--surface); outline: none; }
.more { margin: 4px 0 4px calc(var(--depth) * 18px + 24px); }
/* ---------- paste ---------- */
.paste-body { flex: 1; min-height: 0; overflow: auto; padding: 16px; display: flex; flex-direction: column; gap: 8px; }
.paste-input { flex: 1 0 280px; width: 100%; padding: 12px 14px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); resize: vertical; line-height: 1.5; outline: none; }
.paste-input:focus { border-color: var(--accent); }
.section-title { margin: 16px 0 6px; font-size: 13px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); }
.paste-item { display: flex; align-items: center; gap: 12px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); margin-bottom: 6px; }
.paste-preview { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.paste-view { flex: 1; min-height: 0; display: flex; overflow: auto; background: var(--surface); line-height: 20px; }
.paste-lines { flex: none; padding: 12px 10px 40px; background: var(--surface-2); color: var(--muted); text-align: right; white-space: pre; user-select: none; position: sticky; left: 0; }
.paste-text { flex: 1; margin: 0; padding: 12px 14px 40px; font: inherit; white-space: pre; }
.paste-view.wrap .paste-text { white-space: pre-wrap; overflow-wrap: anywhere; }
.paste-view.wrap .paste-lines { display: none; }
/* ---------- narrow screens ---------- */
@media (max-width: 800px) {
.shell { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'top' 'main'; }
.menu-btn { display: inline-block; }
.sidebar { position: fixed; z-index: 30; top: var(--topbar); bottom: 0; left: 0; width: min(280px, 85vw); transform: translateX(-100%); transition: transform 0.18s ease-out; box-shadow: var(--shadow); }
.drawer-open .sidebar { transform: none; }
.drawer-open .scrim { display: block; position: fixed; inset: var(--topbar) 0 0 0; z-index: 20; background: rgba(0, 0, 0, 0.35); }
/* one row that scrolls sideways, so the editor keeps the screen */
.toolbar { padding: 8px; flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; }
.toolbar > * { flex: none; }
.toolbar > .spacer { flex: 1 0 8px; }
.home { padding: 20px 16px 40px; }
.md-workspace[data-mode='split'], .json-workspace[data-mode='split'] { grid-template-columns: 1fr; grid-template-rows: 1fr 1fr; }
.md-workspace[data-mode='preview'] .md-preview { padding: 20px 16px 60px; }
}

1
app/static/favicon.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#3b6ef5"/><path d="M10 11l-4 5 4 5M22 11l4 5-4 5M18 9l-4 14" stroke="#fff" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>

After

Width:  |  Height:  |  Size: 263 B

30
app/static/index.html Normal file
View file

@ -0,0 +1,30 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Tools</title>
<link rel="icon" href="/assets/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/assets/css/style.css">
<script type="module" src="/assets/js/app.js"></script>
</head>
<body>
<div class="shell">
<header class="topbar">
<button class="icon-btn menu-btn" id="menu-btn" aria-label="Menu" aria-expanded="false">☰</button>
<a href="/" class="brand"><span class="brand-mark">⌘</span> tools</a>
<span class="topbar-title" id="topbar-title"></span>
<span class="spacer"></span>
<button class="icon-btn" id="theme-btn" aria-label="Theme" title="Theme: auto"></button>
</header>
<nav class="sidebar" id="sidebar" aria-label="Tools">
<input type="search" id="nav-filter" class="nav-filter" placeholder="Find a tool… /" aria-label="Find a tool">
<div id="nav-list"></div>
</nav>
<div class="scrim" id="scrim"></div>
<main id="view" class="view"></main>
</div>
<div class="toasts" id="toasts" aria-live="polite"></div>
</body>
</html>

210
app/static/js/app.js Normal file
View file

@ -0,0 +1,210 @@
// App shell: navigation, routing, theme. Tools themselves live in js/tools/*.js.
//
// A tool module exports mount(el, ctx) and may return a cleanup function.
// ctx = {
// rest, // path after the tool's own path, e.g. "abc123" for /paste/abc123
// query, // URLSearchParams of the current URL
// navigate, // navigate('/paste/abc') — client-side navigation
// setTitle, // setTitle('abc123') — extra text in the top bar and tab title
// }
import { TOOLS, CATEGORY_ORDER } from './registry.js';
import { el, store } from './ui.js';
const view = document.getElementById('view');
const navList = document.getElementById('nav-list');
const navFilter = document.getElementById('nav-filter');
const titleEl = document.getElementById('topbar-title');
let cleanup = null;
let routeSeq = 0;
// ---------- theme ----------
const THEMES = ['auto', 'light', 'dark'];
const svg = (d) => `<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${d}</svg>`;
const THEME_ICON = {
auto: svg('<circle cx="12" cy="12" r="9"/><path d="M12 3v18" /><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/>'),
light: svg('<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>'),
dark: svg('<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>'),
};
const themeBtn = document.getElementById('theme-btn');
function applyTheme(t) {
if (t === 'auto') delete document.documentElement.dataset.theme;
else document.documentElement.dataset.theme = t;
themeBtn.innerHTML = THEME_ICON[t];
themeBtn.title = `Theme: ${t}`;
}
let theme = store.get('theme', 'auto');
applyTheme(theme);
themeBtn.addEventListener('click', () => {
theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
store.set('theme', theme);
applyTheme(theme);
});
// ---------- navigation ----------
function grouped(tools) {
const groups = new Map();
for (const t of tools) {
if (!groups.has(t.category)) groups.set(t.category, []);
groups.get(t.category).push(t);
}
const rank = (c) => (CATEGORY_ORDER.includes(c) ? CATEGORY_ORDER.indexOf(c) : 999);
return [...groups].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b));
}
function matches(t, q) {
q = q.trim().toLowerCase();
return !q || `${t.name} ${t.description} ${t.category}`.toLowerCase().includes(q);
}
function renderNav() {
const q = navFilter.value;
navList.replaceChildren(
el('a.nav-item.nav-home', { href: '/', dataset: { path: '/' } }, el('span.nav-icon', {}, '⌂'), 'All tools'),
...grouped(TOOLS.filter((t) => matches(t, q))).map(([cat, tools]) =>
el('div.nav-group', {},
el('div.nav-heading', {}, cat),
tools.map((t) => el('a.nav-item', { href: t.path, dataset: { path: t.path } }, el('span.nav-icon', {}, t.icon), t.name)),
),
),
);
markActive();
}
function markActive() {
const tool = findTool(location.pathname);
for (const a of navList.querySelectorAll('.nav-item')) {
const on = tool ? a.dataset.path === tool.path : a.dataset.path === '/';
a.classList.toggle('active', on);
if (on) a.setAttribute('aria-current', 'page');
else a.removeAttribute('aria-current');
}
}
navFilter.addEventListener('input', renderNav);
navFilter.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const first = TOOLS.find((t) => matches(t, navFilter.value));
if (first) {
navFilter.value = '';
renderNav();
navigate(first.path);
}
} else if (e.key === 'Escape') {
navFilter.value = '';
renderNav();
navFilter.blur();
}
});
document.addEventListener('keydown', (e) => {
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName) || document.activeElement?.isContentEditable;
if (e.key === '/' && !typing) {
e.preventDefault();
setDrawer(true);
navFilter.focus();
}
});
// Mobile drawer
const menuBtn = document.getElementById('menu-btn');
function setDrawer(open) {
document.body.classList.toggle('drawer-open', open);
menuBtn.setAttribute('aria-expanded', String(open));
}
menuBtn.addEventListener('click', () => setDrawer(!document.body.classList.contains('drawer-open')));
document.getElementById('scrim').addEventListener('click', () => setDrawer(false));
// ---------- routing ----------
function findTool(pathname) {
return TOOLS.find((t) => pathname === t.path || pathname.startsWith(`${t.path}/`));
}
export function navigate(path, { replace = false } = {}) {
if (path === location.pathname + location.search) return;
history[replace ? 'replaceState' : 'pushState']({}, '', path);
route();
}
document.addEventListener('click', (e) => {
const a = e.target.closest('a[href]');
if (!a || a.target || a.hasAttribute('download') || e.defaultPrevented) return;
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const url = new URL(a.href, location.href);
if (url.origin !== location.origin || url.pathname.startsWith('/raw/') || url.pathname.startsWith('/api/')) return;
e.preventDefault();
setDrawer(false);
navigate(url.pathname + url.search);
});
window.addEventListener('popstate', route);
function setTitle(tool, extra) {
titleEl.textContent = tool ? [tool.name, extra].filter(Boolean).join(' · ') : '';
document.title = tool ? `${[extra, tool.name].filter(Boolean).join(' · ')} — tools` : 'tools';
}
async function route() {
const seq = ++routeSeq;
if (cleanup) {
try { cleanup(); } catch (err) { console.error(err); }
cleanup = null;
}
markActive();
const tool = findTool(location.pathname);
document.body.dataset.tool = tool ? tool.id : 'home';
if (!tool) {
if (location.pathname !== '/') history.replaceState({}, '', '/');
setTitle(null);
renderHome();
return;
}
setTitle(tool);
view.replaceChildren(el('div.loading', {}, 'Loading…'));
try {
const mod = await tool.load();
if (seq !== routeSeq) return; // navigated away while loading
view.replaceChildren();
const ctx = {
rest: location.pathname.slice(tool.path.length).replace(/^\//, ''),
query: new URLSearchParams(location.search),
navigate,
setTitle: (extra) => setTitle(tool, extra),
};
cleanup = (await mod.mount(view, ctx)) || null;
} catch (err) {
console.error(err);
if (seq === routeSeq) view.replaceChildren(el('div.empty', {}, `Couldn't load ${tool.name}: ${err.message}`));
}
}
function renderHome() {
const filter = el('input.home-filter', { type: 'search', placeholder: 'Find a tool…', 'aria-label': 'Find a tool' });
const grid = el('div.card-grid');
const draw = () =>
grid.replaceChildren(
...TOOLS.filter((t) => matches(t, filter.value)).map((t) =>
el('a.tool-card', { href: t.path },
el('div.tool-card-icon', {}, t.icon),
el('div', {}, el('div.tool-card-name', {}, t.name), el('div.tool-card-desc', {}, t.description)),
),
),
);
filter.addEventListener('input', draw);
filter.addEventListener('keydown', (e) => {
const first = e.key === 'Enter' && grid.querySelector('a');
if (first) navigate(new URL(first.href).pathname);
});
draw();
view.replaceChildren(
el('div.home', {},
el('h1', {}, 'Tools'),
el('p.muted', {}, 'Small utilities that run in your browser. Only pastes are stored on the server, and only for 24 hours.'),
filter,
grid,
),
);
}
renderNav();
route();

37
app/static/js/registry.js Normal file
View file

@ -0,0 +1,37 @@
// The list of tools. The sidebar, the home page and the router are all built from it.
//
// To add a tool: create js/tools/<id>.js exporting mount(el, ctx) (see app.js for ctx),
// then add an entry here. A tool owns every path under its `path`, so /paste/abc123
// goes to the paste tool with ctx.rest = "abc123".
export const TOOLS = [
{
id: 'markdown',
name: 'Markdown',
path: '/markdown',
category: 'Text',
icon: 'M↓',
description: 'Write Markdown with a live preview: side by side, editor only or full-page preview.',
load: () => import('./tools/markdown.js'),
},
{
id: 'json',
name: 'JSON editor',
path: '/json',
category: 'Data',
icon: '{ }',
description: 'Validate, prettify and compact JSON, with a live tree view you can edit.',
load: () => import('./tools/json.js'),
},
{
id: 'paste',
name: 'Pastebin',
path: '/paste',
category: 'Sharing',
icon: '⎘',
description: 'Share text with a short link. Pastes are deleted after 24 hours.',
load: () => import('./tools/paste.js'),
},
];
// Sidebar groups appear in this order; unknown categories go last, alphabetically.
export const CATEGORY_ORDER = ['Text', 'Data', 'Sharing'];

View file

@ -0,0 +1,234 @@
// JSON parser and printer that work on source tokens rather than JS values, so
// formatting never changes the data: numbers keep their exact digits (no precision
// loss on big integers), strings keep their original escapes, duplicate keys survive.
//
// Node shapes (start/end are offsets into the source text):
// {type:'object', entries:[{key, keyRaw, keyStart, keyEnd, value}], start, end}
// {type:'array', items:[node], start, end}
// {type:'string', value, raw, start, end}
// {type:'number', raw, start, end}
// {type:'boolean', value, start, end} / {type:'null', start, end}
export class JsonSyntaxError extends Error {
constructor(message, pos, text) {
const { line, col } = lineCol(text, pos);
super(message);
this.pos = pos;
this.line = line;
this.col = col;
}
}
export function lineCol(text, pos) {
let line = 1;
let last = -1;
for (let i = text.indexOf('\n'); i !== -1 && i < pos; i = text.indexOf('\n', i + 1)) {
line++;
last = i;
}
return { line, col: pos - last };
}
const STRING_RE = /"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/y;
const NUMBER_RE = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
export function parse(text) {
let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;
const fail = (msg, at = i) => {
throw new JsonSyntaxError(msg, at, text);
};
const describe = (at) => {
if (at >= text.length) return 'end of input';
const ch = text[at];
return ch === '\n' ? 'line break' : `'${ch}'`;
};
function ws() {
for (;;) {
const c = text.charCodeAt(i);
if (c === 32 || c === 10 || c === 13 || c === 9) i++;
else if (c === 47 && (text[i + 1] === '/' || text[i + 1] === '*')) fail("Comments aren't allowed in JSON");
else return;
}
}
function string() {
STRING_RE.lastIndex = i;
const m = STRING_RE.exec(text);
if (!m) {
// Find the exact problem for a useful message.
for (let j = i + 1; j < text.length; j++) {
const c = text.charCodeAt(j);
if (c === 34) break;
if (c === 10) fail('Unterminated string (strings cannot span lines; use \\n)', j);
if (c < 32) fail('Control character in string; escape it', j);
if (c === 92) {
const e = text[j + 1];
if (e === 'u') {
if (!/^[0-9a-fA-F]{4}$/.test(text.slice(j + 2, j + 6))) fail('Invalid \\u escape: needs four hex digits', j);
j += 5;
} else if ('"\\/bfnrt'.includes(e) && e !== undefined) j++;
else fail(`Invalid escape '\\${e ?? ''}'`, j);
}
}
fail('Unterminated string');
}
const start = i;
i += m[0].length;
return { type: 'string', raw: m[0], value: JSON.parse(m[0]), start, end: i };
}
function value(depth) {
if (depth > 2000) fail('Nested too deeply (more than 2000 levels)');
ws();
const start = i;
const c = text[i];
if (c === '{') {
i++;
const entries = [];
ws();
if (text[i] === '}') return { type: 'object', entries, start, end: ++i };
for (;;) {
ws();
if (text[i] !== '"') {
if (text[i] === '}' && entries.length) fail('Trailing comma before }', i);
if (text[i] === "'") fail('Strings must use double quotes');
fail(i >= text.length ? 'Unexpected end of input: object is not closed' : `Expected a "quoted" key, found ${describe(i)}`);
}
const k = string();
ws();
if (text[i] !== ':') fail(`Expected ':' after key, found ${describe(i)}`);
i++;
const v = value(depth + 1);
entries.push({ key: k.value, keyRaw: k.raw, keyStart: k.start, keyEnd: k.end, value: v });
ws();
if (text[i] === ',') { i++; continue; }
if (text[i] === '}') return { type: 'object', entries, start, end: ++i };
fail(i >= text.length ? 'Unexpected end of input: object is not closed' : `Expected ',' or '}', found ${describe(i)}`);
}
}
if (c === '[') {
i++;
const items = [];
ws();
if (text[i] === ']') return { type: 'array', items, start, end: ++i };
for (;;) {
ws();
if (text[i] === ']' && items.length) fail('Trailing comma before ]', i);
items.push(value(depth + 1));
ws();
if (text[i] === ',') { i++; continue; }
if (text[i] === ']') return { type: 'array', items, start, end: ++i };
fail(i >= text.length ? 'Unexpected end of input: array is not closed' : `Expected ',' or ']', found ${describe(i)}`);
}
}
if (c === '"') return string();
if (c === "'") fail('Strings must use double quotes');
if (c === '-' || (c >= '0' && c <= '9')) {
NUMBER_RE.lastIndex = i;
const m = NUMBER_RE.exec(text);
if (!m) fail('Invalid number');
i += m[0].length;
if (/[0-9.eE]/.test(text[i] || '')) fail('Invalid number (leading zeros and trailing dots are not allowed)', start);
return { type: 'number', raw: m[0], start, end: i };
}
for (const [word, node] of [['true', { type: 'boolean', value: true }], ['false', { type: 'boolean', value: false }], ['null', { type: 'null' }]]) {
if (text.startsWith(word, i)) {
i += word.length;
return { ...node, start, end: i };
}
}
if (i >= text.length) fail('Unexpected end of input: expected a value');
const word = /^[A-Za-z_$][\w$]*/.exec(text.slice(i, i + 40));
if (word) fail(`Unexpected '${word[0]}': ${['undefined', 'NaN', 'Infinity', 'True', 'False', 'None'].includes(word[0]) ? "not valid in JSON" : 'strings must be "quoted"'}`);
fail(`Unexpected ${describe(i)}`);
}
ws();
if (i >= text.length) fail('Empty document');
let root;
try {
root = value(0);
} catch (err) {
if (err instanceof RangeError) throw new JsonSyntaxError('Nested too deeply', i, text);
throw err;
}
ws();
if (i < text.length) fail(`Unexpected ${describe(i)} after the end of the JSON value`);
return root;
}
/** Prints a node. indent '' = compact (no whitespace at all), else e.g. ' ', ' ', '\t'. */
export function stringify(node, indent = ' ') {
const out = [];
const sep = indent ? ': ' : ':';
function walk(n, pad) {
switch (n.type) {
case 'object': {
if (!n.entries.length) return out.push('{}');
const inner = pad + indent;
out.push('{');
n.entries.forEach((e, idx) => {
if (idx) out.push(',');
if (indent) out.push('\n', inner);
out.push(e.keyRaw, sep);
walk(e.value, inner);
});
if (indent) out.push('\n', pad);
return out.push('}');
}
case 'array': {
if (!n.items.length) return out.push('[]');
const inner = pad + indent;
out.push('[');
n.items.forEach((item, idx) => {
if (idx) out.push(',');
if (indent) out.push('\n', inner);
walk(item, inner);
});
if (indent) out.push('\n', pad);
return out.push(']');
}
case 'string':
case 'number':
return out.push(n.raw);
case 'boolean':
return out.push(String(n.value));
case 'null':
return out.push('null');
}
}
walk(node, '');
return out.join('');
}
/** A copy with object keys sorted (by code point), recursively. */
export function sortKeys(node) {
if (node.type === 'object') {
const entries = node.entries
.map((e) => ({ ...e, value: sortKeys(e.value) }))
.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
return { ...node, entries };
}
if (node.type === 'array') return { ...node, items: node.items.map(sortKeys) };
return node;
}
/** Turns text typed into the tree editor into a node: valid JSON as-is, anything else as a string. */
export function nodeFromInput(text) {
try {
return parse(text);
} catch {
return stringNode(text);
}
}
export function stringNode(value) {
return { type: 'string', value, raw: JSON.stringify(value) };
}
/** JavaScript-style path for display, e.g. $.users[0]["first name"] */
export function pathToString(path) {
return '$' + path.map((p) => (typeof p === 'number' ? `[${p}]` : /^[A-Za-z_$][\w$]*$/.test(p) ? `.${p}` : `[${JSON.stringify(p)}]`)).join('');
}

460
app/static/js/tools/json.js Normal file
View file

@ -0,0 +1,460 @@
// JSON editor: a text pane and a live tree pane that stay in sync.
// Text edits re-render the tree as you type; tree edits rewrite the text (undoable).
import { parse, stringify, sortKeys, nodeFromInput, stringNode, pathToString, JsonSyntaxError } from './json-core.js';
import { el, segmented, store, copyText, downloadText, openTextFile, debounce, formatBytes, tabIndent, toast, onLeave } from '../ui.js';
const SAMPLE = `{
"name": "tools",
"version": 1,
"bigNumber": 12345678901234567890,
"tags": ["markdown", "json", "paste"],
"nested": { "ok": true, "nothing": null, "items": [{ "id": 1 }, { "id": 2 }] }
}
`;
const INDENTS = { '2': ' ', '4': ' ', tab: '\t' };
const PAGE = 200; // children shown per expanded node before "show more"
const TREE_LIVE_LIMIT = 5_000_000; // bytes; above this the tree updates on pause, not per keystroke
export async function mount(root, ctx) {
let mode = store.get('json:mode', window.innerWidth < 800 ? 'text' : 'split');
let indentKey = store.get('json:indent', '2');
let ast = null;
let error = null;
let selectedPath = null;
// Open/closed overrides by path key; without one, the root and its children start open.
let opened = new Set();
let closed = new Set();
const shown = new Map(); // path key -> how many children are visible
// ---------- layout ----------
const editor = el('textarea.json-input.mono', { spellcheck: false, wrap: 'off', 'aria-label': 'JSON text', placeholder: 'Paste or type JSON…' });
tabIndent(editor);
const gutter = el('div.gutter.mono', { 'aria-hidden': 'true' });
const gutterNums = el('div.gutter-nums');
const errorMark = el('div.gutter-error');
gutter.append(gutterNums, errorMark);
const tree = el('div.json-tree.mono', { role: 'tree', 'aria-label': 'JSON tree' });
const status = el('div.statusbar');
const modes = segmented([['text', 'Text'], ['split', 'Split'], ['tree', 'Tree']], mode, setMode, 'View mode');
const indentSel = el('select.select', { title: 'Indentation for Format', 'aria-label': 'Indentation', onchange: () => {
indentKey = indentSel.value;
store.set('json:indent', indentKey);
} },
el('option', { value: '2' }, '2 spaces'), el('option', { value: '4' }, '4 spaces'), el('option', { value: 'tab' }, 'Tabs'));
indentSel.value = indentKey;
const toolbar = el('div.toolbar', {},
modes,
el('span.divider'),
el('button.btn.primary', { onclick: format, title: 'Prettify (Ctrl+Shift+F)' }, 'Format'),
indentSel,
el('button.btn', { onclick: compact, title: 'Remove all whitespace outside keys and values (Ctrl+Shift+M)' }, 'Compact'),
el('button.btn', { onclick: sort, title: 'Sort object keys A→Z, recursively' }, 'Sort keys'),
el('span.spacer'),
el('button.btn', { onclick: openFile }, 'Open'),
el('button.btn', { onclick: () => downloadText(editor.value, 'data.json', 'application/json') }, 'Download'),
el('button.btn', { onclick: () => copyText(editor.value) }, 'Copy'),
el('button.btn', { onclick: () => replaceText(''), title: 'Clear (undo with Ctrl+Z)' }, 'Clear'),
);
const treeBar = el('div.tree-bar', {},
el('button.btn.small', { onclick: () => expandAll(true) }, 'Expand all'),
el('button.btn.small', { onclick: () => expandAll(false) }, 'Collapse all'),
el('span.spacer'),
);
const pathBox = el('button.path-chip.mono', { title: 'Copy path', hidden: true, onclick: () => copyText(pathBox.textContent, 'Path copied') });
treeBar.append(pathBox);
const workspace = el('div.json-workspace', {},
el('div.pane.json-text-pane', {}, el('div.editor-wrap', {}, gutter, editor)),
el('div.pane.json-tree-pane', {}, treeBar, tree),
);
root.append(el('div.tool.json-tool', {}, toolbar, workspace, status));
// ---------- text pane ----------
let lineCount = 0;
function updateGutter() {
let n = 1;
for (let i = editor.value.indexOf('\n'); i !== -1; i = editor.value.indexOf('\n', i + 1)) n++;
if (n !== lineCount) {
lineCount = n;
gutterNums.textContent = Array.from({ length: n }, (_, k) => k + 1).join('\n');
}
syncGutter();
}
function syncGutter() {
gutter.scrollTop = editor.scrollTop;
}
editor.addEventListener('scroll', syncGutter);
// When the text shrinks the browser clamps the editor's scroll without always firing
// 'scroll', so re-sync after layout too.
editor.addEventListener('input', () => requestAnimationFrame(syncGutter));
/** Replaces the whole text in a way the browser's undo (Ctrl+Z) can reverse. */
function replaceText(text) {
editor.focus({ preventScroll: true });
editor.select();
// execCommand types into whatever has focus; when the text pane is hidden (Tree
// mode) the editor can't take focus, so set the value directly (not undoable).
if (document.activeElement !== editor || !document.execCommand('insertText', false, text)) {
editor.value = text;
editor.dispatchEvent(new Event('input'));
}
editor.setSelectionRange(0, 0);
editor.scrollTop = 0;
}
function lineHeight() {
return parseFloat(getComputedStyle(editor).lineHeight) || 20;
}
function selectRange(start, end) {
if (mode === 'tree') return;
const before = editor.value.slice(0, start);
const line = before.split('\n').length;
editor.focus({ preventScroll: true });
editor.setSelectionRange(start, end);
editor.scrollTop = Math.max(0, (line - 1) * lineHeight() - editor.clientHeight / 3);
}
// ---------- parsing & status ----------
function reparse() {
const text = editor.value;
try {
ast = text.trim() ? parse(text) : null;
error = null;
} catch (err) {
if (!(err instanceof JsonSyntaxError)) throw err;
error = err;
// Keep showing the last good tree (dimmed) so it doesn't flicker while typing.
}
renderStatus();
renderTree();
updateGutter();
}
function renderStatus() {
const size = formatBytes(new Blob([editor.value]).size);
errorMark.hidden = !error;
if (error) {
errorMark.style.top = `${(error.line - 1) * lineHeight()}px`;
status.className = 'statusbar error';
status.replaceChildren(
el('button.linklike', { onclick: () => selectRange(error.pos, Math.min(error.pos + 1, editor.value.length)), title: 'Go to the error' },
`Line ${error.line}, column ${error.col}`),
`: ${error.message}`,
el('span.spacer'),
el('span.muted', {}, size),
);
} else if (!ast) {
status.className = 'statusbar';
status.replaceChildren(el('span.muted', {}, 'Empty'));
} else {
status.className = 'statusbar ok';
status.replaceChildren('✓ Valid JSON', el('span.muted', {}, ` · ${summary(ast)}`), el('span.spacer'), el('span.muted', {}, size));
}
}
function summary(n) {
if (n.type === 'object') return `object, ${n.entries.length} key${n.entries.length === 1 ? '' : 's'}`;
if (n.type === 'array') return `array, ${n.items.length} item${n.items.length === 1 ? '' : 's'}`;
return n.type;
}
// ---------- toolbar actions ----------
function current() {
if (error) {
toast(`Fix the error first: line ${error.line}, column ${error.col}`, 'error');
selectRange(error.pos, error.pos + 1);
return null;
}
return ast;
}
function format() {
const a = current();
if (a) replaceText(stringify(a, INDENTS[indentKey]) + '\n');
}
function compact() {
const a = current();
if (a) replaceText(stringify(a, ''));
}
function sort() {
const a = current();
if (a) replaceText(stringify(sortKeys(a), INDENTS[indentKey]) + '\n');
}
async function openFile() {
const f = await openTextFile('.json,application/json,text/plain');
if (f) replaceText(f.text);
}
// ---------- tree ----------
const key = (path) => path.map((p) => '/' + String(p).replace(/~/g, '~0').replace(/\//g, '~1')).join('');
const isOpen = (path) => {
const k = key(path);
return closed.has(k) ? false : opened.has(k) || path.length <= 1;
};
function setOpen(path, open) {
const k = key(path);
(open ? opened : closed).add(k);
(open ? closed : opened).delete(k);
}
function renderTree() {
if (mode === 'text') return;
tree.classList.toggle('stale', !!error);
if (!ast) {
tree.replaceChildren(el('div.empty', {}, error ? 'Fix the JSON to see the tree.' : 'Nothing to show yet.'));
return;
}
const scroll = tree.scrollTop;
tree.replaceChildren(renderNode(ast, [], null, null));
tree.scrollTop = scroll;
}
function renderNode(node, path, label, parent) {
const isContainer = node.type === 'object' || node.type === 'array';
const row = el('div.tree-row', { role: 'treeitem', tabIndex: -1 });
const pk = key(path);
if (selectedPath === pk) row.classList.add('selected');
row.style.setProperty('--depth', path.length);
const open = isContainer && isOpen(path);
if (isContainer) {
row.setAttribute('aria-expanded', String(open));
row.append(el('button.twisty', { tabIndex: -1, 'aria-label': open ? 'Collapse' : 'Expand', onclick: (e) => {
e.stopPropagation();
setOpen(path, !open);
renderTree();
} }, open ? '▾' : '▸'));
} else row.append(el('span.twisty-space'));
if (label != null) {
if (typeof label === 'number') row.append(el('span.t-index', {}, String(label)), el('span.t-punct', {}, ': '));
else row.append(editable(el('span.t-key', { title: 'Double-click to rename' }, label), label, (v) => renameKey(parent, path, v)), el('span.t-punct', {}, ': '));
}
if (isContainer) {
const n = node.type === 'object' ? node.entries.length : node.items.length;
row.append(el('span.t-punct', {}, node.type === 'object' ? '{' : '['),
el('span.t-count', {}, open ? '' : ` ${n} ${node.type === 'object' ? (n === 1 ? 'key' : 'keys') : n === 1 ? 'item' : 'items'} `),
el('span.t-punct', {}, open ? '' : node.type === 'object' ? '}' : ']'));
} else {
const shownText = node.type === 'string' ? node.value : node.type === 'number' ? node.raw : String(node.value ?? 'null');
const display = node.type === 'string' ? JSON.stringify(shownText.length > 2000 ? shownText.slice(0, 2000) + '…' : shownText) : shownText;
row.append(editable(el(`span.t-val.t-${node.type}`, { title: 'Double-click to edit' }, display), shownText, (v) => editValue(path, node, v)));
}
const actions = el('span.row-actions');
if (isContainer) actions.append(el('button.mini', { title: node.type === 'object' ? 'Add a key' : 'Add an item', onclick: (e) => { e.stopPropagation(); addChild(path, node); } }, '+'));
if (path.length) actions.append(el('button.mini', { title: 'Delete', onclick: (e) => { e.stopPropagation(); removeAt(path); } }, '×'));
row.append(actions);
row.addEventListener('click', () => {
selectedPath = pk;
tree.querySelectorAll('.tree-row.selected').forEach((r) => r.classList.remove('selected'));
row.classList.add('selected');
pathBox.hidden = false;
pathBox.textContent = pathToString(path);
if (!error && node.start != null) selectRange(node.start, node.end);
});
if (!open) return row;
const children = node.type === 'object' ? node.entries.map((e) => [e.key, e.value]) : node.items.map((v, i) => [i, v]);
const limit = shown.get(pk) || PAGE;
const box = el('div.tree-children', { role: 'group' });
for (const [k, v] of children.slice(0, limit)) box.append(renderNode(v, [...path, k], k, node));
if (children.length > limit) {
box.append(el('button.btn.small.more', { style: `--depth:${path.length + 1}`, onclick: () => { shown.set(pk, limit + PAGE * 5); renderTree(); } },
`Show more (${children.length - limit} hidden)`));
}
const close = el('div.tree-row.closing', {}, el('span.twisty-space'), el('span.t-punct', {}, node.type === 'object' ? '}' : ']'));
close.style.setProperty('--depth', path.length);
return el('div', {}, row, box, close);
}
/** Double-click (or Enter on the focused row) turns a span into an inline input. */
function editable(span, initial, commit) {
span.addEventListener('dblclick', (e) => {
e.stopPropagation();
const input = el('input.inline-edit.mono', { value: initial, size: Math.max(4, Math.min(60, initial.length + 2)) });
let done = false;
const finish = (save) => {
if (done) return;
done = true;
if (save && input.value !== initial) commit(input.value);
else input.replaceWith(span);
};
input.addEventListener('keydown', (ev) => {
ev.stopPropagation();
// preventDefault: committing focuses the text pane, and the Enter must not land there.
if (ev.key === 'Enter') { ev.preventDefault(); finish(true); }
if (ev.key === 'Escape') { ev.preventDefault(); finish(false); }
});
input.addEventListener('blur', () => finish(true));
span.replaceWith(input);
input.focus();
input.select();
});
return span;
}
// Tree edits: change the AST, then rewrite the text formatted with the current indent.
function getAt(path) {
let n = ast;
for (const p of path) n = n.type === 'object' ? n.entries.find((e) => e.key === p)?.value : n.items[p];
return n;
}
function parentAndIndex(path) {
const parent = getAt(path.slice(0, -1));
const last = path[path.length - 1];
const idx = parent.type === 'object' ? parent.entries.findIndex((e) => e.key === last) : last;
return [parent, idx];
}
function commitAst() {
replaceText(stringify(ast, INDENTS[indentKey]) + '\n');
}
function guard() {
if (error) {
toast('Fix the JSON text before editing the tree', 'error');
renderTree();
return false;
}
return true;
}
function editValue(path, node, text) {
if (!guard()) return;
// Strings stay strings; other values are re-read as JSON (so "12" → 12, "abc" → "abc").
const next = node.type === 'string' ? stringNode(text) : nodeFromInput(text.trim());
if (!path.length) ast = next;
else {
const [parent, idx] = parentAndIndex(path);
if (parent.type === 'object') parent.entries[idx].value = next;
else parent.items[idx] = next;
}
commitAst();
}
function renameKey(parent, path, newKey) {
if (!guard()) return;
const [obj, idx] = parentAndIndex(path);
if (obj.entries.some((e, i) => i !== idx && e.key === newKey)) return toast(`Key "${newKey}" already exists`, 'error'), renderTree();
obj.entries[idx].key = newKey;
obj.entries[idx].keyRaw = JSON.stringify(newKey);
remapExpanded(path, [...path.slice(0, -1), newKey]);
commitAst();
}
function remapExpanded(from, to) {
const a = key(from), b = key(to);
const move = (set) => new Set([...set].map((k) => (k === a || k.startsWith(a + '/') ? b + k.slice(a.length) : k)));
opened = move(opened);
closed = move(closed);
}
function addChild(path, node) {
if (!guard()) return;
const target = getAt(path);
if (target.type === 'object') {
let k = 'key', i = 1;
while (target.entries.some((e) => e.key === k)) k = `key${++i}`;
target.entries.push({ key: k, keyRaw: JSON.stringify(k), value: { type: 'null' } });
} else target.items.push({ type: 'null' });
setOpen(path, true);
commitAst();
}
function removeAt(path) {
if (!guard()) return;
const [parent, idx] = parentAndIndex(path);
if (parent.type === 'object') parent.entries.splice(idx, 1);
else parent.items.splice(idx, 1);
selectedPath = null;
pathBox.hidden = true;
commitAst();
}
function expandAll(open) {
if (!ast) return;
opened = new Set();
closed = new Set();
shown.clear();
let count = 0;
(function walk(n, path) {
if (count > 5000 || (n.type !== 'object' && n.type !== 'array')) return;
count++;
if (open) opened.add(key(path));
else if (path.length) closed.add(key(path));
if (n.type === 'object') n.entries.forEach((e) => walk(e.value, [...path, e.key]));
else n.items.forEach((v, i) => walk(v, [...path, i]));
})(ast, []);
if (open && count > 5000) toast('Large document: expanded the first 5000 nodes');
renderTree();
}
// ---------- modes, input, shortcuts ----------
function setMode(m) {
mode = m;
workspace.dataset.mode = m;
modes.set(m);
store.set('json:mode', m);
renderTree();
}
// A paste opened via ?paste= is never written over this browser's own draft.
let fromPaste = false;
const save = debounce(() => {
if (!fromPaste && editor.value.length < 2_000_000) store.set('json:text', editor.value);
}, 500);
const slowParse = debounce(reparse, 400);
editor.addEventListener('input', () => {
updateGutter();
if (editor.value.length > TREE_LIVE_LIMIT) slowParse();
else reparse();
save();
});
function onKey(e) {
if (!(e.ctrlKey || e.metaKey) || !e.shiftKey) return;
const k = e.key.toLowerCase();
if (k === 'f') { e.preventDefault(); format(); }
if (k === 'm') { e.preventDefault(); compact(); }
}
document.addEventListener('keydown', onKey);
// Pasting a whole document into an empty editor formats it straight away.
editor.addEventListener('paste', (e) => {
if (editor.value.trim()) return;
const text = e.clipboardData?.getData('text/plain');
if (!text) return;
try {
const a = parse(text);
e.preventDefault();
document.execCommand('insertText', false, stringify(a, INDENTS[indentKey]) + '\n');
} catch {}
});
editor.value = store.get('json:text', SAMPLE);
const pasteId = ctx.query.get('paste');
if (pasteId) {
try {
const r = await fetch(`/api/paste/${encodeURIComponent(pasteId)}`);
const body = await r.json();
if (!r.ok) throw new Error(body.detail);
editor.value = body.content;
fromPaste = true;
ctx.setTitle(`paste ${pasteId}`);
toast('Opened a shared paste; edits here are not saved');
} catch (err) {
toast(`Couldn't load paste: ${err.message}`, 'error');
}
}
setMode(mode);
reparse();
const off = onLeave(save.flush);
return () => {
save.flush();
off();
document.removeEventListener('keydown', onKey);
};
}

View file

@ -0,0 +1,159 @@
// Markdown editor with live preview. Modes: edit only, side by side, full-page preview.
import { marked } from '../../vendor/marked.esm.js';
import DOMPurify from '../../vendor/purify.es.mjs';
import { el, segmented, store, copyText, downloadText, openTextFile, debounce, tabIndent, toast, onLeave } from '../ui.js';
import { createPaste } from './paste.js';
const SAMPLE = `# Markdown
Type on the left, see it rendered on the right. Switch to **Preview** for a full-page view.
## Formatting
*Italic*, **bold**, ~~strikethrough~~, \`inline code\` and [links](https://example.com).
> Blockquotes look like this.
- [x] Task lists
- [ ] Nested lists
1. one
2. two
| Column | Another | Right |
| ------ | :-----: | ----: |
| tables | aligned | 42 |
\`\`\`js
function hello(name) {
return \`Hello, \${name}!\`;
}
\`\`\`
---
Your text is saved in this browser as you type.
`;
marked.use({ gfm: true });
DOMPurify.addHook('afterSanitizeAttributes', (node) => {
if (node.tagName === 'A' && node.getAttribute('href') && !node.getAttribute('href').startsWith('#')) {
node.setAttribute('target', '_blank');
node.setAttribute('rel', 'noopener noreferrer');
}
});
export function render(md) {
return DOMPurify.sanitize(marked.parse(md));
}
export async function mount(root, ctx) {
let mode = store.get('md:mode', window.innerWidth < 800 ? 'edit' : 'split');
const editor = el('textarea.md-input.mono', {
spellcheck: true,
'aria-label': 'Markdown',
placeholder: 'Write Markdown here…',
});
tabIndent(editor);
const preview = el('article.md-preview.prose', { 'aria-label': 'Preview' });
const stats = el('span.muted.small');
const modes = segmented(
[['edit', 'Edit', 'Editor only'], ['split', 'Split', 'Editor and preview side by side'], ['preview', 'Preview', 'Full-page preview']],
mode,
setMode,
'View mode',
);
const workspace = el('div.md-workspace', {},
el('div.pane.md-edit-pane', {}, editor),
el('div.pane.md-preview-pane', {}, preview),
);
const toolbar = el('div.toolbar', {},
modes,
el('span.spacer'),
stats,
el('button.btn', { onclick: openFile, title: 'Open a .md file' }, 'Open'),
el('button.btn', { onclick: () => downloadText(editor.value, 'document.md', 'text/markdown'), title: 'Download as .md' }, 'Download'),
el('button.btn', { onclick: () => copyText(render(editor.value), 'HTML copied'), title: 'Copy the rendered HTML' }, 'Copy HTML'),
el('button.btn', { onclick: share, title: 'Create a 24-hour paste and copy its link' }, 'Share'),
);
root.append(el('div.tool.md-tool', {}, toolbar, workspace));
function update() {
preview.innerHTML = render(editor.value);
const words = (editor.value.match(/\S+/g) || []).length;
stats.textContent = `${words} word${words === 1 ? '' : 's'}`;
}
// A shared paste opened via ?paste= is never written over this browser's own draft.
let fromPaste = false;
const save = debounce(() => !fromPaste && store.set('md:text', editor.value), 400);
const live = debounce(update, 60);
editor.addEventListener('input', () => {
live();
save();
});
function setMode(m) {
mode = m;
workspace.dataset.mode = m;
modes.set(m);
if (!fromPaste) store.set('md:mode', m);
if (m !== 'edit') update();
if (m !== 'preview') editor.focus({ preventScroll: true });
}
// Keep the preview roughly in step with the editor while scrolling side by side.
let syncing = null;
const sync = (from, to) => () => {
if (mode !== 'split' || (syncing && syncing !== from)) return;
syncing = from;
const max = from.scrollHeight - from.clientHeight;
to.scrollTop = max > 0 ? (from.scrollTop / max) * (to.scrollHeight - to.clientHeight) : 0;
clearTimeout(sync.t);
sync.t = setTimeout(() => (syncing = null), 80);
};
const previewPane = workspace.querySelector('.md-preview-pane');
editor.addEventListener('scroll', sync(editor, previewPane));
previewPane.addEventListener('scroll', sync(previewPane, editor));
async function openFile() {
const f = await openTextFile('.md,.markdown,.txt,text/markdown,text/plain');
if (!f) return;
editor.value = f.text;
update();
save();
}
async function share() {
if (!editor.value.trim()) return toast('Nothing to share', 'error');
const p = await createPaste(editor.value);
if (p) copyText(`${location.origin}/markdown?paste=${p.id}`, 'Link copied (expires in 24 h)');
}
// Load: ?paste=<id> opens a paste here; otherwise the saved draft, otherwise the sample.
const pasteId = ctx.query.get('paste');
editor.value = store.get('md:text', SAMPLE);
if (pasteId) {
try {
const r = await fetch(`/api/paste/${encodeURIComponent(pasteId)}`);
if (!r.ok) throw new Error((await r.json()).detail);
editor.value = (await r.json()).content;
ctx.setTitle(`paste ${pasteId}`);
fromPaste = true;
mode = 'preview';
toast('Opened a shared paste; edits here are not saved', 'info');
} catch (err) {
toast(`Couldn't load paste: ${err.message}`, 'error');
}
}
setMode(mode);
update();
const off = onLeave(save.flush);
return () => {
save.flush();
off();
};
}

View file

@ -0,0 +1,165 @@
// Pastebin: /paste to create, /paste/<id> to view. Pastes expire 24 h after creation.
// Pastes made in this browser are remembered locally (with their delete tokens).
import { el, store, copyText, downloadText, toast, timeLeft, formatBytes } from '../ui.js';
const MAX_BYTES = 1024 * 1024;
function mine() {
const now = Date.now() / 1000;
return (store.get('paste:mine', []) || []).filter((p) => p.expires_at > now);
}
function remember(p, preview) {
store.set('paste:mine', [{ id: p.id, expires_at: p.expires_at, delete_token: p.delete_token, preview }, ...mine()].slice(0, 50));
}
function forget(id) {
store.set('paste:mine', mine().filter((p) => p.id !== id));
}
/** Creates a paste and remembers it locally. Resolves with {id, expires_at, delete_token} or null. */
export async function createPaste(content) {
try {
const r = await fetch('/api/paste', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content }),
});
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(body.detail || `HTTP ${r.status}`);
remember(body, content.slice(0, 80).replace(/\s+/g, ' '));
return body;
} catch (err) {
toast(`Couldn't create paste: ${err.message}`, 'error');
return null;
}
}
async function deletePaste(id, token) {
const r = await fetch(`/api/paste/${encodeURIComponent(id)}`, { method: 'DELETE', headers: { 'X-Delete-Token': token } });
if (r.ok || r.status === 404) forget(id);
return r.ok;
}
export async function mount(root, ctx) {
const timers = [];
const cleanup = () => timers.forEach(clearInterval);
if (ctx.rest) await renderView(root, ctx, ctx.rest, timers);
else renderCreate(root, ctx, timers);
return cleanup;
}
function renderCreate(root, ctx, timers) {
const ta = el('textarea.paste-input.mono', { placeholder: 'Paste or type text…', spellcheck: false, 'aria-label': 'Paste content' });
ta.value = store.get('paste:draft', '');
const info = el('span.muted.small');
const btn = el('button.btn.primary', { onclick: submit }, 'Create paste');
const updateInfo = () => {
const n = new Blob([ta.value]).size;
info.textContent = `${formatBytes(n)} of 1 MB · expires 24 h after creation`;
info.classList.toggle('error-text', n > MAX_BYTES);
};
ta.addEventListener('input', () => {
updateInfo();
store.set('paste:draft', ta.value);
});
ta.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit();
});
async function submit() {
if (!ta.value.trim()) return toast('Nothing to paste', 'error');
if (new Blob([ta.value]).size > MAX_BYTES) return toast('Paste is larger than 1 MB', 'error');
btn.disabled = true;
const p = await createPaste(ta.value);
btn.disabled = false;
if (!p) return;
store.set('paste:draft', '');
copyText(`${location.origin}/paste/${p.id}`, 'Link copied');
ctx.navigate(`/paste/${p.id}`);
}
const list = el('div.paste-list');
function drawList() {
const items = mine();
list.replaceChildren(
...(items.length
? [el('h2.section-title', {}, 'Your recent pastes'),
...items.map((p) =>
el('div.paste-item', {},
el('a.mono', { href: `/paste/${p.id}` }, p.id),
el('span.paste-preview.muted', {}, p.preview || ''),
el('span.muted.small.nowrap', {}, timeLeft(p.expires_at)),
el('button.btn.small', { title: 'Delete now', onclick: async () => {
if (await deletePaste(p.id, p.delete_token)) toast('Deleted');
drawList();
} }, 'Delete'),
))]
: []),
);
}
drawList();
timers.push(setInterval(drawList, 30000));
updateInfo();
root.append(
el('div.tool.paste-tool', {},
el('div.toolbar', {}, el('strong', {}, 'New paste'), el('span.spacer'), info, btn),
el('div.paste-body', {}, ta, el('div.hint.muted.small', {}, 'Ctrl+Enter to create. Anyone with the link can read it until it expires. Don\'t paste secrets.'), list),
),
);
ta.focus();
}
async function renderView(root, ctx, id, timers) {
ctx.setTitle(id);
let p;
try {
const r = await fetch(`/api/paste/${encodeURIComponent(id)}`);
p = await r.json();
if (!r.ok) throw new Error(p.detail || `HTTP ${r.status}`);
} catch (err) {
forget(id);
root.append(el('div.empty', {}, el('p', {}, err.message), el('a.btn.primary', { href: '/paste' }, 'New paste')));
return;
}
const own = mine().find((m) => m.id === id);
const left = el('span.muted.small', {}, timeLeft(p.expires_at));
timers.push(setInterval(() => (left.textContent = timeLeft(p.expires_at)), 30000));
const lines = p.content.split('\n');
const wrapBtn = el('button.btn', { onclick: () => {
view.classList.toggle('wrap');
store.set('paste:wrap', view.classList.contains('wrap'));
} }, 'Wrap');
const view = el('div.paste-view.mono', {},
el('div.paste-lines', { 'aria-hidden': 'true' }, lines.map((_, i) => i + 1).join('\n')),
el('pre.paste-text', {}, p.content),
);
if (store.get('paste:wrap', false)) view.classList.add('wrap');
root.append(
el('div.tool.paste-tool', {},
el('div.toolbar', {},
el('span.mono.strong', {}, id),
el('span.muted.small', {}, `${formatBytes(p.size)} · ${lines.length} line${lines.length === 1 ? '' : 's'}`),
left,
el('span.spacer'),
el('button.btn', { onclick: () => copyText(`${location.origin}/paste/${id}`, 'Link copied') }, 'Copy link'),
el('button.btn', { onclick: () => copyText(p.content) }, 'Copy text'),
el('a.btn', { href: `/raw/${id}`, target: '_blank', rel: 'noopener' }, 'Raw'),
el('button.btn', { onclick: () => downloadText(p.content, `${id}.txt`) }, 'Download'),
el('a.btn', { href: `/markdown?paste=${id}`, title: 'Render this paste as Markdown' }, 'As Markdown'),
el('a.btn', { href: `/json?paste=${id}`, title: 'Open this paste in the JSON editor' }, 'As JSON'),
wrapBtn,
own && el('button.btn.danger', { onclick: async () => {
if (!confirm('Delete this paste now?')) return;
if (await deletePaste(id, own.delete_token)) {
toast('Deleted');
ctx.navigate('/paste');
} else toast("Couldn't delete", 'error');
} }, 'Delete'),
el('a.btn.primary', { href: '/paste' }, 'New'),
),
view,
),
);
}

159
app/static/js/ui.js Normal file
View file

@ -0,0 +1,159 @@
// Small helpers shared by every tool.
/** el('button.primary', {onclick}, 'Save') — tag with optional .classes, props/attrs, children. */
export function el(spec, props = {}, ...children) {
const [tag, ...classes] = spec.split('.');
const node = document.createElement(tag || 'div');
if (classes.length) node.className = classes.join(' ');
for (const [k, v] of Object.entries(props || {})) {
if (v == null || v === false) continue;
if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
else if (k === 'dataset') Object.assign(node.dataset, v);
else if (k in node && typeof v !== 'string') node[k] = v;
else node.setAttribute(k, v === true ? '' : v);
}
for (const c of children.flat()) if (c != null && c !== false) node.append(c);
return node;
}
export function toast(message, kind = 'info') {
const box = document.getElementById('toasts');
const t = el(`div.toast.${kind}`, { role: kind === 'error' ? 'alert' : 'status' }, message);
box.append(t);
setTimeout(() => t.classList.add('out'), kind === 'error' ? 5000 : 2200);
setTimeout(() => t.remove(), kind === 'error' ? 5400 : 2600);
}
export async function copyText(text, what = 'Copied') {
try {
await navigator.clipboard.writeText(text);
} catch {
const ta = el('textarea', { value: text, style: 'position:fixed;opacity:0' });
document.body.append(ta);
ta.select();
document.execCommand('copy');
ta.remove();
}
toast(what);
}
export function downloadText(text, filename, type = 'text/plain') {
const url = URL.createObjectURL(new Blob([text], { type: `${type};charset=utf-8` }));
const a = el('a', { href: url, download: filename });
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/** Opens a file picker and resolves with {name, text}, or null if cancelled. */
export function openTextFile(accept = '') {
return new Promise((resolve) => {
const input = el('input', { type: 'file', accept });
input.addEventListener('change', async () => {
const f = input.files[0];
resolve(f ? { name: f.name, text: await f.text() } : null);
});
input.addEventListener('cancel', () => resolve(null));
input.click();
});
}
// localStorage can be missing or throw (private windows, blocked storage); never let that break a tool.
export const store = {
get(key, fallback = null) {
try {
const v = localStorage.getItem(`tools:${key}`);
return v == null ? fallback : JSON.parse(v);
} catch {
return fallback;
}
},
set(key, value) {
try {
localStorage.setItem(`tools:${key}`, JSON.stringify(value));
} catch {}
},
};
export function formatBytes(n) {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / 1024 / 1024).toFixed(2)} MB`;
}
export function timeLeft(expiresAtSec) {
const s = Math.max(0, Math.round(expiresAtSec - Date.now() / 1000));
if (s <= 0) return 'expired';
if (s < 60) return `${s}s left`;
if (s < 3600) return `${Math.floor(s / 60)}m left`;
return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m left`;
}
/** Debounced fn; .flush() runs a pending call now (e.g. before the page unloads). */
export function debounce(fn, ms) {
let t, pending;
const d = (...args) => {
clearTimeout(t);
pending = args;
t = setTimeout(d.flush, ms);
};
d.flush = () => {
clearTimeout(t);
if (pending) {
const args = pending;
pending = null;
fn(...args);
}
};
return d;
}
/** Runs fn when the page is hidden/unloaded; returns a function that removes the listener. */
export function onLeave(fn) {
window.addEventListener('pagehide', fn);
return () => window.removeEventListener('pagehide', fn);
}
/** A segmented control: segmented([['edit','Edit'],...], current, onChange). */
export function segmented(options, current, onChange, label = '') {
const wrap = el('div.segmented', { role: 'radiogroup', 'aria-label': label });
const buttons = options.map(([value, text, title]) =>
el('button', {
type: 'button',
role: 'radio',
title: title || text,
'aria-checked': String(value === current),
onclick: () => set(value, true),
}, text),
);
function set(value, fire) {
options.forEach(([v], i) => buttons[i].setAttribute('aria-checked', String(v === value)));
if (fire) onChange(value);
}
wrap.append(...buttons);
wrap.set = (v) => set(v, false);
return wrap;
}
/** Makes Tab / Shift+Tab indent and outdent in a textarea instead of moving focus. */
export function tabIndent(ta, unit = ' ') {
ta.addEventListener('keydown', (e) => {
if (e.key !== 'Tab' || e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
const { selectionStart: s, selectionEnd: end, value } = ta;
const lineStart = value.lastIndexOf('\n', s - 1) + 1;
if (s === end && !e.shiftKey) {
document.execCommand('insertText', false, unit) || ta.setRangeText(unit, s, end, 'end');
return;
}
const block = value.slice(lineStart, end);
const lines = block.split('\n');
const out = e.shiftKey
? lines.map((l) => (l.startsWith(unit) ? l.slice(unit.length) : l.replace(/^\t| {1,2}/, '')))
: lines.map((l) => unit + l);
ta.setSelectionRange(lineStart, end);
document.execCommand('insertText', false, out.join('\n')) || ta.setRangeText(out.join('\n'), lineStart, end, 'select');
ta.setSelectionRange(lineStart, lineStart + out.join('\n').length);
});
}

202
app/static/vendor/dompurify.LICENSE vendored Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

44
app/static/vendor/marked.LICENSE vendored Normal file
View file

@ -0,0 +1,44 @@
# License information
## Contribution License Agreement
If you contribute code to this project, you are implicitly allowing your code
to be distributed under the MIT license. You are also implicitly verifying that
all code is your original work. `</legalese>`
## Marked
Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/)
Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## Markdown
Copyright © 2004, John Gruber
http://daringfireball.net/
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

81
app/static/vendor/marked.esm.js vendored Normal file

File diff suppressed because one or more lines are too long

9
app/static/vendor/purify.es.mjs vendored Normal file

File diff suppressed because one or more lines are too long

1
app/tools/__init__.py Normal file
View file

@ -0,0 +1 @@
"""Server-side parts of tools. Each non-underscore module here must expose `router`."""

180
app/tools/paste.py Normal file
View file

@ -0,0 +1,180 @@
"""Pastebin: anonymous text pastes that expire 24 hours after creation.
Storage is one SQLite file in $DATA_DIR. Expired pastes are invisible at once and
deleted by a sweep every few minutes. Anti-abuse is deliberately simple: a size cap
per paste, a cap on total live storage, and a per-IP creation rate limit.
"""
import asyncio
import json
import os
import secrets
import sqlite3
import threading
import time
from collections import defaultdict, deque
from pathlib import Path
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import PlainTextResponse
TTL = 24 * 3600
MAX_BYTES = 1024 * 1024 # per paste
MAX_TOTAL_BYTES = 256 * 1024 * 1024 # all live pastes together
RATE_LIMIT = 30 # creations per IP ...
RATE_WINDOW = 3600 # ... per this many seconds
SWEEP_EVERY = 300
DB_PATH = Path(os.environ.get("DATA_DIR", "./data")) / "paste.db"
router = APIRouter()
_lock = threading.Lock()
_recent: dict[str, deque] = defaultdict(deque)
_sweeper: asyncio.Task | None = None
def _db() -> sqlite3.Connection:
conn = sqlite3.connect(DB_PATH, timeout=10)
conn.row_factory = sqlite3.Row
return conn
def _init():
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
with _db() as c:
c.execute("PRAGMA journal_mode=WAL")
c.execute(
"""CREATE TABLE IF NOT EXISTS pastes (
id TEXT PRIMARY KEY,
content TEXT NOT NULL,
size INTEGER NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
delete_token TEXT NOT NULL
)"""
)
c.execute("CREATE INDEX IF NOT EXISTS pastes_expires ON pastes(expires_at)")
def _sweep() -> int:
with _db() as c:
return c.execute("DELETE FROM pastes WHERE expires_at <= ?", (int(time.time()),)).rowcount
async def _sweep_loop():
while True:
await asyncio.to_thread(_sweep)
await asyncio.sleep(SWEEP_EVERY)
async def startup():
global _sweeper
_init()
_sweeper = asyncio.create_task(_sweep_loop())
async def shutdown():
if _sweeper:
_sweeper.cancel()
def client_ip(request: Request) -> str:
# uvicorn runs with --proxy-headers --forwarded-allow-ips 127.0.0.1, so behind
# a reverse proxy that connects over loopback this is already the visitor's address.
return request.client.host if request.client else ""
def _rate_limited(ip: str) -> bool:
now = time.monotonic()
with _lock:
q = _recent[ip]
while q and q[0] <= now - RATE_WINDOW:
q.popleft()
if len(q) >= RATE_LIMIT:
return True
q.append(now)
if len(_recent) > 10000: # drop idle entries so the map can't grow forever
for k in [k for k, v in _recent.items() if not v]:
del _recent[k]
return False
def _get(pid: str) -> sqlite3.Row:
with _db() as c:
row = c.execute(
"SELECT id, content, size, created_at, expires_at FROM pastes WHERE id = ? AND expires_at > ?",
(pid, int(time.time())),
).fetchone()
if not row:
raise HTTPException(404, "This paste doesn't exist or has expired.")
return row
@router.post("/api/paste", status_code=201)
async def create(request: Request):
body = bytearray()
async for chunk in request.stream():
body += chunk
if len(body) > MAX_BYTES + 64 * 1024:
raise HTTPException(413, "Paste is larger than 1 MiB.")
try:
data = json.loads(body)
content = data["content"]
assert isinstance(content, str)
except Exception:
raise HTTPException(400, 'Expected JSON: {"content": "<text>"}')
size = len(content.encode())
if not content.strip():
raise HTTPException(400, "Paste is empty.")
if size > MAX_BYTES:
raise HTTPException(413, "Paste is larger than 1 MiB.")
if _rate_limited(client_ip(request)):
raise HTTPException(429, f"Too many pastes; the limit is {RATE_LIMIT} per hour.")
now = int(time.time())
pid, token = secrets.token_urlsafe(6), secrets.token_urlsafe(18)
with _lock, _db() as c:
used = c.execute("SELECT COALESCE(SUM(size), 0) FROM pastes WHERE expires_at > ?", (now,)).fetchone()[0]
if used + size > MAX_TOTAL_BYTES:
raise HTTPException(507, "The pastebin is full right now; try again later.")
c.execute(
"INSERT INTO pastes (id, content, size, created_at, expires_at, delete_token) VALUES (?, ?, ?, ?, ?, ?)",
(pid, content, size, now, now + TTL, token),
)
return {"id": pid, "expires_at": now + TTL, "delete_token": token}
@router.get("/api/paste/{pid}")
def read(pid: str):
row = _get(pid)
return {
"id": row["id"],
"content": row["content"],
"size": row["size"],
"created_at": row["created_at"],
"expires_at": row["expires_at"],
}
@router.delete("/api/paste/{pid}", status_code=204)
def delete(pid: str, request: Request):
token = request.headers.get("x-delete-token", "")
with _db() as c:
row = c.execute("SELECT delete_token FROM pastes WHERE id = ?", (pid,)).fetchone()
if not row or not secrets.compare_digest(row["delete_token"], token):
raise HTTPException(404, "Not found, or wrong delete token.")
c.execute("DELETE FROM pastes WHERE id = ?", (pid,))
@router.get("/raw/{pid}", response_class=PlainTextResponse)
def raw(pid: str):
row = _get(pid)
return PlainTextResponse(
row["content"],
headers={
# Never let a paste act as a web page on this origin.
"Content-Security-Policy": "default-src 'none'; sandbox",
"X-Robots-Tag": "noindex",
"Cache-Control": "no-store",
},
)