Redesign admin Pastes page as Xiaohongshu-style cards with previews

- Replace the pastes table with a masonry card grid: each card shows the
  paste's first image as a thumbnail, a short plain-text summary, meta badges,
  and Copy link / Edit / QR / Delete actions.
- Clicking anywhere on a card (except the action buttons) opens an in-page
  preview modal with the rendered paste in an iframe; it can be expanded to the
  main content area or closed (Esc/backdrop/button). Keyboard accessible.
- Generate and cache 512px (long side) JPEG thumbnails for uploaded images on
  first request (GET /uploads/thumb/{filename}); also generated at upload time
  and invalidated on resize/delete. WebP falls back to the original.
- Sync the public paste pages (bin_view, bin_token) to the dark theme so they
  match the rest of the app and the preview iframe.
- Relax framing headers to same-origin (X-Frame-Options SAMEORIGIN,
  frame-ancestors 'self') so the same-origin preview iframe can load; cross-site
  framing stays blocked.
- Document the new thumbnail route in the README routes table.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
lucioandClaude Opus 4.8 committed 2026-06-05 00:23:51 -07:00
1 parent f013e1f22b
commit 87477556e2
7 files changed
+520 -63

No files matched your search

+1
View File
@@ -423,6 +423,7 @@ If proxying through Cloudflare, `X-Forwarded-For` is safe to trust for rate limi
| `GET` | `/bin/{name}` | Public | View paste |
| `GET` | `/bin/{name}/{token}` | Public | View token-protected paste |
| `GET` | `/uploads/{filename}` | Public | Serve uploaded image inline; non-images forced as `attachment` |
| `GET` | `/uploads/thumb/{filename}` | Public | Serve a 512px (long side) JPEG thumbnail of an uploaded image, generated and cached on first request |
| `GET` | `/admin/login` | Public | Login form |
| `POST` | `/admin/login` | Public | Submit login |
| `POST` | `/admin/logout` | Admin | Logout (CSRF protected) |
+165 -1
View File
@@ -27,6 +27,7 @@ import (
"strings"
"time"
"glimmer/internal/db"
"glimmer/internal/slug"
"github.com/yuin/goldmark"
@@ -544,8 +545,16 @@ func (s *Server) handleAdminBin(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
cards := make([]pasteCard, 0, len(pastes))
for _, p := range pastes {
cards = append(cards, pasteCard{
Paste: p,
Summary: pasteSummary(p.Content, 140),
ThumbURL: thumbURLFor(firstPasteImage(p.Content)),
})
}
d := s.adminPage(w, r)
d.Pastes = pastes
d.Pastes = cards
renderTemplate(w, "admin_bin.html", d)
}
@@ -776,6 +785,158 @@ func scaleImage(src image.Image, maxDim int) image.Image {
return dst
}
// ---- Thumbnails ----
const thumbMaxDim = 512 // long-side size of generated thumbnails, in pixels
// thumbDir is the directory thumbnails are cached in (a subdir of uploads).
func (s *Server) thumbDir() string {
return filepath.Join(s.cfg.Upload.Dir, "thumbs")
}
// thumbPath returns the on-disk path of the thumbnail for an upload filename.
// Thumbnails are always JPEG, named after the original's hash.
func (s *Server) thumbPath(filename string) string {
base := strings.TrimSuffix(filename, filepath.Ext(filename))
return filepath.Join(s.thumbDir(), base+".jpg")
}
// generateThumbnail decodes an uploaded image, scales it so its long side is at
// most thumbMaxDim px, and writes a cached JPEG thumbnail. Best-effort: returns
// an error for formats it can't decode (e.g. WebP), leaving callers to fall
// back to the original file.
func (s *Server) generateThumbnail(filename string) error {
if !isImageFile(filename) {
return fmt.Errorf("not an image")
}
f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, filename))
if err != nil {
return err
}
src, _, err := image.Decode(f)
f.Close()
if err != nil {
return err
}
dst := scaleImage(src, thumbMaxDim)
if err := os.MkdirAll(s.thumbDir(), 0755); err != nil {
return err
}
tp := s.thumbPath(filename)
tmp := tp + ".tmp"
out, err := os.Create(tmp)
if err != nil {
return err
}
if err := jpeg.Encode(out, dst, &jpeg.Options{Quality: 82}); err != nil {
out.Close()
os.Remove(tmp)
return err
}
out.Close()
return os.Rename(tmp, tp)
}
// handleThumb serves a cached 512px (long side) JPEG thumbnail for an uploaded
// image, generating it on first request. Falls back to serving the original
// inline for images it can't decode (e.g. WebP).
func (s *Server) handleThumb(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("filename")
if !validUploadFilename(name) || !isImageFile(name) {
http.NotFound(w, r)
return
}
orig := filepath.Join(s.cfg.Upload.Dir, name)
if _, err := os.Stat(orig); err != nil {
http.NotFound(w, r)
return
}
tp := s.thumbPath(name)
if _, err := os.Stat(tp); err != nil {
if err := s.generateThumbnail(name); err != nil {
// Can't thumbnail this format — serve the original inline.
http.ServeFile(w, r, orig)
return
}
}
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Cache-Control", "public, max-age=86400")
http.ServeFile(w, r, tp)
}
// ---- Paste card helpers (admin Pastes grid) ----
type pasteCard struct {
db.Paste
Summary string
ThumbURL string // thumbnail URL for the first image, or "" if none
}
var (
pasteImgMDRe = regexp.MustCompile(`!\[[^\]]*\]\(\s*(\S+?)\s*\)`)
pasteImgHTMLRe = regexp.MustCompile(`(?i)<img[^>]+src=["']?([^"'>\s]+)`)
fencedCodeRe = regexp.MustCompile("(?s)```.*?```")
mdLinkRe = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
mdStripRe = regexp.MustCompile("[#>*_`~|<>\\-]+")
)
// firstPasteImage returns the URL of the first image referenced in paste
// content (markdown or HTML), or "" if there is none.
func firstPasteImage(content string) string {
idxMD, idxHTML := -1, -1
var urlMD, urlHTML string
if m := pasteImgMDRe.FindStringSubmatchIndex(content); m != nil {
idxMD, urlMD = m[0], content[m[2]:m[3]]
}
if m := pasteImgHTMLRe.FindStringSubmatchIndex(content); m != nil {
idxHTML, urlHTML = m[0], content[m[2]:m[3]]
}
switch {
case idxMD == -1 && idxHTML == -1:
return ""
case idxHTML == -1:
return urlMD
case idxMD == -1:
return urlHTML
case idxMD <= idxHTML:
return urlMD
default:
return urlHTML
}
}
// thumbURLFor maps a paste's first image URL to a card thumbnail URL. Local
// uploads use the on-the-fly thumbnail route; remote https images are used
// as-is (allowed by CSP img-src); anything else yields no thumbnail.
func thumbURLFor(rawURL string) string {
if strings.HasPrefix(rawURL, "/uploads/") {
name := strings.TrimPrefix(rawURL, "/uploads/")
if validUploadFilename(name) && isImageFile(name) {
return "/uploads/thumb/" + name
}
return ""
}
if strings.HasPrefix(rawURL, "https://") {
return rawURL
}
return ""
}
// pasteSummary produces a short plain-text excerpt from paste content by
// stripping code fences, images, link targets, and markdown punctuation.
func pasteSummary(content string, max int) string {
t := fencedCodeRe.ReplaceAllString(content, " ")
t = pasteImgMDRe.ReplaceAllString(t, " ")
t = mdLinkRe.ReplaceAllString(t, "$1")
t = mdStripRe.ReplaceAllString(t, " ")
t = strings.Join(strings.Fields(t), " ")
r := []rune(t)
if len(r) > max {
return strings.TrimSpace(string(r[:max])) + "…"
}
return t
}
// handleUploadsServe serves files from the upload directory. For non-image
// files it forces Content-Disposition: attachment with an octet-stream type so
// that arbitrary uploads (e.g. HTML, SVG, JS) cannot be rendered in-browser
@@ -886,6 +1047,7 @@ func (s *Server) handleAdminUploadDelete(w http.ResponseWriter, r *http.Request)
return
}
os.Remove(filepath.Join(s.cfg.Upload.Dir, filename))
os.Remove(s.thumbPath(filename))
s.db.DeleteUpload(filename)
http.Redirect(w, r, "/admin/uploads", http.StatusSeeOther)
}
@@ -945,6 +1107,7 @@ func (s *Server) handleAdminUploadResize(w http.ResponseWriter, r *http.Request)
jsonError(w, "Failed to save resized image", http.StatusInternalServerError)
return
}
os.Remove(s.thumbPath(filename)) // invalidate cached thumbnail; regenerated on next view
info, _ := os.Stat(path)
var newSize int64
@@ -1067,6 +1230,7 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
displayName := sanitizeDisplayFilename(header.Filename)
s.db.RecordUpload(filename, displayName)
_ = s.generateThumbnail(filename) // best-effort; lazily regenerated on first view otherwise
imgURL := "/uploads/" + filename
w.Header().Set("Content-Type", "application/json")
+9 -4
View File
@@ -43,7 +43,9 @@ func New(cfg *config.Config, database *db.DB) *Server {
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Frame-Options", "DENY")
// SAMEORIGIN (not DENY) so the admin Pastes page can preview a paste in
// an in-page iframe; cross-site framing is still blocked.
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
// All assets are served from the same origin (Pico CSS is vendored
@@ -51,8 +53,9 @@ func securityHeaders(next http.Handler) http.Handler {
// down. img-src allows data: and https: so uploaded/remote images and
// favicons still render, and blob: so the client-side image compressor
// (canvas) can load a selected file before upload. 'unsafe-inline' is required by the inline
// scripts/styles in the templates; object-src/base-uri/frame-ancestors
// are pinned to blunt injection and clickjacking.
// scripts/styles in the templates; object-src/base-uri are pinned to
// blunt injection; frame-ancestors 'self' permits the same-origin paste
// preview iframe while blocking cross-site clickjacking.
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"img-src 'self' data: https: blob:; "+
@@ -60,7 +63,7 @@ func securityHeaders(next http.Handler) http.Handler {
"script-src 'self' 'unsafe-inline'; "+
"object-src 'none'; "+
"base-uri 'none'; "+
"frame-ancestors 'none'")
"frame-ancestors 'self'")
next.ServeHTTP(w, r)
})
}
@@ -96,6 +99,8 @@ func (s *Server) Start() error {
// Uploaded files (public — appear in public pastes). Non-image files are
// served as attachments to prevent same-origin XSS via HTML/SVG/JS uploads.
// The more specific /uploads/thumb/ route wins for thumbnails.
mux.HandleFunc("GET /uploads/thumb/{filename}", s.handleThumb)
mux.HandleFunc("GET /uploads/", s.handleUploadsServe)
// Public routes
+225
View File
@@ -417,3 +417,228 @@ mark.badge-hidden {
min-width: 2.5rem;
text-align: center;
}
/* ── Pastes masonry cards (Xiaohongshu style) ───────────────────────── */
.pcard-grid {
columns: 240px;
column-gap: 1rem;
margin-top: 1rem;
}
.pcard {
break-inside: avoid;
display: inline-block;
width: 100%;
margin: 0 0 1rem;
padding: 0;
background: var(--pico-card-background-color);
border: 1px solid var(--pico-muted-border-color);
border-radius: var(--pico-border-radius);
overflow: hidden;
cursor: pointer;
transition: border-color 0.15s, box-shadow 0.15s, transform 0.15s;
}
.pcard:hover {
transform: translateY(-2px);
}
.pcard:focus-visible {
outline: 2px solid var(--pico-primary);
outline-offset: 2px;
}
.pcard:hover .pcard-img {
opacity: 0.92;
}
.pcard:hover {
border-color: var(--pico-primary);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
}
.pcard-imgwrap {
display: block;
width: 100%;
margin: 0;
padding: 0;
border: 0;
background: none;
cursor: pointer;
line-height: 0;
}
.pcard-img {
width: 100%;
height: auto;
display: block;
transition: opacity 0.15s;
}
.pcard-imgwrap:hover .pcard-img {
opacity: 0.9;
}
.pcard-body {
padding: 0.75rem;
}
.pcard-title {
display: block;
width: 100%;
margin: 0 0 0.35rem;
padding: 0;
border: 0;
background: none;
text-align: left;
font-weight: 600;
font-size: 1rem;
line-height: 1.3;
color: var(--pico-color);
cursor: pointer;
}
.pcard-title:hover {
color: var(--pico-primary);
}
.pcard-summary {
margin: 0 0 0.5rem;
font-size: 0.85rem;
line-height: 1.45;
color: var(--pico-muted-color);
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.pcard-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.3rem;
margin-bottom: 0.6rem;
font-size: 0.72rem;
color: var(--pico-muted-color);
}
.pcard-date {
margin-left: auto;
font-variant-numeric: tabular-nums;
}
.pcard-actions {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
cursor: default;
}
.pcard-actions form {
margin: 0;
display: flex;
}
.pcard-actions a[role="button"],
.pcard-actions button {
margin: 0;
padding: 0.2rem 0.5rem;
font-size: 0.78rem;
white-space: nowrap;
}
/* ── In-page paste preview modal ────────────────────────────────────── */
.preview-dialog {
width: min(820px, 94vw);
height: min(80vh, 920px);
max-width: none;
max-height: none;
padding: 0;
border: 1px solid var(--pico-muted-border-color);
border-radius: 16px;
background: var(--pico-card-background-color);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55);
overflow: hidden;
transition: width 0.22s ease, height 0.22s ease;
}
/* dialog is only laid out when open; scope flex so closed state stays hidden */
.preview-dialog[open] {
display: flex;
flex-direction: column;
}
/* Expanded fills the main content area, not the whole viewport. */
.preview-dialog.expanded {
width: min(1180px, 94vw);
height: 88vh;
}
.preview-dialog::backdrop {
background: rgba(0, 0, 0, 0.55);
backdrop-filter: blur(3px);
}
.preview-head {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.55rem 0.6rem 0.55rem 1rem;
background: var(--pico-card-background-color);
border-bottom: 1px solid var(--pico-muted-border-color);
}
.preview-title {
flex: 1;
min-width: 0;
font-weight: 600;
font-size: 0.95rem;
color: var(--pico-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.preview-actions {
flex: 0 0 auto;
display: flex;
gap: 0.4rem;
align-items: center;
}
.preview-actions a,
.preview-actions button {
margin: 0;
border-radius: 8px;
}
/* square icon buttons for expand / close */
#preview-expand,
.preview-close {
width: 2rem;
padding: 0.25rem 0;
text-align: center;
line-height: 1;
font-size: 0.95rem;
}
.preview-close {
background: transparent;
border: 1px solid var(--pico-muted-border-color);
color: var(--pico-muted-color);
}
.preview-close:hover {
background: var(--pico-del-color);
border-color: var(--pico-del-color);
color: #fff;
}
.preview-frame {
flex: 1 1 auto;
width: 100%;
border: 0;
background: var(--pico-background-color);
}
+118 -56
View File
@@ -26,67 +26,70 @@
<a href="/admin/bin" class="tab-link active">Pastes</a>
<a href="/admin/uploads" class="tab-link">Uploads</a>
</div>
<main class="container" style="max-width:960px">
<main class="container" style="max-width:1180px">
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
<article class="card-table">
<div class="section-header">
<hgroup>
<h2>Pastes</h2>
<p>{{len .Pastes}} pastes</p>
</hgroup>
<a href="/admin/bin/new" role="button" class="btn-sm">+ New Paste</a>
</div>
<figure>
<table role="grid">
<thead>
<tr>
<th>Name</th>
<th>Title</th>
<th>Format</th>
<th>Token</th>
<th>Updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{range .Pastes}}
<tr>
<td><a href="/bin/{{.Name}}{{if .Token}}/{{.Token}}{{end}}" target="_blank">{{.Name}}</a></td>
<td>{{.Title}}</td>
<td><mark class="badge-format">{{.Format}}</mark></td>
<td>{{if .Token}}<mark class="badge-token">&#128274; token</mark>{{else}}<mark class="badge-public">public</mark>{{end}}{{if .Hidden}} <mark class="badge-hidden">hidden</mark>{{end}}</td>
<td>{{.UpdatedAt.Format "2006-01-02 15:04"}}</td>
<td>
<div role="group">
<a href="/admin/bin/edit/{{.ID}}" role="button" class="outline">Edit</a>
<button type="button" class="outline" onclick="showBinQR('{{.Name}}', false)">QR</button>
{{if .Token}}<button type="button" class="outline" onclick="showBinQR('{{.Name}}', true)">Full QR</button>{{end}}
<form method="post" action="/admin/bin/delete/{{.ID}}" onsubmit="return confirm('Delete paste {{.Name}}?')">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary">Del</button>
</form>
</div>
</td>
</tr>
{{else}}
<tr>
<td colspan="6">
<div class="empty-state">
<span class="empty-icon">&#128196;</span>
<p>No pastes yet.</p>
<a href="/admin/bin/new">Create your first paste</a>
</div>
</td>
</tr>
{{end}}
</tbody>
</table>
</figure>
</article>
<div class="section-header" style="padding-left:0;padding-right:0">
<hgroup>
<h2>Pastes</h2>
<p>{{len .Pastes}} pastes</p>
</hgroup>
<a href="/admin/bin/new" role="button" class="btn-sm">+ New Paste</a>
</div>
{{if .Pastes}}
<div class="pcard-grid">
{{range .Pastes}}
<article class="pcard js-preview" data-name="{{.Name}}" data-token="{{.Token}}" data-title="{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}" role="button" tabindex="0">
{{if .ThumbURL}}
<div class="pcard-imgwrap">
<img class="pcard-img" src="{{.ThumbURL}}" alt="" loading="lazy">
</div>
{{end}}
<div class="pcard-body">
<h3 class="pcard-title">{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}</h3>
{{if .Summary}}<p class="pcard-summary">{{.Summary}}</p>{{end}}
<div class="pcard-meta">
<mark class="badge-format">{{.Format}}</mark>
{{if .Token}}<mark class="badge-token">&#128274;</mark>{{else}}<mark class="badge-public">public</mark>{{end}}
{{if .Hidden}}<mark class="badge-hidden">hidden</mark>{{end}}
<span class="pcard-date">{{.UpdatedAt.Format "01-02 15:04"}}</span>
</div>
<div class="pcard-actions" role="group">
<button type="button" class="outline" onclick="copyPasteLink('{{.Name}}','{{.Token}}', this)">Copy link</button>
<a href="/admin/bin/edit/{{.ID}}" role="button" class="outline">Edit</a>
<button type="button" class="outline" onclick="showBinQR('{{.Name}}', false)">QR</button>
<form method="post" action="/admin/bin/delete/{{.ID}}" onsubmit="return confirm('Delete paste {{.Name}}?')">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary">Del</button>
</form>
</div>
</div>
</article>
{{end}}
</div>
{{else}}
<div class="empty-state">
<span class="empty-icon">&#128196;</span>
<p>No pastes yet.</p>
<a href="/admin/bin/new">Create your first paste</a>
</div>
{{end}}
</main>
<dialog id="preview-dialog" class="preview-dialog">
<div class="preview-head">
<span class="preview-title" id="preview-title">Preview</span>
<div class="preview-actions">
<a id="preview-open" href="#" target="_blank" rel="noopener" role="button" class="outline btn-sm">Open &#8599;</a>
<button type="button" class="outline btn-sm" id="preview-expand" onclick="toggleExpand()" aria-label="Expand">&#8690;</button>
<button type="button" class="btn-sm preview-close" onclick="closePreview()" aria-label="Close">&#10005;</button>
</div>
</div>
<iframe id="preview-frame" class="preview-frame" src="about:blank" title="Paste preview"></iframe>
</dialog>
<dialog id="qr-dialog">
<article>
<header>
@@ -97,6 +100,65 @@
</article>
</dialog>
<script>
function previewURL(name, token) {
var u = '/bin/' + encodeURIComponent(name);
if (token) u += '/' + encodeURIComponent(token);
return u;
}
function openPreview(name, token, title) {
var dlg = document.getElementById('preview-dialog');
var url = previewURL(name, token);
document.getElementById('preview-frame').src = url;
document.getElementById('preview-open').href = url;
document.getElementById('preview-title').textContent = title || name;
dlg.classList.remove('expanded');
document.getElementById('preview-expand').innerHTML = '&#8690;';
document.getElementById('preview-expand').setAttribute('aria-label', 'Expand');
dlg.showModal();
}
function closePreview() {
document.getElementById('preview-dialog').close();
}
function toggleExpand() {
var dlg = document.getElementById('preview-dialog');
var expanded = dlg.classList.toggle('expanded');
var btn = document.getElementById('preview-expand');
btn.innerHTML = expanded ? '&#8689;' : '&#8690;';
btn.setAttribute('aria-label', expanded ? 'Shrink' : 'Expand');
}
function copyPasteLink(name, token, btn) {
var url = location.origin + previewURL(name, token);
navigator.clipboard.writeText(url).then(function() {
var orig = btn.textContent;
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = orig; }, 1500);
});
}
// Clicking anywhere on a card opens the preview, except on the action
// buttons. Data attributes avoid quoting issues with paste titles.
document.querySelectorAll('.js-preview').forEach(function(el) {
el.addEventListener('click', function(e) {
if (e.target.closest('.pcard-actions')) return;
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
});
el.addEventListener('keydown', function(e) {
if ((e.key === 'Enter' || e.key === ' ') && !e.target.closest('.pcard-actions')) {
e.preventDefault();
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
}
});
});
// Clear the iframe when the dialog is dismissed via Esc / backdrop / button.
document.getElementById('preview-dialog').addEventListener('close', function() {
document.getElementById('preview-frame').src = 'about:blank';
});
function showBinQR(name, full) {
var container = document.getElementById('qr-container');
var title = document.getElementById('qr-title');
+1 -1
View File
@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en" data-theme="light">
<html lang="en" data-theme="dark">
<head>
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<meta charset="utf-8">
+1 -1
View File
@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en" data-theme="light">
<html lang="en" data-theme="dark">
<head>
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<meta charset="utf-8">