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=: 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: () => , }) 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 ( 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(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>(undefined) // deleting a dashboard deletes its cards and links, so it takes a second click const [confirming, setConfirming] = useState(null) // Every control saves on its own. `action` returns a message when it failed. const run = async (action: () => Promise) => { 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
{data.title}
Settings Changes are saved as you make them. {error && ( {error} )} {status === "saving" && ( <> Saving … )} {status === "saved" && ( <> Saved )}
{SECTIONS.map(({ id, label, icon: Icon }) => ( {label} ))}
General How this start page is called. Title Shown at the top left of every dashboard. save({ title })} /> Dashboards 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. {data.dashboards.map((d) => { const isDefault = d.id === data.defaultDashboardId return ( run(() => saveDashboard({ data: { id: d.id, name } }) ) } /> ) })}
{ e.preventDefault() const form = e.currentTarget const name = String(new FormData(form).get("name")) void run(() => saveDashboard({ data: { name } })).then( () => form.reset() ) }} >
Clock How the time on the dashboard looks.
Font
save({ clockFont: v as ClockFont })} > {CLOCK_FONTS.map((f) => ( {CLOCK_FONT_NAMES[f]} ))}
Style
Glass shows the wallpaper blurred through the digits. Tinted takes its color from the wallpaper.
save({ clockStyle: v as ClockStyle }) } > {CLOCK_STYLES.map((s) => ( {CLOCK_STYLE_NAMES[s]} ))}
Search Where the search bar sends you. DuckDuckGo !bangs work with every engine.
Search engine
{data.searxngUrl ? `SearXNG instance: ${data.searxngUrl}` : "SearXNG is off: set SEARXNG_URL on the server to use it."}
save({ searchEngine: v as Engine })} > {ENGINES.map((e) => ( {ENGINE_NAMES[e]} ))}
Wallpaper 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. {data.dashboards.length > 1 && (
Dashboard
Whose wallpaper you change here.
router.navigate({ to: "/settings", search: { d }, hash: "wallpaper", }) } > {data.dashboards.map((d) => ( {d.name} ))}
)}
Current wallpaper {/* as dark as on the dashboard */}
Image address 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://" ) }} /> {uploaded ? "You use an uploaded image now." : data.wallpaperUrl ? "You use an image from the web now." : "You use the default photo now."}
{ const image = e.target.files?.[0] if (image) void upload(image) e.target.value = "" }} />
Darken How much the wallpaper is darkened, so that the text on it stays readable. { 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" /> {dim}% Account
{data.user.name}
{data.user.email}
) }