feat: every dashboard has its own wallpaper
The wallpaper and how much it is darkened move from the user to the dashboard. Migration 0007 copies what each user had to all their dashboards. Settings open for the dashboard you came from (/settings?d=<id>): its wallpaper is shown, a switch reaches the others, and "Back to dashboard" returns to it.
This commit is contained in:
+9
-5
@@ -86,6 +86,10 @@ export const dashboard = pgTable(
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
// null = bundled default wallpaper
|
||||
wallpaperUrl: text("wallpaper_url"),
|
||||
// percent of black over the wallpaper, see DEFAULT_WALLPAPER_DIM
|
||||
wallpaperDim: integer("wallpaper_dim").notNull().default(40),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
},
|
||||
(t) => [index("dashboard_user_id_idx").on(t.userId)]
|
||||
@@ -151,10 +155,6 @@ export const settings = pgTable("settings", {
|
||||
})
|
||||
.notNull()
|
||||
.default("duckduckgo"),
|
||||
// null = bundled default wallpaper
|
||||
wallpaperUrl: text("wallpaper_url"),
|
||||
// percent of black over the wallpaper, see DEFAULT_WALLPAPER_DIM
|
||||
wallpaperDim: integer("wallpaper_dim").notNull().default(40),
|
||||
// the big clock, see src/lib/clock.ts
|
||||
clockFont: text("clock_font", {
|
||||
enum: ["serif", "sans", "light", "rounded", "slab"],
|
||||
@@ -181,9 +181,13 @@ export const icon = pgTable(
|
||||
(t) => [index("icon_user_id_idx").on(t.userId)]
|
||||
)
|
||||
|
||||
/** The wallpaper that was uploaded for a dashboard, served from /api/wallpaper. */
|
||||
export const wallpaper = pgTable("wallpaper", {
|
||||
userId: text("user_id")
|
||||
dashboardId: uuid("dashboard_id")
|
||||
.primaryKey()
|
||||
.references(() => dashboard.id, { onDelete: "cascade" }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
mime: text("mime").notNull(),
|
||||
data: bytea("data").notNull(),
|
||||
|
||||
@@ -2,7 +2,6 @@ import { createServerFn } from "@tanstack/react-start"
|
||||
import { getRequestHeaders } from "@tanstack/react-start/server"
|
||||
import { and, asc, eq, inArray, sql } from "drizzle-orm"
|
||||
import { z } from "zod"
|
||||
import { DEFAULT_WALLPAPER_DIM } from "@/components/wallpaper"
|
||||
import { db } from "@/db"
|
||||
import { card, dashboard, link, settings, wallpaper } from "@/db/schema"
|
||||
import { auth, requireUser, signUpEnabled, ssoName } from "@/lib/auth"
|
||||
@@ -39,6 +38,14 @@ export const getAuthInfo = createServerFn({ method: "GET" }).handler(
|
||||
})
|
||||
)
|
||||
|
||||
/** What the pages need of a dashboard. */
|
||||
const shown = {
|
||||
id: dashboard.id,
|
||||
name: dashboard.name,
|
||||
wallpaperUrl: dashboard.wallpaperUrl,
|
||||
wallpaperDim: dashboard.wallpaperDim,
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the dashboard renders, or null when signed out. Without a
|
||||
* `dashboardId`, or with one that does not exist, it is the default dashboard.
|
||||
@@ -52,7 +59,7 @@ export const getDashboard = createServerFn({ method: "GET" })
|
||||
const userId = session.user.id
|
||||
const [dashboards, rows] = await Promise.all([
|
||||
db
|
||||
.select({ id: dashboard.id, name: dashboard.name })
|
||||
.select(shown)
|
||||
.from(dashboard)
|
||||
.where(eq(dashboard.userId, userId))
|
||||
.orderBy(asc(dashboard.createdAt)),
|
||||
@@ -66,12 +73,13 @@ export const getDashboard = createServerFn({ method: "GET" })
|
||||
...(await db
|
||||
.insert(dashboard)
|
||||
.values({ userId, name: "Home" })
|
||||
.returning({ id: dashboard.id, name: dashboard.name }))
|
||||
.returning(shown))
|
||||
)
|
||||
const s = rows.at(0) // no row until the first save
|
||||
const has = (id?: string | null) => dashboards.find((d) => d.id === id)?.id
|
||||
const defaultDashboardId = has(s?.defaultDashboardId) ?? dashboards[0].id
|
||||
const dashboardId = has(data?.dashboardId) ?? defaultDashboardId
|
||||
const find = (id?: string | null) => dashboards.find((d) => d.id === id)
|
||||
const byDefault = find(s?.defaultDashboardId) ?? dashboards[0]
|
||||
const current = find(data?.dashboardId) ?? byDefault
|
||||
const dashboardId = current.id
|
||||
const [cards, links] = await Promise.all([
|
||||
db
|
||||
.select({ id: card.id, name: card.name })
|
||||
@@ -102,15 +110,15 @@ export const getDashboard = createServerFn({ method: "GET" })
|
||||
user: { name: session.user.name, email: session.user.email },
|
||||
dashboards,
|
||||
dashboardId,
|
||||
defaultDashboardId,
|
||||
defaultDashboardId: byDefault.id,
|
||||
cards: cards.map((c) => ({
|
||||
...c,
|
||||
links: links.filter((l) => l.cardId === c.id),
|
||||
})),
|
||||
title: s?.title ?? "Dahoam",
|
||||
searchEngine: s?.searchEngine ?? "duckduckgo",
|
||||
wallpaperUrl: s?.wallpaperUrl ?? null,
|
||||
wallpaperDim: s?.wallpaperDim ?? DEFAULT_WALLPAPER_DIM,
|
||||
wallpaperUrl: current.wallpaperUrl,
|
||||
wallpaperDim: current.wallpaperDim,
|
||||
clockFont: s?.clockFont ?? "serif",
|
||||
clockStyle: s?.clockStyle ?? "solid",
|
||||
searxngUrl: process.env.SEARXNG_URL || null,
|
||||
@@ -255,11 +263,6 @@ export const saveSettings = createServerFn({ method: "POST" })
|
||||
title: z.string().trim().min(1).max(40),
|
||||
defaultDashboardId: z.uuid(),
|
||||
searchEngine: z.enum(ENGINES),
|
||||
// external image, the user's own upload, or null for the default
|
||||
wallpaperUrl: z
|
||||
.union([httpUrl, z.string().regex(/^\/api\/wallpaper\?v=\d+$/)])
|
||||
.nullable(),
|
||||
wallpaperDim: z.int().min(0).max(100),
|
||||
clockFont: z.enum(CLOCK_FONTS),
|
||||
clockStyle: z.enum(CLOCK_STYLES),
|
||||
})
|
||||
@@ -274,9 +277,31 @@ export const saveSettings = createServerFn({ method: "POST" })
|
||||
.insert(settings)
|
||||
.values({ ...data, userId: user.id })
|
||||
.onConflictDoUpdate({ target: settings.userId, set: data })
|
||||
})
|
||||
|
||||
/** The wallpaper of one dashboard. An upload goes to /api/wallpaper instead. */
|
||||
export const saveWallpaper = createServerFn({ method: "POST" })
|
||||
.validator(
|
||||
z
|
||||
.object({
|
||||
dashboardId: z.uuid(),
|
||||
// an image on the web, or null for the default photo
|
||||
wallpaperUrl: httpUrl.nullable().optional(),
|
||||
wallpaperDim: z.int().min(0).max(100).optional(),
|
||||
})
|
||||
.refine((patch) => Object.keys(patch).length > 1)
|
||||
)
|
||||
.handler(async ({ data: { dashboardId, ...patch } }) => {
|
||||
const user = await requireUser()
|
||||
const saved = await db
|
||||
.update(dashboard)
|
||||
.set(patch)
|
||||
.where(and(eq(dashboard.id, dashboardId), eq(dashboard.userId, user.id)))
|
||||
.returning({ id: dashboard.id })
|
||||
if (!saved.length) throw new Error("Unknown dashboard")
|
||||
// the stored upload is no longer shown
|
||||
if (data.wallpaperUrl !== undefined && !data.wallpaperUrl?.startsWith("/"))
|
||||
await db.delete(wallpaper).where(eq(wallpaper.userId, user.id))
|
||||
if (patch.wallpaperUrl !== undefined)
|
||||
await db.delete(wallpaper).where(eq(wallpaper.dashboardId, dashboardId))
|
||||
})
|
||||
|
||||
export const suggest = createServerFn({ method: "GET" })
|
||||
|
||||
+29
-14
@@ -1,7 +1,8 @@
|
||||
import { createFileRoute } from "@tanstack/react-router"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { z } from "zod"
|
||||
import { db } from "@/db"
|
||||
import { settings, wallpaper } from "@/db/schema"
|
||||
import { dashboard, wallpaper } from "@/db/schema"
|
||||
import { readImage, serveImage, userId } from "@/lib/upload"
|
||||
|
||||
const LIMITS = {
|
||||
@@ -11,6 +12,10 @@ const LIMITS = {
|
||||
maxMb: 10,
|
||||
}
|
||||
|
||||
/** ?d=<dashboard id>: every dashboard has its own wallpaper. */
|
||||
const dashboardOf = (request: Request) =>
|
||||
z.uuid().safeParse(new URL(request.url).searchParams.get("d")).data
|
||||
|
||||
export const Route = createFileRoute("/api/wallpaper")({
|
||||
server: {
|
||||
handlers: {
|
||||
@@ -18,32 +23,42 @@ export const Route = createFileRoute("/api/wallpaper")({
|
||||
GET: async ({ request }) => {
|
||||
const id = await userId(request)
|
||||
if (!id) return new Response("Unauthorized", { status: 401 })
|
||||
const d = dashboardOf(request)
|
||||
if (!d) return new Response("Not found", { status: 404 })
|
||||
return serveImage(
|
||||
(
|
||||
await db.select().from(wallpaper).where(eq(wallpaper.userId, id))
|
||||
await db
|
||||
.select()
|
||||
.from(wallpaper)
|
||||
.where(
|
||||
and(eq(wallpaper.dashboardId, d), eq(wallpaper.userId, id))
|
||||
)
|
||||
).at(0)
|
||||
)
|
||||
},
|
||||
POST: async ({ request }) => {
|
||||
const image = await readImage(request, LIMITS)
|
||||
if (image instanceof Response) return image
|
||||
const wallpaperUrl = `/api/wallpaper?v=${Date.now()}`
|
||||
await db.transaction(async (tx) => {
|
||||
const d = dashboardOf(request)
|
||||
if (!d) return new Response("Not found", { status: 404 })
|
||||
const wallpaperUrl = `/api/wallpaper?d=${d}&v=${Date.now()}`
|
||||
const saved = await db.transaction(async (tx) => {
|
||||
const mine = await tx
|
||||
.update(dashboard)
|
||||
.set({ wallpaperUrl })
|
||||
.where(and(eq(dashboard.id, d), eq(dashboard.userId, image.userId)))
|
||||
.returning({ id: dashboard.id })
|
||||
if (!mine.length) return false
|
||||
await tx
|
||||
.insert(wallpaper)
|
||||
.values(image)
|
||||
.values({ ...image, dashboardId: d })
|
||||
.onConflictDoUpdate({
|
||||
target: wallpaper.userId,
|
||||
target: wallpaper.dashboardId,
|
||||
set: { mime: image.mime, data: image.data },
|
||||
})
|
||||
await tx
|
||||
.insert(settings)
|
||||
.values({ userId: image.userId, wallpaperUrl })
|
||||
.onConflictDoUpdate({
|
||||
target: settings.userId,
|
||||
set: { wallpaperUrl },
|
||||
})
|
||||
return true
|
||||
})
|
||||
if (!saved) return new Response("Not found", { status: 404 })
|
||||
return Response.json({ wallpaperUrl })
|
||||
},
|
||||
},
|
||||
|
||||
+15
-4
@@ -50,6 +50,8 @@ function Dashboard() {
|
||||
const [link, setLink] = useState<LinkTarget | null>(null)
|
||||
const [card, setCard] = useState<CardTarget | null>(null)
|
||||
|
||||
// settings open for this dashboard: its wallpaper, and back to it
|
||||
const here = { d: data.dashboardId }
|
||||
// the server makes sure there is always a card
|
||||
const addLink = () => setLink({ cardId: data.cards[0].id })
|
||||
|
||||
@@ -93,7 +95,7 @@ function Dashboard() {
|
||||
<Plus className="size-5" />
|
||||
</Button>
|
||||
<Button asChild variant="ghost" iconOnly className={onWallpaper}>
|
||||
<Link to="/settings" aria-label="Settings">
|
||||
<Link to="/settings" search={here} aria-label="Settings">
|
||||
<Settings2 className="size-5" />
|
||||
</Link>
|
||||
</Button>
|
||||
@@ -135,12 +137,16 @@ function Dashboard() {
|
||||
label: "Add dashboard",
|
||||
icon: <LayoutDashboard className="size-4" />,
|
||||
run: () =>
|
||||
router.navigate({ to: "/settings", hash: "dashboards" }),
|
||||
router.navigate({
|
||||
to: "/settings",
|
||||
search: here,
|
||||
hash: "dashboards",
|
||||
}),
|
||||
},
|
||||
{
|
||||
label: "Settings",
|
||||
icon: <Settings2 className="size-4" />,
|
||||
run: () => router.navigate({ to: "/settings" }),
|
||||
run: () => router.navigate({ to: "/settings", search: here }),
|
||||
},
|
||||
{
|
||||
label: "Sign out",
|
||||
@@ -180,7 +186,12 @@ function Dashboard() {
|
||||
</span>
|
||||
)}
|
||||
<Button asChild variant="ghost" iconOnly className={onWallpaper}>
|
||||
<Link to="/settings" hash="wallpaper" aria-label="Change wallpaper">
|
||||
<Link
|
||||
to="/settings"
|
||||
search={here}
|
||||
hash="wallpaper"
|
||||
aria-label="Change wallpaper"
|
||||
>
|
||||
<Pencil className="size-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
|
||||
+61
-12
@@ -36,6 +36,7 @@ import {
|
||||
getDashboard,
|
||||
saveDashboard,
|
||||
saveSettings,
|
||||
saveWallpaper,
|
||||
} from "@/lib/dashboard.functions"
|
||||
import { ENGINES, ENGINE_NAMES } from "@/lib/search"
|
||||
import type { Engine } from "@/lib/search"
|
||||
@@ -74,13 +75,18 @@ import { Spinner } from "@/vendor/collabry/components/Spinner/Spinner"
|
||||
import { cn } from "@/vendor/collabry/lib/cn"
|
||||
|
||||
export const Route = createFileRoute("/settings")({
|
||||
loader: async () => {
|
||||
const data = await getDashboard()
|
||||
// ?d=<dashboard id>: the dashboard you came from, and whose wallpaper is shown
|
||||
validateSearch: (search): { d?: string } =>
|
||||
typeof search.d === "string" ? { d: search.d } : {},
|
||||
loaderDeps: ({ search }) => search,
|
||||
loader: async ({ deps }) => {
|
||||
const data = await getDashboard({ data: { dashboardId: deps.d } })
|
||||
if (!data) throw redirect({ to: "/login" })
|
||||
return data
|
||||
},
|
||||
head: () => ({ meta: [{ title: "Settings" }] }),
|
||||
component: Settings,
|
||||
// a new key per dashboard: the page starts again with that dashboard's wallpaper
|
||||
component: () => <Settings key={Route.useLoaderData().dashboardId} />,
|
||||
})
|
||||
|
||||
const SECTIONS = [
|
||||
@@ -145,14 +151,20 @@ function Settings() {
|
||||
title?: string
|
||||
defaultDashboardId?: string
|
||||
searchEngine?: Engine
|
||||
wallpaperUrl?: string | null
|
||||
wallpaperDim?: number
|
||||
clockFont?: ClockFont
|
||||
clockStyle?: ClockStyle
|
||||
}) => run(() => saveSettings({ data: patch }))
|
||||
// the wallpaper belongs to the dashboard that is chosen in its section
|
||||
const saveWall = (patch: {
|
||||
wallpaperUrl?: string | null
|
||||
wallpaperDim?: number
|
||||
}) =>
|
||||
run(() =>
|
||||
saveWallpaper({ data: { dashboardId: data.dashboardId, ...patch } })
|
||||
)
|
||||
const upload = (image: File) =>
|
||||
run(async () => {
|
||||
const res = await fetch("/api/wallpaper", {
|
||||
const res = await fetch(`/api/wallpaper?d=${data.dashboardId}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": image.type },
|
||||
body: image,
|
||||
@@ -170,7 +182,7 @@ function Settings() {
|
||||
<Logo className="size-5 text-fg" />
|
||||
<span className="min-w-0 truncate font-bold">{data.title}</span>
|
||||
<Button asChild size="sm" className="ml-auto">
|
||||
<Link to="/">
|
||||
<Link to="/" search={{ d: data.dashboardId }}>
|
||||
<ArrowLeft size={14} aria-hidden /> Back to dashboard
|
||||
</Link>
|
||||
</Button>
|
||||
@@ -221,6 +233,7 @@ function Settings() {
|
||||
<Link
|
||||
to="/settings"
|
||||
hash={id}
|
||||
search
|
||||
// without this every link counts as the current page
|
||||
activeOptions={{ includeHash: true }}
|
||||
>
|
||||
@@ -446,10 +459,46 @@ function Settings() {
|
||||
<SettingsSectionHeader>
|
||||
<SettingsSectionTitle>Wallpaper</SettingsSectionTitle>
|
||||
<SettingsSectionDescription>
|
||||
The picture behind your dashboard. Upload one (JPEG, PNG,
|
||||
WebP or AVIF, up to 10 MB) or use any image on the web.
|
||||
The picture behind a dashboard, every dashboard has its own.
|
||||
Upload one (JPEG, PNG, WebP or AVIF, up to 10 MB) or use any
|
||||
image on the web.
|
||||
</SettingsSectionDescription>
|
||||
</SettingsSectionHeader>
|
||||
{data.dashboards.length > 1 && (
|
||||
<SettingsRow>
|
||||
<SettingsRowText>
|
||||
<div
|
||||
id="settings-wallpaper-of"
|
||||
className="leading-tight font-bold"
|
||||
>
|
||||
Dashboard
|
||||
</div>
|
||||
<SettingsRowDescription>
|
||||
Whose wallpaper you change here.
|
||||
</SettingsRowDescription>
|
||||
</SettingsRowText>
|
||||
<SettingsRowControl>
|
||||
<SegmentedControl
|
||||
aria-labelledby="settings-wallpaper-of"
|
||||
size="md"
|
||||
value={data.dashboardId}
|
||||
onValueChange={(d) =>
|
||||
router.navigate({
|
||||
to: "/settings",
|
||||
search: { d },
|
||||
hash: "wallpaper",
|
||||
})
|
||||
}
|
||||
>
|
||||
{data.dashboards.map((d) => (
|
||||
<SegmentedControlItem key={d.id} value={d.id}>
|
||||
{d.name}
|
||||
</SegmentedControlItem>
|
||||
))}
|
||||
</SegmentedControl>
|
||||
</SettingsRowControl>
|
||||
</SettingsRow>
|
||||
)}
|
||||
<SettingsRow stacked>
|
||||
<div className="flex flex-wrap items-start gap-x-6 gap-y-4">
|
||||
<div className="relative w-60 flex-none overflow-hidden rounded-xl border border-line">
|
||||
@@ -483,7 +532,7 @@ function Settings() {
|
||||
const url = e.target.value.trim()
|
||||
if (!url || url === data.wallpaperUrl) return
|
||||
if (e.target.checkValidity())
|
||||
void save({ wallpaperUrl: url })
|
||||
void saveWall({ wallpaperUrl: url })
|
||||
else
|
||||
setError(
|
||||
"The image address must start with http:// or https://"
|
||||
@@ -519,7 +568,7 @@ function Settings() {
|
||||
<Button
|
||||
variant="ghost"
|
||||
disabled={status === "saving" || !data.wallpaperUrl}
|
||||
onClick={() => save({ wallpaperUrl: null })}
|
||||
onClick={() => saveWall({ wallpaperUrl: null })}
|
||||
>
|
||||
Use default
|
||||
</Button>
|
||||
@@ -551,7 +600,7 @@ function Settings() {
|
||||
// one save when the slider rests, not one per step
|
||||
clearTimeout(dimSave.current)
|
||||
dimSave.current = setTimeout(
|
||||
() => save({ wallpaperDim }),
|
||||
() => saveWall({ wallpaperDim }),
|
||||
400
|
||||
)
|
||||
}}
|
||||
|
||||
Reference in New Issue
Block a user