feat: several dashboards with a default, icon search and icon upload
images / check (push) Successful in 33s
images / image (push) Successful in 16s

Dashboards are separate sets of cards (Home, Work). Settings manages them and
sets the one that opens at sign-in, the header and the search bar switch.
Migration 0006 puts the existing cards on a dashboard "Home".

The link dialog searches dashboard-icons and uploads custom icons (/api/icon,
up to 1 MB, SVG served sandboxed). Wallpaper and icons share the upload checks.
This commit is contained in:
2026-11-18 17:53:27 +01:00
parent 4b9690e064
commit e85244e820
18 changed files with 1643 additions and 125 deletions
+16 -3
View File
@@ -21,19 +21,28 @@ import {
export type CardTarget = { id: string; name: string; links: unknown[] } | "new"
/** `card` is the card to edit, "new" to add one, or null when closed. */
/**
* `card` is the card to edit, "new" to add one, or null when closed.
* A new card goes on the dashboard `dashboardId`.
*/
export function CardDialog({
card,
dashboardId,
onClose,
}: {
card: CardTarget | null
dashboardId: string
onClose: () => void
}) {
return (
<Dialog open={!!card} onOpenChange={(open) => !open && onClose()}>
<GlassDialogContent>
{card && (
<CardForm card={card === "new" ? null : card} onClose={onClose} />
<CardForm
card={card === "new" ? null : card}
dashboardId={dashboardId}
onClose={onClose}
/>
)}
</GlassDialogContent>
</Dialog>
@@ -42,9 +51,11 @@ export function CardDialog({
function CardForm({
card,
dashboardId,
onClose,
}: {
card: Exclude<CardTarget, "new"> | null
dashboardId: string
onClose: () => void
}) {
const router = useRouter()
@@ -72,7 +83,9 @@ function CardForm({
onSubmit={(e) => {
e.preventDefault()
const name = String(new FormData(e.currentTarget).get("name"))
void submit(() => saveCard({ data: { id: card?.id, name } }))
void submit(() =>
saveCard({ data: { id: card?.id, name, dashboardId } })
)
}}
>
<DialogHeader>
+122 -13
View File
@@ -1,9 +1,16 @@
import { useState } from "react"
import { useEffect, useRef, useState } from "react"
import { useRouter } from "@tanstack/react-router"
import { Trash2 } from "lucide-react"
import { Trash2, Upload, X } from "lucide-react"
import { GlassDialogContent } from "@/components/glass"
import type { HomeLink } from "@/components/link-tile"
import { deleteLink, saveLink } from "@/lib/dashboard.functions"
import {
LIBRARY_INDEX,
UPLOADED_ICON,
isImageAddress,
libraryIcon,
searchIcons,
} from "@/lib/icons"
import { Button } from "@/vendor/collabry/components/Button/Button"
import {
Field,
@@ -38,7 +45,8 @@ export function LinkDialog({
}) {
return (
<Dialog open={!!target} onOpenChange={(open) => !open && onClose()}>
<GlassDialogContent>
{/* taller than a small screen since it shows icons: scroll inside */}
<GlassDialogContent className="max-h-[86vh] overflow-y-auto">
{target && <LinkForm target={target} cards={cards} onClose={onClose} />}
</GlassDialogContent>
</Dialog>
@@ -58,6 +66,41 @@ function LinkForm({
const router = useRouter()
const [busy, setBusy] = useState(false)
const [error, setError] = useState("")
const [name, setName] = useState(link?.name ?? "")
const [icon, setIcon] = useState(link?.icon ?? "")
const [library, setLibrary] = useState<string[]>([])
const file = useRef<HTMLInputElement>(null)
// Without the library's index the field still takes a name or an address.
useEffect(() => {
fetch(LIBRARY_INDEX)
.then((res) => res.json())
.then((index: { png: string[] }) =>
setLibrary(index.png.map((f) => f.replace(/\.png$/, "")))
)
.catch(() => {})
}, [])
const uploaded = icon.startsWith(UPLOADED_ICON)
// what the field holds, or what an empty field would look up
const matches = isImageAddress(icon) ? [] : searchIcons(library, icon || name)
const upload = async (image: File) => {
setBusy(true)
setError("")
try {
const res = await fetch("/api/icon", {
method: "POST",
headers: { "Content-Type": image.type },
body: image,
})
if (res.ok) setIcon((await res.json()).icon)
else setError(await res.text())
} catch {
setError("Could not upload. Try again.")
}
setBusy(false)
}
const submit = async (action: () => Promise<void>) => {
setBusy(true)
@@ -82,9 +125,9 @@ function LinkForm({
data: {
id: link?.id,
cardId: String(form.get("cardId")),
name: String(form.get("name")),
name,
url: String(form.get("url")),
icon: String(form.get("icon")).trim() || null,
icon: icon.trim() || null,
},
})
)
@@ -100,8 +143,8 @@ function LinkForm({
<Field>
<FieldLabel>Name</FieldLabel>
<Input
name="name"
defaultValue={link?.name}
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Plex"
maxLength={60}
required
@@ -123,13 +166,79 @@ function LinkForm({
<FieldLabel>
Icon <FieldNote>(optional)</FieldNote>
</FieldLabel>
<Input
name="icon"
defaultValue={link?.icon ?? ""}
placeholder="Image URL or icon name, e.g. plex"
/>
<div className="flex items-center gap-2">
{uploaded && (
<img
src={icon}
alt=""
className="size-9 flex-none rounded-lg object-contain"
/>
)}
<Input
className="min-w-0 flex-1"
value={uploaded ? "" : icon}
onChange={(e) => setIcon(e.target.value)}
placeholder={
uploaded ? "Your image" : "Search icons or paste a URL"
}
autoComplete="off"
/>
{uploaded && (
<Button
variant="ghost"
iconOnly
aria-label="Remove your image"
onClick={() => setIcon("")}
>
<X size={15} />
</Button>
)}
<input
ref={file}
type="file"
accept="image/png,image/jpeg,image/webp,image/avif,image/svg+xml"
className="hidden"
onChange={(e) => {
const image = e.target.files?.[0]
if (image) void upload(image)
e.target.value = ""
}}
/>
<Button disabled={busy} onClick={() => file.current?.click()}>
<Upload size={15} /> Upload
</Button>
</div>
{matches.length > 0 && (
// two and a half rows, so it shows that there is more to scroll to
<div
role="group"
aria-label="Icons from the library"
className="grid max-h-29 grid-cols-7 gap-1 overflow-y-auto rounded-xl bg-white/5 p-1"
>
{matches.map((match) => (
<button
key={match}
type="button"
title={match}
aria-label={match}
aria-pressed={match === icon}
onClick={() => setIcon(match)}
className="grid h-11 place-items-center rounded-lg outline-none hover:bg-white/10 focus-visible:ring-2 focus-visible:ring-white/60 aria-pressed:bg-white/15"
>
<img
src={libraryIcon(match)}
alt=""
loading="lazy"
referrerPolicy="no-referrer"
className="size-8 object-contain"
/>
</button>
))}
</div>
)}
<FieldDescription>
Empty: found from the name, then from the site's favicon.
Empty: found from the name, then from the site's favicon. Upload a
PNG, JPEG, WebP, AVIF or SVG, up to 1 MB.
</FieldDescription>
</Field>
<Field>
+1 -15
View File
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react"
import { useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { Pencil } from "lucide-react"
import { iconSources } from "@/lib/icons"
import { cn } from "@/vendor/collabry/lib/cn"
export type HomeLink = {
@@ -12,21 +13,6 @@ export type HomeLink = {
icon: string | null
}
const dashboardIcon = (name: string) =>
`https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/png/${name
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "")}.png`
/** Icon sources to try in order; the letter tile is the last resort. */
function iconSources({ name, url, icon }: HomeLink) {
return [
icon && /^https?:\/\//.test(icon) ? icon : dashboardIcon(icon || name),
`${new URL(url).origin}/favicon.ico`,
]
}
type IconProps = { link: HomeLink; className?: string }
/** Starts the fallback chain again when the link changes. */
+46 -5
View File
@@ -77,9 +77,9 @@ export const verification = pgTable(
const bytea = customType<{ data: Uint8Array }>({ dataType: () => "bytea" })
/** A named group of links on the dashboard. */
export const card = pgTable(
"card",
/** A set of cards, for example Home and Work. */
export const dashboard = pgTable(
"dashboard",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: text("user_id")
@@ -88,7 +88,27 @@ export const card = pgTable(
name: text("name").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
},
(t) => [index("card_user_id_idx").on(t.userId)]
(t) => [index("dashboard_user_id_idx").on(t.userId)]
)
/** A named group of links on a dashboard. */
export const card = pgTable(
"card",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
dashboardId: uuid("dashboard_id")
.notNull()
.references(() => dashboard.id, { onDelete: "cascade" }),
name: text("name").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
},
(t) => [
index("card_user_id_idx").on(t.userId),
index("card_dashboard_id_idx").on(t.dashboardId),
]
)
export const link = pgTable(
@@ -105,7 +125,8 @@ export const link = pgTable(
position: integer("position").notNull().default(0),
name: text("name").notNull(),
url: text("url").notNull(),
// image URL or a dashboard-icons name ("plex"); null = guess from name
// image URL, an upload ("/api/icon?id=…") or a dashboard-icons name ("plex");
// null = guess from name
icon: text("icon"),
createdAt: timestamp("created_at").notNull().defaultNow(),
},
@@ -120,6 +141,11 @@ export const settings = pgTable("settings", {
.primaryKey()
.references(() => user.id, { onDelete: "cascade" }),
title: text("title").notNull().default("Dahoam"),
// the dashboard that opens after sign-in; null = the oldest one
defaultDashboardId: uuid("default_dashboard_id").references(
() => dashboard.id,
{ onDelete: "set null" }
),
searchEngine: text("search_engine", {
enum: ["duckduckgo", "searxng", "google"],
})
@@ -140,6 +166,21 @@ export const settings = pgTable("settings", {
.default("solid"),
})
/** A link icon that the user uploaded, served from /api/icon. */
export const icon = pgTable(
"icon",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
mime: text("mime").notNull(),
data: bytea("data").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
},
(t) => [index("icon_user_id_idx").on(t.userId)]
)
export const wallpaper = pgTable("wallpaper", {
userId: text("user_id")
.primaryKey()
+86 -17
View File
@@ -4,7 +4,7 @@ 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, link, settings, wallpaper } from "@/db/schema"
import { card, dashboard, link, settings, wallpaper } from "@/db/schema"
import { auth, requireUser, signUpEnabled, ssoName } from "@/lib/auth"
import { CLOCK_FONTS, CLOCK_STYLES } from "@/lib/clock"
import { ENGINES, parseSuggestions } from "@/lib/search"
@@ -19,6 +19,14 @@ async function requireCard(userId: string, cardId: string) {
if (!found.length) throw new Error("Unknown card")
}
async function requireDashboard(userId: string, dashboardId: string) {
const found = await db
.select({ id: dashboard.id })
.from(dashboard)
.where(and(eq(dashboard.id, dashboardId), eq(dashboard.userId, userId)))
if (!found.length) throw new Error("Unknown dashboard")
}
/** The position after the last link of a card. */
const endOf = (cardId: string) =>
sql<number>`(select coalesce(max(${link.position}) + 1, 0) from ${link} where ${link.cardId} = ${cardId})`
@@ -31,17 +39,44 @@ export const getAuthInfo = createServerFn({ method: "GET" }).handler(
})
)
/** Everything the dashboard renders, or null when signed out. */
export const getDashboard = createServerFn({ method: "GET" }).handler(
async () => {
/**
* Everything the dashboard renders, or null when signed out. Without a
* `dashboardId`, or with one that does not exist, it is the default dashboard.
*/
export const getDashboard = createServerFn({ method: "GET" })
// any string: the id comes from the address bar, a wrong one is not an error
.validator(z.object({ dashboardId: z.string().optional() }).optional())
.handler(async ({ data }) => {
const session = await auth.api.getSession({ headers: getRequestHeaders() })
if (!session) return null
const userId = session.user.id
const [cards, links, rows] = await Promise.all([
const [dashboards, rows] = await Promise.all([
db
.select({ id: dashboard.id, name: dashboard.name })
.from(dashboard)
.where(eq(dashboard.userId, userId))
.orderBy(asc(dashboard.createdAt)),
db.select().from(settings).where(eq(settings.userId, userId)),
])
// Cards need a dashboard and links need a card, so nobody is left without one.
// shortcut: two first loads at the same moment make two of each, add a unique
// constraint if that ever shows up
if (!dashboards.length)
dashboards.push(
...(await db
.insert(dashboard)
.values({ userId, name: "Home" })
.returning({ id: dashboard.id, name: dashboard.name }))
)
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 [cards, links] = await Promise.all([
db
.select({ id: card.id, name: card.name })
.from(card)
.where(eq(card.userId, userId))
.where(and(eq(card.userId, userId), eq(card.dashboardId, dashboardId)))
.orderBy(asc(card.createdAt)),
db
.select({
@@ -52,23 +87,22 @@ export const getDashboard = createServerFn({ method: "GET" }).handler(
icon: link.icon,
})
.from(link)
.where(eq(link.userId, userId))
.innerJoin(card, eq(card.id, link.cardId))
.where(and(eq(link.userId, userId), eq(card.dashboardId, dashboardId)))
.orderBy(asc(link.position), asc(link.createdAt)),
db.select().from(settings).where(eq(settings.userId, userId)),
])
// Links need a card to live in, so nobody is left without one.
// shortcut: two first loads at the same moment make two cards, add a unique
// constraint if that ever shows up
if (!cards.length)
cards.push(
...(await db
.insert(card)
.values({ userId, name: "Apps" })
.values({ userId, dashboardId, name: "Apps" })
.returning({ id: card.id, name: card.name }))
)
const s = rows.at(0) // no row until the first save
return {
user: { name: session.user.name, email: session.user.email },
dashboards,
dashboardId,
defaultDashboardId,
cards: cards.map((c) => ({
...c,
links: links.filter((l) => l.cardId === c.id),
@@ -81,8 +115,7 @@ export const getDashboard = createServerFn({ method: "GET" }).handler(
clockStyle: s?.clockStyle ?? "solid",
searxngUrl: process.env.SEARXNG_URL || null,
}
}
)
})
export const saveLink = createServerFn({ method: "POST" })
.validator(
@@ -119,9 +152,11 @@ export const saveCard = createServerFn({ method: "POST" })
z.object({
id: z.uuid().optional(),
name: z.string().trim().min(1).max(40),
// where a new card goes. A card that exists stays on its dashboard.
dashboardId: z.uuid(),
})
)
.handler(async ({ data: { id, name } }) => {
.handler(async ({ data: { id, name, dashboardId } }) => {
const user = await requireUser()
if (id) {
await db
@@ -129,10 +164,41 @@ export const saveCard = createServerFn({ method: "POST" })
.set({ name })
.where(and(eq(card.id, id), eq(card.userId, user.id)))
} else {
await db.insert(card).values({ name, userId: user.id })
await requireDashboard(user.id, dashboardId)
await db.insert(card).values({ name, dashboardId, userId: user.id })
}
})
export const saveDashboard = createServerFn({ method: "POST" })
.validator(
z.object({
id: z.uuid().optional(),
name: z.string().trim().min(1).max(40),
})
)
.handler(async ({ data: { id, name } }) => {
const user = await requireUser()
if (id) {
await db
.update(dashboard)
.set({ name })
.where(and(eq(dashboard.id, id), eq(dashboard.userId, user.id)))
} else {
await db.insert(dashboard).values({ name, userId: user.id })
}
})
/** Deletes the dashboard and, through the foreign keys, its cards and their links. */
export const deleteDashboard = createServerFn({ method: "POST" })
.validator(z.object({ id: z.uuid() }))
.handler(async ({ data }) => {
const user = await requireUser()
const mine = eq(dashboard.userId, user.id)
if ((await db.$count(dashboard, mine)) < 2)
throw new Error("The last dashboard stays")
await db.delete(dashboard).where(and(eq(dashboard.id, data.id), mine))
})
/** Deletes the card and, through the foreign key, its links. */
export const deleteCard = createServerFn({ method: "POST" })
.validator(z.object({ id: z.uuid() }))
@@ -187,6 +253,7 @@ export const saveSettings = createServerFn({ method: "POST" })
z
.object({
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
@@ -201,6 +268,8 @@ export const saveSettings = createServerFn({ method: "POST" })
)
.handler(async ({ data }) => {
const user = await requireUser()
if (data.defaultDashboardId)
await requireDashboard(user.id, data.defaultDashboardId)
await db
.insert(settings)
.values({ ...data, userId: user.id })
+35
View File
@@ -0,0 +1,35 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { UPLOADED_ICON, iconSources, searchIcons } from "./icons.ts"
const link = { name: "Home Assistant", url: "https://ha.example.com/lovelace" }
const first = (icon: string | null) => iconSources({ ...link, icon })[0]
test("no icon: looked up by name, then the site's favicon", () => {
assert.deepEqual(iconSources({ ...link, icon: null }), [
"https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/png/home-assistant.png",
"https://ha.example.com/favicon.ico",
])
})
test("an icon name is looked up in the library", () => {
assert.match(first(" Plex "), /\/png\/plex\.png$/)
})
test("an image address and an upload are used as they are", () => {
assert.equal(first("https://example.com/a.png"), "https://example.com/a.png")
assert.equal(first(`${UPLOADED_ICON}abc`), "/api/icon?id=abc")
})
test("searchIcons: names that start with the query first, the shortest first", () => {
// the order of the library's index: "plex-alt" is before "plex" there
const names = ["a-plex", "jellyfin", "plex-alt", "plex", "plexamp"]
assert.deepEqual(searchIcons(names, "Plex"), [
"plex",
"plexamp",
"plex-alt",
"a-plex",
])
assert.deepEqual(searchIcons(names, "plex", 2), ["plex", "plexamp"])
assert.deepEqual(searchIcons(names, "nothing"), [])
})
+51
View File
@@ -0,0 +1,51 @@
// Where a link's icon comes from. Pure, so it can be tested without a browser.
const LIBRARY = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons"
/** JSON with the file names of every icon in the library: `{ png: ["plex.png", …] }`. */
export const LIBRARY_INDEX = `${LIBRARY}/tree.json`
/** How a link stores an icon that the user uploaded: this plus the icon's id. */
export const UPLOADED_ICON = "/api/icon?id="
const slug = (name: string) =>
name
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "")
export const libraryIcon = (name: string) => `${LIBRARY}/png/${slug(name)}.png`
/** An image address or an upload, not a name in the library. */
export const isImageAddress = (icon: string) =>
/^https?:\/\//.test(icon) || icon.startsWith(UPLOADED_ICON)
/** Icon sources to try in order; the letter tile is the last resort. */
export function iconSources({
name,
url,
icon,
}: {
name: string
url: string
icon: string | null
}) {
return [
icon && isImageAddress(icon) ? icon : libraryIcon(icon || name),
`${new URL(url).origin}/favicon.ico`,
]
}
/**
* Library icons for what the user typed: names that start with it, then names that
* contain it. In both groups the shortest first, so "plex" is before "plex-alt".
*/
export function searchIcons(names: string[], query: string, limit = 42) {
const q = slug(query)
const rank = (n: string) => (n.startsWith(q) ? 0 : 1000) + n.length
return names
.filter((n) => n.includes(q))
.sort((a, b) => rank(a) - rank(b))
.slice(0, limit)
}
+49
View File
@@ -0,0 +1,49 @@
// Shared by the routes that store images in the database (wallpaper, link icons).
import { auth } from "@/lib/auth"
export async function userId(request: Request) {
const session = await auth.api.getSession({ headers: request.headers })
return session?.user.id
}
/** The image in the body of an upload, or the response that says why it was refused. */
export async function readImage(
request: Request,
limits: { types: string[]; formats: string; maxMb: number }
) {
const id = await userId(request)
if (!id) return new Response("Unauthorized", { status: 401 })
const mime = request.headers.get("content-type") ?? ""
if (!limits.types.includes(mime))
return new Response(`Use a ${limits.formats} image`, { status: 415 })
const maxBytes = limits.maxMb * 1024 * 1024
const tooLarge = () =>
new Response(`Image is empty or larger than ${limits.maxMb} MB`, {
status: 413,
})
// a chunked body has no declared size and could fill the memory
const declared = Number(request.headers.get("content-length"))
if (
!(declared > 0 && declared <= maxBytes) ||
request.headers.has("transfer-encoding")
)
return tooLarge()
const data = new Uint8Array(await request.arrayBuffer())
if (!data.length || data.length > maxBytes) return tooLarge()
return { userId: id, mime, data }
}
/** Answers with a stored image. Its URL has to change when the image does. */
export const serveImage = (row?: { mime: string; data: Uint8Array }) =>
row
? new Response(new Uint8Array(row.data), {
headers: {
"Content-Type": row.mime,
"X-Content-Type-Options": "nosniff",
// an SVG that is opened in its own tab must not run scripts on this origin
"Content-Security-Policy":
"default-src 'none'; style-src 'unsafe-inline'; sandbox",
"Cache-Control": "private, max-age=31536000, immutable",
},
})
: new Response("Not found", { status: 404 })
+39 -3
View File
@@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
import { Route as IndexRouteImport } from './routes/index'
import { Route as LoginRouteImport } from './routes/login'
import { Route as SettingsRouteImport } from './routes/settings'
import { Route as ApiIconRouteImport } from './routes/api/icon'
import { Route as ApiWallpaperRouteImport } from './routes/api/wallpaper'
import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$'
@@ -30,6 +31,11 @@ const SettingsRoute = SettingsRouteImport.update({
path: '/settings',
getParentRoute: () => rootRouteImport,
} as any)
const ApiIconRoute = ApiIconRouteImport.update({
id: '/api/icon',
path: '/api/icon',
getParentRoute: () => rootRouteImport,
} as any)
const ApiWallpaperRoute = ApiWallpaperRouteImport.update({
id: '/api/wallpaper',
path: '/api/wallpaper',
@@ -45,6 +51,7 @@ export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/login': typeof LoginRoute
'/settings': typeof SettingsRoute
'/api/icon': typeof ApiIconRoute
'/api/wallpaper': typeof ApiWallpaperRoute
'/api/auth/$': typeof ApiAuthSplatRoute
}
@@ -52,6 +59,7 @@ export interface FileRoutesByTo {
'/': typeof IndexRoute
'/login': typeof LoginRoute
'/settings': typeof SettingsRoute
'/api/icon': typeof ApiIconRoute
'/api/wallpaper': typeof ApiWallpaperRoute
'/api/auth/$': typeof ApiAuthSplatRoute
}
@@ -60,22 +68,42 @@ export interface FileRoutesById {
'/': typeof IndexRoute
'/login': typeof LoginRoute
'/settings': typeof SettingsRoute
'/api/icon': typeof ApiIconRoute
'/api/wallpaper': typeof ApiWallpaperRoute
'/api/auth/$': typeof ApiAuthSplatRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/login' | '/settings' | '/api/wallpaper' | '/api/auth/$'
fullPaths:
| '/'
| '/login'
| '/settings'
| '/api/icon'
| '/api/wallpaper'
| '/api/auth/$'
fileRoutesByTo: FileRoutesByTo
to: '/' | '/login' | '/settings' | '/api/wallpaper' | '/api/auth/$'
to:
| '/'
| '/login'
| '/settings'
| '/api/icon'
| '/api/wallpaper'
| '/api/auth/$'
id:
'__root__' | '/' | '/login' | '/settings' | '/api/wallpaper' | '/api/auth/$'
| '__root__'
| '/'
| '/login'
| '/settings'
| '/api/icon'
| '/api/wallpaper'
| '/api/auth/$'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
LoginRoute: typeof LoginRoute
SettingsRoute: typeof SettingsRoute
ApiIconRoute: typeof ApiIconRoute
ApiWallpaperRoute: typeof ApiWallpaperRoute
ApiAuthSplatRoute: typeof ApiAuthSplatRoute
}
@@ -103,6 +131,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsRouteImport
parentRoute: typeof rootRouteImport
}
'/api/icon': {
id: '/api/icon'
path: '/api/icon'
fullPath: '/api/icon'
preLoaderRoute: typeof ApiIconRouteImport
parentRoute: typeof rootRouteImport
}
'/api/wallpaper': {
id: '/api/wallpaper'
path: '/api/wallpaper'
@@ -124,6 +159,7 @@ const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
LoginRoute: LoginRoute,
SettingsRoute: SettingsRoute,
ApiIconRoute: ApiIconRoute,
ApiWallpaperRoute: ApiWallpaperRoute,
ApiAuthSplatRoute: ApiAuthSplatRoute,
}
+63
View File
@@ -0,0 +1,63 @@
import { createFileRoute } from "@tanstack/react-router"
import { and, eq, sql } from "drizzle-orm"
import { z } from "zod"
import { db } from "@/db"
import { icon, link } from "@/db/schema"
import { UPLOADED_ICON } from "@/lib/icons"
import { readImage, serveImage, userId } from "@/lib/upload"
const LIMITS = {
// SVG is safe here: serveImage sandboxes it
types: [
"image/png",
"image/jpeg",
"image/webp",
"image/avif",
"image/svg+xml",
],
formats: "PNG, JPEG, WebP, AVIF or SVG",
maxMb: 1,
}
export const Route = createFileRoute("/api/icon")({
server: {
handlers: {
GET: async ({ request }) => {
const user = await userId(request)
if (!user) return new Response("Unauthorized", { status: 401 })
const id = z
.uuid()
.safeParse(new URL(request.url).searchParams.get("id"))
if (!id.success) return new Response("Not found", { status: 404 })
return serveImage(
(
await db
.select()
.from(icon)
.where(and(eq(icon.id, id.data), eq(icon.userId, user)))
).at(0)
)
},
POST: async ({ request }) => {
const image = await readImage(request, LIMITS)
if (image instanceof Response) return image
// Icons that no link uses any more go away with the next upload. An hour of
// grace, because a new icon has no link until its dialog is saved.
// shortcut: no limit on uploads per user, add one if strangers can sign up
await db.execute(sql`
delete from ${icon}
where ${icon.userId} = ${image.userId}
and ${icon.createdAt} < now() - interval '1 hour'
and not exists (
select 1 from ${link}
where ${link.icon} = ${UPLOADED_ICON} || ${icon.id}::text
)`)
const [row] = await db
.insert(icon)
.values(image)
.returning({ id: icon.id })
return Response.json({ icon: UPLOADED_ICON + row.id })
},
},
},
})
+17 -44
View File
@@ -2,70 +2,43 @@ import { createFileRoute } from "@tanstack/react-router"
import { eq } from "drizzle-orm"
import { db } from "@/db"
import { settings, wallpaper } from "@/db/schema"
import { auth } from "@/lib/auth"
import { readImage, serveImage, userId } from "@/lib/upload"
const MAX_BYTES = 10 * 1024 * 1024
// no SVG: it can carry scripts
const TYPES = ["image/jpeg", "image/png", "image/webp", "image/avif"]
async function userId(request: Request) {
const session = await auth.api.getSession({ headers: request.headers })
return session?.user.id
const LIMITS = {
// no SVG: a wallpaper is a photo
types: ["image/jpeg", "image/png", "image/webp", "image/avif"],
formats: "JPEG, PNG, WebP or AVIF",
maxMb: 10,
}
export const Route = createFileRoute("/api/wallpaper")({
server: {
handlers: {
// the URL carries ?v=<upload time>, so it never changes
GET: async ({ request }) => {
const id = await userId(request)
if (!id) return new Response("Unauthorized", { status: 401 })
const row = (
await db.select().from(wallpaper).where(eq(wallpaper.userId, id))
).at(0)
if (!row) return new Response("Not found", { status: 404 })
return new Response(new Uint8Array(row.data), {
headers: {
"Content-Type": row.mime,
"X-Content-Type-Options": "nosniff",
// the URL carries ?v=<upload time>, so it never changes
"Cache-Control": "private, max-age=31536000, immutable",
},
})
return serveImage(
(
await db.select().from(wallpaper).where(eq(wallpaper.userId, id))
).at(0)
)
},
POST: async ({ request }) => {
const id = await userId(request)
if (!id) return new Response("Unauthorized", { status: 401 })
const mime = request.headers.get("content-type") ?? ""
if (!TYPES.includes(mime))
return new Response("Use a JPEG, PNG, WebP or AVIF image", {
status: 415,
})
// a chunked body has no declared size and could fill the memory
const declared = Number(request.headers.get("content-length"))
if (
!(declared > 0 && declared <= MAX_BYTES) ||
request.headers.has("transfer-encoding")
)
return new Response("Image is empty or larger than 10 MB", {
status: 413,
})
const data = new Uint8Array(await request.arrayBuffer())
if (!data.length || data.length > MAX_BYTES)
return new Response("Image is empty or larger than 10 MB", {
status: 413,
})
const image = await readImage(request, LIMITS)
if (image instanceof Response) return image
const wallpaperUrl = `/api/wallpaper?v=${Date.now()}`
await db.transaction(async (tx) => {
await tx
.insert(wallpaper)
.values({ userId: id, mime, data })
.values(image)
.onConflictDoUpdate({
target: wallpaper.userId,
set: { mime, data },
set: { mime: image.mime, data: image.data },
})
await tx
.insert(settings)
.values({ userId: id, wallpaperUrl })
.values({ userId: image.userId, wallpaperUrl })
.onConflictDoUpdate({
target: settings.userId,
set: { wallpaperUrl },
+53 -6
View File
@@ -5,7 +5,14 @@ import {
redirect,
useRouter,
} from "@tanstack/react-router"
import { LayoutGrid, LogOut, Pencil, Plus, Settings2 } from "lucide-react"
import {
LayoutDashboard,
LayoutGrid,
LogOut,
Pencil,
Plus,
Settings2,
} from "lucide-react"
import { CardDialog } from "@/components/card-dialog"
import type { CardTarget } from "@/components/card-dialog"
import { CardGrid } from "@/components/card-grid"
@@ -21,8 +28,12 @@ import { Button } from "@/vendor/collabry/components/Button/Button"
import { cn } from "@/vendor/collabry/lib/cn"
export const Route = createFileRoute("/")({
loader: async () => {
const data = await getDashboard()
// ?d=<dashboard id>. Without it the default dashboard opens.
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
},
@@ -50,14 +61,33 @@ function Dashboard() {
<header className="flex h-20 w-full max-w-[1200px] items-center gap-4 px-2 sm:px-8">
<Logo className="size-6" />
<h1 className="m-0 text-md font-semibold">{data.title}</h1>
<span className="hidden font-mono text-sm text-white/50 sm:inline">
{data.dashboards.length > 1 && (
<nav
aria-label="Dashboards"
className="flex min-w-0 gap-1 overflow-x-auto p-1"
>
{data.dashboards.map((d) => (
<Link
key={d.id}
to="/"
search={{ d: d.id }}
aria-current={d.id === data.dashboardId ? "page" : undefined}
className="rounded-full px-3 py-1 text-sm whitespace-nowrap text-white/60 outline-none hover:bg-white/10 hover:text-white focus-visible:ring-2 focus-visible:ring-white/60 aria-[current=page]:bg-white/15 aria-[current=page]:text-white"
>
{d.name}
</Link>
))}
</nav>
)}
{/* at the right, so it does not read as one more dashboard */}
<span className="ml-auto hidden font-mono text-sm text-white/50 sm:inline">
{data.user.name}
</span>
<Button
variant="ghost"
iconOnly
aria-label="Add link"
className={cn(onWallpaper, "ml-auto")}
className={cn(onWallpaper, "ml-auto sm:ml-0")}
onClick={addLink}
>
<Plus className="size-5" />
@@ -94,6 +124,19 @@ function Dashboard() {
icon: <LayoutGrid className="size-4" />,
run: () => setCard("new"),
},
...data.dashboards
.filter((d) => d.id !== data.dashboardId)
.map((d) => ({
label: `Switch to ${d.name}`,
icon: <LayoutDashboard className="size-4" />,
run: () => router.navigate({ to: "/", search: { d: d.id } }),
})),
{
label: "Add dashboard",
icon: <LayoutDashboard className="size-4" />,
run: () =>
router.navigate({ to: "/settings", hash: "dashboards" }),
},
{
label: "Settings",
icon: <Settings2 className="size-4" />,
@@ -149,7 +192,11 @@ function Dashboard() {
cards={data.cards}
onClose={() => setLink(null)}
/>
<CardDialog card={card} onClose={() => setCard(null)} />
<CardDialog
card={card}
dashboardId={data.dashboardId}
onClose={() => setCard(null)}
/>
</div>
)
}
+125 -16
View File
@@ -1,4 +1,5 @@
import { useRef, useState } from "react"
import type { ComponentProps } from "react"
import {
Link,
createFileRoute,
@@ -12,9 +13,12 @@ import {
CircleUser,
Clock,
Image,
LayoutDashboard,
LogOut,
Plus,
Search,
SlidersHorizontal,
Trash2,
Upload,
} from "lucide-react"
import { Logo } from "@/components/logo"
@@ -27,7 +31,12 @@ import {
CLOCK_STYLE_NAMES,
} from "@/lib/clock"
import type { ClockFont, ClockStyle } from "@/lib/clock"
import { getDashboard, saveSettings } from "@/lib/dashboard.functions"
import {
deleteDashboard,
getDashboard,
saveDashboard,
saveSettings,
} 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"
@@ -76,6 +85,7 @@ export const Route = createFileRoute("/settings")({
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 },
@@ -85,6 +95,30 @@ const SECTIONS = [
// 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()
@@ -95,6 +129,8 @@ function Settings() {
// 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>) => {
@@ -107,6 +143,7 @@ function Settings() {
}
const save = (patch: {
title?: string
defaultDashboardId?: string
searchEngine?: Engine
wallpaperUrl?: string | null
wallpaperDim?: number
@@ -199,37 +236,109 @@ function Settings() {
<SettingsSectionHeader>
<SettingsSectionTitle>General</SettingsSectionTitle>
<SettingsSectionDescription>
How this dashboard is called.
How this start page is called.
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsRow>
<SettingsRowText>
<SettingsRowLabel htmlFor="settings-title">
Dashboard name
Title
</SettingsRowLabel>
<SettingsRowDescription>
Shown at the top left of the dashboard.
Shown at the top left of every dashboard.
</SettingsRowDescription>
</SettingsRowText>
<SettingsRowControl>
<Input
<NameInput
id="settings-title"
className="w-64"
defaultValue={data.title}
maxLength={40}
onKeyDown={(e) =>
e.key === "Enter" && e.currentTarget.blur()
}
onBlur={(e) => {
const title = e.target.value.trim()
if (title && title !== data.title) void save({ title })
else e.target.value = data.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>