Custom background picture for the dot matrix headers
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>
This commit is contained in:
1 parent
422e46bf65
commit
02756ddf90
11 files changed
+309
-18
No files matched your search
@@ -6,6 +6,15 @@ step 1 (Hugging Face downloader) is released as a minor version.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.18.0] - 2026-11-02
|
||||
|
||||
### Added
|
||||
|
||||
- **Your own background picture** (Settings → Appearance): upload an image and every page header
|
||||
draws it as the dot matrix instead of *The Creation of Adam*; click the preview to choose the part
|
||||
that stays in view. The browser turns it into dots, so only those are saved (not the image).
|
||||
**Use the built-in painting** switches back.
|
||||
|
||||
## [0.17.0] - 2026-11-02
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -3,20 +3,22 @@ import { redirect } from "next/navigation";
|
||||
import { auth, signOut } from "@/auth";
|
||||
import { AppNav } from "@/components/app-nav";
|
||||
import { CommandPalette, CommandPaletteButton } from "@/components/command-palette";
|
||||
import { BackdropProvider } from "@/components/hero/dot-painting";
|
||||
import { LabelSettingsProvider } from "@/components/labels";
|
||||
import { UserMenu } from "@/components/user-menu";
|
||||
import { WorkerIndicator } from "@/components/worker-indicator";
|
||||
import { getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
||||
import { getBackdrop, getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||
const session = await auth();
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
const [worker, fileRoles, recommendedRoles] = await Promise.all([
|
||||
const [worker, fileRoles, recommendedRoles, backdrop] = await Promise.all([
|
||||
getWorkerStatus(),
|
||||
getFileRoleStyles(),
|
||||
getRecommendedRoles(),
|
||||
getBackdrop(),
|
||||
]);
|
||||
|
||||
return (
|
||||
@@ -46,7 +48,9 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
|
||||
</header>
|
||||
<CommandPalette />
|
||||
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
|
||||
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
|
||||
<BackdropProvider backdrop={backdrop}>
|
||||
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
|
||||
</BackdropProvider>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getBackdrop } from "@/lib/settings";
|
||||
import { BackdropSettings } from "./backdrop-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Appearance · Settings" };
|
||||
|
||||
export default async function AppearanceSettingsPage() {
|
||||
return <BackdropSettings initial={await getBackdrop()} />;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { DownloadIcon, PaletteIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { PageHero } from "@/components/hero/page-hero";
|
||||
import { SettingsNav } from "./settings-nav";
|
||||
|
||||
@@ -6,13 +6,14 @@ const SECTIONS = [
|
||||
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
|
||||
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
|
||||
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
|
||||
{ href: "/settings/appearance", label: "Appearance", icon: <PaletteIcon className="size-4" /> },
|
||||
];
|
||||
|
||||
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
|
||||
return (
|
||||
<PageHero
|
||||
title="Settings"
|
||||
description="File labels, tags, and how Kaname downloads and scans models."
|
||||
description="File labels, tags, how Kaname downloads and scans models, and the background picture."
|
||||
painting={{ view: 0.4, focus: [0.5, 0.43], anchor: [0.7, 0.4] }}
|
||||
>
|
||||
<div className="grid items-start gap-4 md:grid-cols-[200px_minmax(0,1fr)]">
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { getBackdrop, saveBackdrop, SettingsError } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Appearance: the custom picture behind the page headers (null for the built-in painting). */
|
||||
export const GET = withAuth(async () => NextResponse.json({ backdrop: await getBackdrop() }));
|
||||
|
||||
const Body = z.object({ backdrop: z.unknown() });
|
||||
|
||||
export const PUT = withAuth(async (req) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
return NextResponse.json({ backdrop: await saveBackdrop(body.backdrop ?? null) });
|
||||
} catch (err) {
|
||||
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
LibraryIcon,
|
||||
MonitorIcon,
|
||||
MoonIcon,
|
||||
PaletteIcon,
|
||||
PlusIcon,
|
||||
ScanSearchIcon,
|
||||
SearchIcon,
|
||||
@@ -98,6 +99,7 @@ export function CommandPaletteDialog({ open, setOpen }: { open: boolean; setOpen
|
||||
{ id: "s:speed", group: "Settings", title: "Download speed limit", icon: DownloadIcon, hint: "Downloads", keywords: "bandwidth mb/s", run: go("/settings/downloads") },
|
||||
{ id: "s:recommended", group: "Settings", title: "Recommended files", icon: DownloadIcon, hint: "Downloads", keywords: "mmproj mtp template quant", run: go("/settings/downloads") },
|
||||
{ id: "s:scan", group: "Settings", title: "Models folder scan schedule", icon: ScanSearchIcon, hint: "Downloads", keywords: "daily weekly monthly nas", run: go("/settings/downloads#scan") },
|
||||
{ id: "s:backdrop", group: "Settings", title: "Background picture", icon: PaletteIcon, hint: "Appearance", keywords: "image upload dot matrix painting header wallpaper", run: go("/settings/appearance") },
|
||||
];
|
||||
for (const m of index?.models ?? []) {
|
||||
out.push({ id: `m:${m.id}`, group: "Models", title: m.repoId, hint: m.quants.join(", ") || m.status, icon: BoxIcon, keywords: `${m.status} ${m.tags.join(" ")}`, run: go(`/${m.repoId}`) });
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { createContext, useContext, useEffect, useMemo, useRef } from "react";
|
||||
import type { Backdrop } from "@/lib/backdrop";
|
||||
|
||||
const SPACING = 6; // CSS px between dot centres
|
||||
|
||||
type Grid = { w: number; h: number; levels: Uint8Array };
|
||||
const parse = (dots: string) => Uint8Array.from(dots, (c) => parseInt(c, 16));
|
||||
|
||||
// The brightness grid (26 KB of text) is its own chunk, shared by every page and parsed once per
|
||||
// tab. Imported statically, it was copied into each page's chunk.
|
||||
@@ -13,34 +15,51 @@ const loadGrid = () =>
|
||||
(grid ??= import("./adam-dots").then(({ ADAM_DOTS, ADAM_H, ADAM_W }) => ({
|
||||
w: ADAM_W,
|
||||
h: ADAM_H,
|
||||
levels: Uint8Array.from(ADAM_DOTS, (c) => parseInt(c, 16)),
|
||||
levels: parse(ADAM_DOTS),
|
||||
})));
|
||||
|
||||
const BackdropContext = createContext<Backdrop | null>(null);
|
||||
|
||||
/** Provides the custom picture from Settings → Appearance (null for the built-in painting). */
|
||||
export function BackdropProvider({ backdrop, children }: { backdrop: Backdrop | null; children: React.ReactNode }) {
|
||||
return <BackdropContext.Provider value={backdrop}>{children}</BackdropContext.Provider>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Creation of Adam as a dot matrix. `view` is the horizontal slice of the painting (0–1) that
|
||||
* fills the box (at least covering it), placed so `focus` (the hands) lands at `anchor` (x, y as
|
||||
* fractions of the box) as far as the painting's edges allow. Dots use the element's text color; bright parts of the painting get big dots in
|
||||
* dark mode, dark parts in light mode, so it reads as the painting either way.
|
||||
*
|
||||
* With a custom picture (Settings → Appearance, or `source`), that picture covers the box instead,
|
||||
* with its own focus point at `anchor`; `view` and `focus` only apply to the built-in painting.
|
||||
*/
|
||||
export function DotPainting({
|
||||
className,
|
||||
view = 0.7,
|
||||
focus = [0.48, 0.42],
|
||||
anchor = [0.68, 0.5],
|
||||
source,
|
||||
}: {
|
||||
className?: string;
|
||||
view?: number;
|
||||
focus?: [number, number];
|
||||
anchor?: [number, number];
|
||||
/** Draw this picture instead of the one from the settings (the Appearance preview). */
|
||||
source?: Backdrop | null;
|
||||
}) {
|
||||
const ref = useRef<HTMLCanvasElement>(null);
|
||||
const fromSettings = useContext(BackdropContext);
|
||||
const custom = source !== undefined ? source : fromSettings;
|
||||
const customGrid = useMemo(() => (custom ? { w: custom.w, h: custom.h, levels: parse(custom.dots) } : null), [custom]);
|
||||
|
||||
const [fx, fy] = focus;
|
||||
const [fx, fy] = custom ? custom.focus : focus;
|
||||
const [ax, ay] = anchor;
|
||||
const v = custom ? 1 : view;
|
||||
useEffect(() => {
|
||||
const canvas = ref.current;
|
||||
if (!canvas) return;
|
||||
let data: Grid | null = null;
|
||||
let data: Grid | null = customGrid;
|
||||
let cancelled = false;
|
||||
let frame = 0;
|
||||
// What the canvas shows (size, pixel ratio, theme, color): a drawing takes tens of ms, so skip it
|
||||
@@ -65,7 +84,7 @@ export function DotPainting({
|
||||
g.clearRect(0, 0, width, height);
|
||||
g.fillStyle = color;
|
||||
// CSS px per grid cell: `view` of the painting's width fills the box (at least covering it).
|
||||
const scale = Math.max(width / (view * w), height / h);
|
||||
const scale = Math.max(width / (v * w), height / h);
|
||||
const offX = ax * width - fx * w * scale;
|
||||
const offY = ay * height - fy * h * scale;
|
||||
const clampOff = (o: number, box: number, size: number) => Math.min(0, Math.max(box - size, o));
|
||||
@@ -76,8 +95,8 @@ export function DotPainting({
|
||||
const iy = Math.min(h - 1, Math.max(0, Math.floor((y - oy) / scale)));
|
||||
for (let x = SPACING / 2; x < width; x += SPACING) {
|
||||
const ix = Math.min(w - 1, Math.max(0, Math.floor((x - ox) / scale)));
|
||||
const v = levels[iy * w + ix] / 15;
|
||||
const r = maxR * (dark ? v : 1 - v);
|
||||
const level = levels[iy * w + ix] / 15;
|
||||
const r = maxR * (dark ? level : 1 - level);
|
||||
if (r < 0.35) continue;
|
||||
g.beginPath();
|
||||
g.arc(x, y, r, 0, Math.PI * 2);
|
||||
@@ -89,11 +108,13 @@ export function DotPainting({
|
||||
const schedule = () => {
|
||||
if (!frame) frame = requestAnimationFrame(draw);
|
||||
};
|
||||
void loadGrid().then((g) => {
|
||||
if (cancelled) return;
|
||||
data = g;
|
||||
draw();
|
||||
});
|
||||
if (data) draw();
|
||||
else
|
||||
void loadGrid().then((g) => {
|
||||
if (cancelled) return;
|
||||
data = g;
|
||||
draw();
|
||||
});
|
||||
const resize = new ResizeObserver(schedule);
|
||||
resize.observe(canvas);
|
||||
// next-themes switches the class on <html>.
|
||||
@@ -105,7 +126,7 @@ export function DotPainting({
|
||||
resize.disconnect();
|
||||
theme.disconnect();
|
||||
};
|
||||
}, [view, fx, fy, ax, ay]);
|
||||
}, [customGrid, v, fx, fy, ax, ay]);
|
||||
|
||||
return <canvas ref={ref} aria-hidden className={className} />;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { parseBackdrop } from "./backdrop";
|
||||
|
||||
const valid = { w: 10, h: 8, dots: "0123456789abcdef".repeat(5), focus: [0.3, 0.7] };
|
||||
|
||||
test("parseBackdrop keeps a valid grid", () => {
|
||||
assert.deepEqual(parseBackdrop(valid), valid);
|
||||
});
|
||||
|
||||
test("parseBackdrop rejects broken grids", () => {
|
||||
assert.equal(parseBackdrop(null), null);
|
||||
assert.equal(parseBackdrop({ ...valid, dots: valid.dots.slice(1) }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, dots: valid.dots.replace("a", "g") }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, w: 4, dots: "0".repeat(32) }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, w: 241, dots: "0".repeat(241 * 8) }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, focus: [0.5, 1.5] }), null);
|
||||
assert.equal(parseBackdrop({ ...valid, focus: [0.5] }), null);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// A custom picture for the dot painting behind every page header (Settings → Appearance). Stored as
|
||||
// a brightness grid like the built-in painting; the uploaded photo itself is never sent or kept.
|
||||
|
||||
export const BACKDROP_KEY = "appearance.backdrop";
|
||||
/** Longest side of the grid, in cells. */
|
||||
export const BACKDROP_MAX_CELLS = 240;
|
||||
|
||||
export type Backdrop = {
|
||||
w: number;
|
||||
h: number;
|
||||
/** w×h brightness levels 0–f, row by row. */
|
||||
dots: string;
|
||||
/** The point (x, y as fractions of the picture) kept in view when the header crops it. */
|
||||
focus: [number, number];
|
||||
};
|
||||
|
||||
const fraction = (v: unknown) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
|
||||
const side = (v: unknown) => Number.isInteger(v) && (v as number) >= 8 && (v as number) <= BACKDROP_MAX_CELLS;
|
||||
|
||||
/** The backdrop if `v` is a valid one, else null. */
|
||||
export function parseBackdrop(v: unknown): Backdrop | null {
|
||||
if (!v || typeof v !== "object") return null;
|
||||
const { w, h, dots, focus } = v as Record<string, unknown>;
|
||||
if (!side(w) || !side(h)) return null;
|
||||
if (typeof dots !== "string" || dots.length !== (w as number) * (h as number) || !/^[0-9a-f]*$/.test(dots)) return null;
|
||||
if (!Array.isArray(focus) || focus.length !== 2 || !focus.every(fraction)) return null;
|
||||
return { w: w as number, h: h as number, dots, focus: [focus[0], focus[1]] };
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import "server-only";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { settings, workerState } from "@/lib/db/schema";
|
||||
import { type Backdrop, BACKDROP_KEY, parseBackdrop } from "@/lib/backdrop";
|
||||
import { isLabelColor } from "@/lib/colors";
|
||||
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
|
||||
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
|
||||
@@ -140,3 +141,19 @@ export async function getScanStatus(): Promise<ScanStatus> {
|
||||
nextScanAt: next?.getTime() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The custom picture behind the page headers (Settings → Appearance), or null for the built-in painting. */
|
||||
export async function getBackdrop(): Promise<Backdrop | null> {
|
||||
return parseBackdrop(await read<unknown>(BACKDROP_KEY));
|
||||
}
|
||||
|
||||
export async function saveBackdrop(input: unknown): Promise<Backdrop | null> {
|
||||
if (input == null) {
|
||||
await db().delete(settings).where(eq(settings.key, BACKDROP_KEY));
|
||||
return null;
|
||||
}
|
||||
const backdrop = parseBackdrop(input);
|
||||
if (!backdrop) throw new SettingsError("That picture couldn't be read. Try another image.");
|
||||
await write(BACKDROP_KEY, backdrop);
|
||||
return backdrop;
|
||||
}
|
||||
Reference in new issue
Block a user