Settings → Appearance: upload an image and every page header draws it as the dot matrix instead of The Creation of Adam, with a clickable focus point and a switch back to the built-in painting. The browser turns the image into a brightness grid; only that grid is saved as a setting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
159 lines
6.9 KiB
TypeScript
159 lines
6.9 KiB
TypeScript
"use client";
|
||
|
||
import { ImageIcon, ImageUpIcon, Loader2Icon } from "lucide-react";
|
||
import { useRouter } from "next/navigation";
|
||
import { useRef, useState } from "react";
|
||
import { toast } from "sonner";
|
||
import { DotPainting } from "@/components/hero/dot-painting";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||
import { type Backdrop, BACKDROP_MAX_CELLS } from "@/lib/backdrop";
|
||
|
||
/**
|
||
* Turns an image into a brightness grid like the built-in painting: at most BACKDROP_MAX_CELLS on
|
||
* the long side, transparency on white, contrast-stretched (2nd–98th percentile) to levels 0–f.
|
||
*/
|
||
async function toBackdrop(file: File): Promise<Backdrop> {
|
||
let img: ImageBitmap | HTMLCanvasElement = await createImageBitmap(file);
|
||
const s = Math.min(1, BACKDROP_MAX_CELLS / Math.max(img.width, img.height));
|
||
const w = Math.max(8, Math.round(img.width * s));
|
||
const h = Math.max(8, Math.round(img.height * s));
|
||
// Halve in steps first: one big downscale skips most pixels and looks noisy.
|
||
while (img.width > w * 2 && img.height > h * 2) {
|
||
const half = document.createElement("canvas");
|
||
half.width = Math.round(img.width / 2);
|
||
half.height = Math.round(img.height / 2);
|
||
half.getContext("2d")!.drawImage(img, 0, 0, half.width, half.height);
|
||
img = half;
|
||
}
|
||
const canvas = document.createElement("canvas");
|
||
canvas.width = w;
|
||
canvas.height = h;
|
||
const g = canvas.getContext("2d", { willReadFrequently: true })!;
|
||
g.fillStyle = "#fff";
|
||
g.fillRect(0, 0, w, h);
|
||
g.imageSmoothingQuality = "high";
|
||
g.drawImage(img, 0, 0, w, h);
|
||
const px = g.getImageData(0, 0, w, h).data;
|
||
const lum = new Float32Array(w * h);
|
||
for (let i = 0; i < lum.length; i++) lum[i] = 0.2126 * px[i * 4] + 0.7152 * px[i * 4 + 1] + 0.0722 * px[i * 4 + 2];
|
||
const sorted = Float32Array.from(lum).sort();
|
||
const lo = sorted[Math.floor(sorted.length * 0.02)];
|
||
const hi = sorted[Math.ceil(sorted.length * 0.98) - 1];
|
||
const range = Math.max(1, hi - lo);
|
||
let dots = "";
|
||
for (const l of lum) dots += Math.round(Math.min(1, Math.max(0, (l - lo) / range)) * 15).toString(16);
|
||
return { w, h, dots, focus: [0.5, 0.5] };
|
||
}
|
||
|
||
/** Upload a picture for the dot painting behind the page headers, pick its focus point, or go back to the built-in one. */
|
||
export function BackdropSettings({ initial }: { initial: Backdrop | null }) {
|
||
const router = useRouter();
|
||
const [saved, setSaved] = useState(initial);
|
||
// The picture being edited: the saved one, a new upload, or null (built-in painting).
|
||
const [draft, setDraft] = useState(initial);
|
||
const [reading, setReading] = useState(false);
|
||
const [busy, setBusy] = useState(false);
|
||
const input = useRef<HTMLInputElement>(null);
|
||
|
||
const dirty = draft?.dots !== saved?.dots || draft?.focus[0] !== saved?.focus[0] || draft?.focus[1] !== saved?.focus[1];
|
||
|
||
async function pick(file: File | undefined) {
|
||
if (!file) return;
|
||
setReading(true);
|
||
try {
|
||
setDraft(await toBackdrop(file));
|
||
} catch {
|
||
toast.error(`"${file.name}" couldn't be read as an image.`);
|
||
} finally {
|
||
setReading(false);
|
||
if (input.current) input.current.value = "";
|
||
}
|
||
}
|
||
|
||
async function save(next: Backdrop | null) {
|
||
setBusy(true);
|
||
try {
|
||
const res = await fetch("/api/settings/appearance", {
|
||
method: "PUT",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ backdrop: next }),
|
||
});
|
||
const body = await res.json().catch(() => ({}));
|
||
if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`);
|
||
setSaved(body.backdrop);
|
||
setDraft(body.backdrop);
|
||
toast.success(body.backdrop ? "Background picture saved" : "Back to The Creation of Adam");
|
||
router.refresh(); // the headers get the picture from the layout
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<Card>
|
||
<CardHeader>
|
||
<CardTitle>Background picture</CardTitle>
|
||
<CardDescription>
|
||
The dot matrix behind every page header. Upload your own picture and it is drawn in dots the same way, in the theme's colors. Only the dots are
|
||
saved, not the image, and they apply for everyone using this Kaname.
|
||
</CardDescription>
|
||
</CardHeader>
|
||
<CardContent className="flex flex-col gap-3 text-sm">
|
||
{draft ? (
|
||
<div className="flex flex-col gap-1.5">
|
||
<button
|
||
type="button"
|
||
className="relative w-full max-w-xl cursor-crosshair overflow-hidden rounded-lg bg-background ring-1 ring-foreground/10"
|
||
style={{ aspectRatio: `${draft.w} / ${draft.h}` }}
|
||
onClick={(e) => {
|
||
const r = e.currentTarget.getBoundingClientRect();
|
||
const f = (v: number) => Math.round(Math.min(1, Math.max(0, v)) * 1000) / 1000;
|
||
setDraft({ ...draft, focus: [f((e.clientX - r.left) / r.width), f((e.clientY - r.top) / r.height)] });
|
||
}}
|
||
aria-label="Set the focus point"
|
||
>
|
||
<DotPainting source={draft} anchor={draft.focus} className="absolute inset-0 size-full text-foreground/75" />
|
||
<span
|
||
className="absolute size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-primary bg-primary/30 shadow"
|
||
style={{ left: `${draft.focus[0] * 100}%`, top: `${draft.focus[1] * 100}%` }}
|
||
aria-hidden
|
||
/>
|
||
</button>
|
||
<p className="text-xs text-muted-foreground">Click the part that should stay in view when a header crops the picture.</p>
|
||
</div>
|
||
) : (
|
||
<p className="flex items-center gap-2 text-muted-foreground">
|
||
<ImageIcon className="size-4" />
|
||
<span>
|
||
Showing the built-in painting, Michelangelo's <i>The Creation of Adam</i>.
|
||
</span>
|
||
</p>
|
||
)}
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<input ref={input} type="file" accept="image/*" className="hidden" onChange={(e) => void pick(e.target.files?.[0])} />
|
||
<Button variant="outline" disabled={reading || busy} onClick={() => input.current?.click()}>
|
||
{reading ? <Loader2Icon className="animate-spin" /> : <ImageUpIcon />}
|
||
{draft ? "Choose another picture" : "Upload a picture"}
|
||
</Button>
|
||
{dirty && (
|
||
<>
|
||
<Button disabled={busy || reading} onClick={() => void save(draft)}>
|
||
Save
|
||
</Button>
|
||
<Button variant="ghost" disabled={busy} onClick={() => setDraft(saved)}>
|
||
Cancel
|
||
</Button>
|
||
</>
|
||
)}
|
||
{saved && !dirty && (
|
||
<Button variant="ghost" disabled={busy} onClick={() => void save(null)}>
|
||
Use the built-in painting
|
||
</Button>
|
||
)}
|
||
</div>
|
||
</CardContent>
|
||
</Card>
|
||
);
|
||
}
|