feat: several dashboards with a default, icon search and icon upload
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:
@@ -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 })
|
||||
|
||||
@@ -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"), [])
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 })
|
||||
Reference in New Issue
Block a user