Files
dahoam/src/lib/dashboard.functions.ts
T
niklas e85244e820
images / check (push) Successful in 33s
images / image (push) Successful in 16s
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.
2026-11-18 17:53:27 +01:00

299 lines
10 KiB
TypeScript

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"
import { CLOCK_FONTS, CLOCK_STYLES } from "@/lib/clock"
import { ENGINES, parseSuggestions } from "@/lib/search"
const httpUrl = z.url({ protocol: /^https?$/ }).max(2000)
async function requireCard(userId: string, cardId: string) {
const found = await db
.select({ id: card.id })
.from(card)
.where(and(eq(card.id, cardId), eq(card.userId, userId)))
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})`
export const getAuthInfo = createServerFn({ method: "GET" }).handler(
async () => ({
signedIn: !!(await auth.api.getSession({ headers: getRequestHeaders() })),
ssoName,
signUpEnabled,
})
)
/**
* 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 [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(and(eq(card.userId, userId), eq(card.dashboardId, dashboardId)))
.orderBy(asc(card.createdAt)),
db
.select({
id: link.id,
cardId: link.cardId,
name: link.name,
url: link.url,
icon: link.icon,
})
.from(link)
.innerJoin(card, eq(card.id, link.cardId))
.where(and(eq(link.userId, userId), eq(card.dashboardId, dashboardId)))
.orderBy(asc(link.position), asc(link.createdAt)),
])
if (!cards.length)
cards.push(
...(await db
.insert(card)
.values({ userId, dashboardId, name: "Apps" })
.returning({ id: card.id, name: card.name }))
)
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),
})),
title: s?.title ?? "Dahoam",
searchEngine: s?.searchEngine ?? "duckduckgo",
wallpaperUrl: s?.wallpaperUrl ?? null,
wallpaperDim: s?.wallpaperDim ?? DEFAULT_WALLPAPER_DIM,
clockFont: s?.clockFont ?? "serif",
clockStyle: s?.clockStyle ?? "solid",
searxngUrl: process.env.SEARXNG_URL || null,
}
})
export const saveLink = createServerFn({ method: "POST" })
.validator(
z.object({
id: z.uuid().optional(),
name: z.string().trim().min(1).max(60),
url: httpUrl,
icon: z.string().trim().max(2000).nullable(),
cardId: z.uuid(),
})
)
.handler(async ({ data: { id, ...values } }) => {
const user = await requireUser()
await requireCard(user.id, values.cardId)
const end = endOf(values.cardId)
if (id) {
await db
.update(link)
.set({
...values,
// a link that changes cards goes to the end of the new one
position: sql`case when ${link.cardId} = ${values.cardId} then ${link.position} else ${end} end`,
})
.where(and(eq(link.id, id), eq(link.userId, user.id)))
} else {
await db
.insert(link)
.values({ ...values, userId: user.id, position: end })
}
})
export const saveCard = createServerFn({ method: "POST" })
.validator(
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, dashboardId } }) => {
const user = await requireUser()
if (id) {
await db
.update(card)
.set({ name })
.where(and(eq(card.id, id), eq(card.userId, user.id)))
} else {
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() }))
.handler(async ({ data }) => {
const user = await requireUser()
await db
.delete(card)
.where(and(eq(card.id, data.id), eq(card.userId, user.id)))
})
/** Stores the result of a drag: for each card, its links in order. */
export const moveLinks = createServerFn({ method: "POST" })
.validator(
z.object({
cards: z
.array(z.object({ id: z.uuid(), linkIds: z.array(z.uuid()).max(500) }))
.max(100),
})
)
.handler(async ({ data }) => {
const user = await requireUser()
const cardIds = [...new Set(data.cards.map((c) => c.id))]
const owned = await db
.select({ id: card.id })
.from(card)
.where(and(eq(card.userId, user.id), inArray(card.id, cardIds)))
if (owned.length !== cardIds.length) throw new Error("Unknown card")
// shortcut: one UPDATE per link, fine for a few hundred links; switch to a
// single UPDATE ... FROM (VALUES ...) if a save gets slow
await db.transaction(async (tx) => {
for (const c of data.cards)
for (const [position, id] of c.linkIds.entries())
await tx
.update(link)
.set({ cardId: c.id, position })
.where(and(eq(link.id, id), eq(link.userId, user.id)))
})
})
export const deleteLink = createServerFn({ method: "POST" })
.validator(z.object({ id: z.uuid() }))
.handler(async ({ data }) => {
const user = await requireUser()
await db
.delete(link)
.where(and(eq(link.id, data.id), eq(link.userId, user.id)))
})
export const saveSettings = createServerFn({ method: "POST" })
.validator(
// a patch: the settings page saves each setting on its own
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
.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),
})
.partial()
.refine((patch) => Object.keys(patch).length > 0)
)
.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 })
.onConflictDoUpdate({ target: settings.userId, set: data })
// the stored upload is no longer shown
if (data.wallpaperUrl !== undefined && !data.wallpaperUrl?.startsWith("/"))
await db.delete(wallpaper).where(eq(wallpaper.userId, user.id))
})
export const suggest = createServerFn({ method: "GET" })
.validator(z.object({ q: z.string().max(200), searxng: z.boolean() }))
.handler(async ({ data }) => {
await requireUser() // not an open proxy
const base = data.searxng && process.env.SEARXNG_URL
const url = base
? `${base.replace(/\/+$/, "")}/autocompleter?q=`
: "https://duckduckgo.com/ac/?type=list&q="
try {
const res = await fetch(url + encodeURIComponent(data.q), {
signal: AbortSignal.timeout(2000),
})
return res.ok ? parseSuggestions(await res.json()) : []
} catch {
return [] // suggestions are optional, search still works
}
})