Files
dahoam/src/routes/settings.tsx
T
niklas dacd374946
images / check (push) Successful in 32s
images / image (push) Successful in 15s
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.
2026-11-18 18:03:10 +01:00

651 lines
25 KiB
TypeScript

import { useRef, useState } from "react"
import type { ComponentProps } from "react"
import {
Link,
createFileRoute,
redirect,
useLocation,
useRouter,
} from "@tanstack/react-router"
import {
ArrowLeft,
Check,
CircleUser,
Clock,
Image,
LayoutDashboard,
LogOut,
Plus,
Search,
SlidersHorizontal,
Trash2,
Upload,
} from "lucide-react"
import { Logo } from "@/components/logo"
import { DEFAULT_WALLPAPER } from "@/components/wallpaper"
import { authClient } from "@/lib/auth-client"
import {
CLOCK_FONTS,
CLOCK_FONT_NAMES,
CLOCK_STYLES,
CLOCK_STYLE_NAMES,
} from "@/lib/clock"
import type { ClockFont, ClockStyle } from "@/lib/clock"
import {
deleteDashboard,
getDashboard,
saveDashboard,
saveSettings,
saveWallpaper,
} from "@/lib/dashboard.functions"
import { ENGINES, ENGINE_NAMES } from "@/lib/search"
import type { Engine } from "@/lib/search"
import { Button } from "@/vendor/collabry/components/Button/Button"
import {
Field,
FieldDescription,
FieldLabel,
Input,
} from "@/vendor/collabry/components/Field/Field"
import {
PageActions,
PageDescription,
PageHeader,
PageHeading,
PageTitle,
} from "@/vendor/collabry/components/Layout/Layout"
import {
SegmentedControl,
SegmentedControlItem,
} from "@/vendor/collabry/components/SegmentedControl/SegmentedControl"
import {
SettingsNav,
SettingsNavItem,
SettingsRow,
SettingsRowControl,
SettingsRowDescription,
SettingsRowLabel,
SettingsRowText,
SettingsSection,
SettingsSectionDescription,
SettingsSectionHeader,
SettingsSectionTitle,
} from "@/vendor/collabry/components/Settings/Settings"
import { Spinner } from "@/vendor/collabry/components/Spinner/Spinner"
import { cn } from "@/vendor/collabry/lib/cn"
export const Route = createFileRoute("/settings")({
// ?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" }] }),
// a new key per dashboard: the page starts again with that dashboard's wallpaper
component: () => <Settings key={Route.useLoaderData().dashboardId} />,
})
const SECTIONS = [
{ id: "general", label: "General", icon: SlidersHorizontal },
{ id: "dashboards", label: "Dashboards", icon: LayoutDashboard },
{ id: "clock", label: "Clock", icon: Clock },
{ id: "search", label: "Search", icon: Search },
{ id: "wallpaper", label: "Wallpaper", icon: Image },
{ id: "account", label: "Account", icon: CircleUser },
]
// the nav links jump to a section; keep its title clear of the window edge
const section = "[&>section]:scroll-mt-24"
/** A name that is saved when the field is left. An empty one goes back to what it was. */
function NameInput({
value,
onSave,
...props
}: { value: string; onSave: (name: string) => void } & ComponentProps<
typeof Input
>) {
return (
<Input
className="w-64"
defaultValue={value}
maxLength={40}
onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
onBlur={(e) => {
const name = e.target.value.trim()
if (name && name !== value) onSave(name)
else e.target.value = value
}}
{...props}
/>
)
}
function Settings() {
const data = Route.useLoaderData()
const router = useRouter()
const hash = useLocation({ select: (l) => l.hash }) || SECTIONS[0].id
const file = useRef<HTMLInputElement>(null)
const [status, setStatus] = useState<"idle" | "saving" | "saved">("idle")
const [error, setError] = useState("")
// follows the slider at once, the save comes a moment later
const [dim, setDim] = useState(data.wallpaperDim)
const dimSave = useRef<ReturnType<typeof setTimeout>>(undefined)
// deleting a dashboard deletes its cards and links, so it takes a second click
const [confirming, setConfirming] = useState<string | null>(null)
// Every control saves on its own. `action` returns a message when it failed.
const run = async (action: () => Promise<string | void>) => {
setError("")
setStatus("saving")
const failure = await action().catch(() => "Could not save. Try again.")
await router.invalidate()
setError(failure || "")
setStatus(failure ? "idle" : "saved")
}
const save = (patch: {
title?: string
defaultDashboardId?: string
searchEngine?: Engine
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?d=${data.dashboardId}`, {
method: "POST",
headers: { "Content-Type": image.type },
body: image,
})
if (!res.ok) return res.text()
})
const uploaded = !!data.wallpaperUrl?.startsWith("/")
return (
// A page of its own: solid Collabry surfaces, no wallpaper behind it
<div className="min-h-svh bg-app">
<header className="sticky top-0 z-10 border-b border-line-shell bg-frame px-4 sm:px-8">
<div className="mx-auto flex h-14 max-w-[1040px] items-center gap-3">
<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="/" search={{ d: data.dashboardId }}>
<ArrowLeft size={14} aria-hidden /> Back to dashboard
</Link>
</Button>
</div>
</header>
<main className="px-4 py-10 sm:px-8 sm:py-12">
<div className="mx-auto flex max-w-[1040px] flex-col gap-7">
<PageHeader>
<PageHeading>
<PageTitle className="font-serif text-4xl font-normal text-fg-strong">
Settings
</PageTitle>
<PageDescription>
Changes are saved as you make them.
</PageDescription>
</PageHeading>
<PageActions className="min-h-5 text-xs font-bold">
{error && (
<span role="alert" className="text-danger-fg">
{error}
</span>
)}
<span
role="status"
className={cn(
"flex items-center gap-1.5",
status === "saved" ? "text-success-fg" : "text-fg-subtle"
)}
>
{status === "saving" && (
<>
<Spinner size={14} /> Saving …
</>
)}
{status === "saved" && (
<>
<Check size={14} strokeWidth={2.5} aria-hidden /> Saved
</>
)}
</span>
</PageActions>
</PageHeader>
<div className="flex flex-wrap items-start gap-x-10 gap-y-6">
<SettingsNav aria-label="Settings" className="lg:sticky lg:top-24">
{SECTIONS.map(({ id, label, icon: Icon }) => (
<SettingsNavItem key={id} asChild active={hash === id}>
<Link
to="/settings"
hash={id}
search
// without this every link counts as the current page
activeOptions={{ includeHash: true }}
>
<Icon size={18} strokeWidth={1.75} aria-hidden />
{label}
</Link>
</SettingsNavItem>
))}
</SettingsNav>
<div className="flex max-w-[760px] min-w-0 flex-[999_1_520px] flex-col gap-5">
<SettingsSection id="general" className={section}>
<SettingsSectionHeader>
<SettingsSectionTitle>General</SettingsSectionTitle>
<SettingsSectionDescription>
How this start page is called.
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsRow>
<SettingsRowText>
<SettingsRowLabel htmlFor="settings-title">
Title
</SettingsRowLabel>
<SettingsRowDescription>
Shown at the top left of every dashboard.
</SettingsRowDescription>
</SettingsRowText>
<SettingsRowControl>
<NameInput
id="settings-title"
value={data.title}
onSave={(title) => save({ title })}
/>
</SettingsRowControl>
</SettingsRow>
</SettingsSection>
<SettingsSection id="dashboards" className={section}>
<SettingsSectionHeader>
<SettingsSectionTitle>Dashboards</SettingsSectionTitle>
<SettingsSectionDescription>
Each dashboard has its own cards, for example Home and Work.
With more than one, you switch between them at the top of
the dashboard. The default one opens when you sign in.
</SettingsSectionDescription>
</SettingsSectionHeader>
{data.dashboards.map((d) => {
const isDefault = d.id === data.defaultDashboardId
return (
<SettingsRow key={d.id}>
<SettingsRowText>
<NameInput
aria-label="Dashboard name"
value={d.name}
onSave={(name) =>
run(() =>
saveDashboard({ data: { id: d.id, name } })
)
}
/>
</SettingsRowText>
<SettingsRowControl className="flex flex-wrap gap-2">
<Button
disabled={isDefault}
onClick={() => save({ defaultDashboardId: d.id })}
>
{isDefault && <Check size={15} />}
{isDefault ? "Default" : "Make default"}
</Button>
<Button
variant={
confirming === d.id ? "danger" : "danger-outline"
}
disabled={data.dashboards.length < 2}
onClick={() =>
confirming === d.id
? run(() =>
deleteDashboard({ data: { id: d.id } })
)
: setConfirming(d.id)
}
>
<Trash2 size={15} />
{confirming === d.id
? "Yes, delete it with its cards and links"
: "Delete"}
</Button>
</SettingsRowControl>
</SettingsRow>
)
})}
<SettingsRow>
<form
className="flex flex-wrap gap-2"
onSubmit={(e) => {
e.preventDefault()
const form = e.currentTarget
const name = String(new FormData(form).get("name"))
void run(() => saveDashboard({ data: { name } })).then(
() => form.reset()
)
}}
>
<Input
name="name"
aria-label="Name of the new dashboard"
className="w-64"
placeholder="New dashboard"
maxLength={40}
required
/>
<Button type="submit">
<Plus size={15} /> Add dashboard
</Button>
</form>
</SettingsRow>
</SettingsSection>
<SettingsSection id="clock" className={section}>
<SettingsSectionHeader>
<SettingsSectionTitle>Clock</SettingsSectionTitle>
<SettingsSectionDescription>
How the time on the dashboard looks.
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsRow>
<SettingsRowText>
<div id="settings-font" className="leading-tight font-bold">
Font
</div>
</SettingsRowText>
<SettingsRowControl>
<SegmentedControl
aria-labelledby="settings-font"
size="md"
value={data.clockFont}
onValueChange={(v) => save({ clockFont: v as ClockFont })}
>
{CLOCK_FONTS.map((f) => (
<SegmentedControlItem key={f} value={f}>
{CLOCK_FONT_NAMES[f]}
</SegmentedControlItem>
))}
</SegmentedControl>
</SettingsRowControl>
</SettingsRow>
<SettingsRow>
<SettingsRowText>
<div
id="settings-style"
className="leading-tight font-bold"
>
Style
</div>
<SettingsRowDescription>
Glass shows the wallpaper blurred through the digits.
Tinted takes its color from the wallpaper.
</SettingsRowDescription>
</SettingsRowText>
<SettingsRowControl>
<SegmentedControl
aria-labelledby="settings-style"
size="md"
value={data.clockStyle}
onValueChange={(v) =>
save({ clockStyle: v as ClockStyle })
}
>
{CLOCK_STYLES.map((s) => (
<SegmentedControlItem key={s} value={s}>
{CLOCK_STYLE_NAMES[s]}
</SegmentedControlItem>
))}
</SegmentedControl>
</SettingsRowControl>
</SettingsRow>
</SettingsSection>
<SettingsSection id="search" className={section}>
<SettingsSectionHeader>
<SettingsSectionTitle>Search</SettingsSectionTitle>
<SettingsSectionDescription>
Where the search bar sends you. DuckDuckGo !bangs work with
every engine.
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsRow>
<SettingsRowText>
<div
id="settings-engine"
className="leading-tight font-bold"
>
Search engine
</div>
<SettingsRowDescription>
{data.searxngUrl
? `SearXNG instance: ${data.searxngUrl}`
: "SearXNG is off: set SEARXNG_URL on the server to use it."}
</SettingsRowDescription>
</SettingsRowText>
<SettingsRowControl>
<SegmentedControl
aria-labelledby="settings-engine"
size="md"
value={data.searchEngine}
onValueChange={(v) => save({ searchEngine: v as Engine })}
>
{ENGINES.map((e) => (
<SegmentedControlItem
key={e}
value={e}
disabled={e === "searxng" && !data.searxngUrl}
>
{ENGINE_NAMES[e]}
</SegmentedControlItem>
))}
</SegmentedControl>
</SettingsRowControl>
</SettingsRow>
</SettingsSection>
<SettingsSection id="wallpaper" className={section}>
<SettingsSectionHeader>
<SettingsSectionTitle>Wallpaper</SettingsSectionTitle>
<SettingsSectionDescription>
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">
<img
src={data.wallpaperUrl ?? DEFAULT_WALLPAPER}
alt="Current wallpaper"
className="aspect-video w-full object-cover"
/>
{/* as dark as on the dashboard */}
<div
className="absolute inset-0 bg-black"
style={{ opacity: dim / 100 }}
/>
</div>
<div className="flex min-w-0 flex-[1_1_260px] flex-col gap-3.5">
<Field>
<FieldLabel>Image address</FieldLabel>
<Input
// empty again after an upload or a reset
key={data.wallpaperUrl}
type="url"
pattern="https?://.+"
defaultValue={
uploaded ? "" : (data.wallpaperUrl ?? "")
}
placeholder="https://…"
onKeyDown={(e) =>
e.key === "Enter" && e.currentTarget.blur()
}
onBlur={(e) => {
const url = e.target.value.trim()
if (!url || url === data.wallpaperUrl) return
if (e.target.checkValidity())
void saveWall({ wallpaperUrl: url })
else
setError(
"The image address must start with http:// or https://"
)
}}
/>
<FieldDescription>
{uploaded
? "You use an uploaded image now."
: data.wallpaperUrl
? "You use an image from the web now."
: "You use the default photo now."}
</FieldDescription>
</Field>
<div className="flex flex-wrap gap-2">
<input
ref={file}
type="file"
accept="image/jpeg,image/png,image/webp,image/avif"
className="hidden"
onChange={(e) => {
const image = e.target.files?.[0]
if (image) void upload(image)
e.target.value = ""
}}
/>
<Button
disabled={status === "saving"}
onClick={() => file.current?.click()}
>
<Upload size={15} /> Upload image
</Button>
<Button
variant="ghost"
disabled={status === "saving" || !data.wallpaperUrl}
onClick={() => saveWall({ wallpaperUrl: null })}
>
Use default
</Button>
</div>
</div>
</div>
</SettingsRow>
<SettingsRow>
<SettingsRowText>
<SettingsRowLabel htmlFor="settings-dim">
Darken
</SettingsRowLabel>
<SettingsRowDescription>
How much the wallpaper is darkened, so that the text on it
stays readable.
</SettingsRowDescription>
</SettingsRowText>
<SettingsRowControl className="flex items-center gap-3">
<input
id="settings-dim"
type="range"
min={0}
max={100}
step={5}
value={dim}
onChange={(e) => {
const wallpaperDim = Number(e.target.value)
setDim(wallpaperDim)
// one save when the slider rests, not one per step
clearTimeout(dimSave.current)
dimSave.current = setTimeout(
() => saveWall({ wallpaperDim }),
400
)
}}
className="w-48 accent-accent scheme-dark"
/>
<output
htmlFor="settings-dim"
className="w-10 text-right text-sm text-fg-subtle tabular-nums"
>
{dim}%
</output>
</SettingsRowControl>
</SettingsRow>
</SettingsSection>
<SettingsSection id="account" className={section}>
<SettingsSectionHeader>
<SettingsSectionTitle>Account</SettingsSectionTitle>
</SettingsSectionHeader>
<SettingsRow>
<SettingsRowText>
<div className="leading-tight font-bold">
{data.user.name}
</div>
<SettingsRowDescription>
{data.user.email}
</SettingsRowDescription>
</SettingsRowText>
<SettingsRowControl>
<Button
onClick={async () => {
await authClient.signOut()
await router.navigate({ to: "/login" })
}}
>
<LogOut size={15} /> Sign out
</Button>
</SettingsRowControl>
</SettingsRow>
</SettingsSection>
</div>
</div>
</div>
</main>
</div>
)
}