feat: Dahoam start page with accounts, cards and search
images / check (push) Successful in 27s
images / image (push) Successful in 32s

Replica of the reference start page: wallpaper, serif clock, search bar
and link cards, as a TanStack Start app.

- Better Auth: email/password and OIDC single sign-on
- Postgres with Drizzle for the auth tables, cards, links, settings and
  uploaded wallpapers; the server applies the migrations on start
- cards group links; links are dragged inside and between cards
- search with DuckDuckGo, SearXNG or Google, suggestions and / commands
- settings page: name, search engine, wallpaper, account
- UI from collabry-components, copied into src/vendor/collabry
- Dockerfile and a Gitea workflow that checks the code, builds the image
  for amd64 and arm64 and pushes it to the registry on main
This commit is contained in:
Niklas Haiden
2026-11-18 00:09:19 +01:00
parent 54914e8e03
commit 8df74a849c
80 changed files with 9642 additions and 1572 deletions
+9
View File
@@ -0,0 +1,9 @@
.git
node_modules
.output
.nitro
.tanstack
# secrets stay out of the build context
.env*
*.log
.DS_Store
+23
View File
@@ -0,0 +1,23 @@
DATABASE_URL=postgres://dashboard:dashboard@localhost:5432/dashboard
# openssl rand -base64 32
BETTER_AUTH_SECRET=
# Public URL of this app (used for cookies and the OIDC callback)
BETTER_AUTH_URL=http://localhost:3000
# IPs or CIDRs of your reverse proxy, comma separated (e.g. 172.16.0.0/12).
# Needed for the per-client login rate limit.
TRUSTED_PROXIES=
# Set to "true" to close email/password registration
DISABLE_SIGNUP=false
# SSO (any OIDC provider: Keycloak, Authentik, Authelia, Entra ID, ...)
# Callback URL to register: ${BETTER_AUTH_URL}/api/auth/callback/sso
OIDC_DISCOVERY_URL=
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
OIDC_PROVIDER_NAME=SSO
# SearXNG instance (must be reachable from the browser and from this server)
SEARXNG_URL=
+95
View File
@@ -0,0 +1,95 @@
# Checks the code and builds the image for linux/amd64 + linux/arm64. On main it PUSHES the image to the registry as
# $REGISTRY_PATH/web, tagged :<short sha> and :latest. Pull requests build without pushing.
#
# Same runner, registry and conventions as typst-workspace (its docs/adr/0008-gitea-ci-multiarch.md):
# - repository variable REGISTRY_PATH (registry/project, e.g. reg.nhaiden.io/dahoam)
# - secrets HARBOR_USERNAME / HARBOR_PASSWORD (robot account with push to that Harbor project)
# - the runner has no QEMU: the Dockerfile cross-builds, never install binfmt here
# - every action is pinned by commit SHA (tag in the comment)
name: images
on:
push:
branches: [main] # one run per commit: with '**' every PR commit would run twice on the single runner
pull_request:
# PRs: a newer push cancels the running build. main: never cancelled, so a push is never cut off halfway.
concurrency:
group: images-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
check:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 (pnpm version: package.json packageManager)
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 26.13.1 # same as the image
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
- run: pnpm test
image:
needs: check
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Decide tags and whether to push
id: meta
env:
REGISTRY_PATH: ${{ vars.REGISTRY_PATH }}
run: |
set -euo pipefail
[ -n "$REGISTRY_PATH" ] || { echo '::error::repository variable REGISTRY_PATH is not set'; exit 1; }
sha=${GITHUB_SHA::7}
image="$REGISTRY_PATH/web"
push=false; tags="$image:$sha"
if [ "$GITHUB_EVENT_NAME" = push ] && [ "$GITHUB_REF" = refs/heads/main ]; then
push=true; tags+=$'\n'"$image:latest"
fi
{
echo "push=$push"
echo "registry=${REGISTRY_PATH%%/*}"
echo "tags<<EOF"; echo "$tags"; echo "EOF"
} >> "$GITHUB_OUTPUT"
echo "push=$push"; echo "$tags"
# A persistent BuildKit container (not removed after the job), so layer caches survive between runs on the
# single runner host. No binfmt/QEMU.
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
id: buildx
with:
name: dahoam-ci
driver-opts: image=moby/buildkit:v0.35.0@sha256:aa632b921ef07411d2cb77292cd34213d4f7b384001d6fceef1e1f25bf9752bb
cleanup: false
- name: Log in to the registry
if: steps.meta.outputs.push == 'true'
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
registry: ${{ steps.meta.outputs.registry }}
username: ${{ secrets.HARBOR_USERNAME }}
password: ${{ secrets.HARBOR_PASSWORD }}
- name: Build (linux/amd64, linux/arm64) and push on main
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: .
platforms: linux/amd64,linux/arm64
push: ${{ steps.meta.outputs.push == 'true' }}
outputs: ${{ steps.meta.outputs.push != 'true' && 'type=cacheonly' || '' }}
tags: ${{ steps.meta.outputs.tags }}
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.revision=${{ github.sha }}
# The persistent builder's cache otherwise grows without bound on the shared host (75 GB disk, it has been full).
- name: Cap the BuildKit cache
if: always() && steps.buildx.outcome == 'success'
run: docker buildx prune --builder dahoam-ci --max-used-space 3gb --force
+2
View File
@@ -14,3 +14,5 @@ todos.json
# typescript # typescript
*.tsbuildinfo *.tsbuildinfo
!.env.example
+2 -1
View File
@@ -1,3 +1,4 @@
package-lock.json package-lock.json
pnpm-lock.yaml pnpm-lock.yaml
yarn.lock yarn.locksrc/vendor
src/routeTree.gen.ts
+24
View File
@@ -0,0 +1,24 @@
# The build stage runs on the builder's own platform ($BUILDPLATFORM). The Nitro output is plain JS and the final
# stage has no RUN, so a linux/amd64 + linux/arm64 build needs no emulation (the CI runner has no QEMU).
FROM --platform=$BUILDPLATFORM node:26.13.1-alpine@sha256:6bd9ab43c0ec0190ca7b2d193906cb8b7edf6e7f4afa43ddeccd6452710bffb5 AS build
WORKDIR /app
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
# Node 26 images have no corepack: install the pnpm version from package.json's packageManager field.
RUN npm install -g "pnpm@$(node -p "require('./package.json').packageManager.split('@')[1]")" \
&& pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
# Self-contained Nitro output (dependencies are bundled): no node_modules install in the runtime image.
FROM node:26.13.1-alpine@sha256:6bd9ab43c0ec0190ca7b2d193906cb8b7edf6e7f4afa43ddeccd6452710bffb5
ENV NODE_ENV=production PORT=3000
WORKDIR /app
COPY --from=build --chown=node:node /app/.output ./
# The server applies these on start (src/db/index.ts).
COPY --chown=node:node drizzle ./drizzle
USER node
EXPOSE 3000
# /login needs the database, so healthy also means migrated.
HEALTHCHECK --interval=15s --timeout=5s --start-period=20s \
CMD node -e "fetch('http://127.0.0.1:3000/login').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"
CMD ["node", "server/index.mjs"]
+100
View File
@@ -0,0 +1,100 @@
# Dahoam — Plan
Replica of the reference start page (wallpaper, big serif clock, search bar,
app-icon row, "Everything else"), as a TanStack Start app with accounts.
Reference: https://pbs.twimg.com/media/HXSYNQ6XcAER0k9?format=jpg&name=4096x4096
## Stack
- TanStack Start (React 19, Vite 8), Tailwind 4
- UI: [collabry-components](https://git.nhaiden.io/niklas/collabry-components) copied into
`src/vendor/collabry` (replaced the scaffolded shadcn radix-nova set)
- Better Auth 1.7 — email/password + SSO (generic OIDC), Drizzle adapter
- Postgres 17 + Drizzle ORM (`postgres` driver), migrations via drizzle-kit
- Nitro (`nitro/vite`) for the production Node server
## Data model (`src/db/schema.ts`)
| Table | Columns |
|-------|---------|
| `user`, `session`, `account`, `verification` | Better Auth core tables |
| `link` | id, userId → user, name, url, icon (URL or dashboard-icons slug, optional), pinned, createdAt |
| `settings` | userId (PK) → user, title, searchEngine (`duckduckgo` \| `searxng` \| `google`), wallpaperUrl |
| `wallpaper` | userId (PK) → user, mime, data (bytea) |
Every row is scoped to its owner; all server functions check the session.
## Features
1. **Auth** — `/login` with sign in / sign up tabs and a "Continue with SSO" button
(only shown when OIDC env is set). `/` redirects to `/login` without a session.
`DISABLE_SIGNUP=true` closes registration.
2. **Dashboard** (`/`) — date, live clock, glass search bar, pinned links row,
"Everything else" section (unpinned links) below the fold, top bar with
title, add (+) and settings buttons, wallpaper credit + edit pencil.
3. **Home links** — add / edit / delete in a dialog (right-click or hover
pencil on a tile to edit). Icon fallback chain: custom icon →
dashboard-icons by name → site `/favicon.ico` → letter.
4. **Search**
- Engine per user: DuckDuckGo, SearXNG (when `SEARXNG_URL` is set), Google.
- Live suggestions proxied through the server (DuckDuckGo `/ac`, SearXNG `/autocompleter`).
- DuckDuckGo `!bangs` always route through DuckDuckGo.
- `/` focuses the bar; `/text` filters links and commands (add link, settings, sign out).
5. **Wallpaper** — paste an image URL or upload a file (stored in Postgres,
served from `/api/wallpaper`, ≤ 10 MB, jpeg/png/webp/avif). Reset to default.
Dither + vignette overlay like the reference.
## Files
```
docker-compose.yml Postgres for local dev
drizzle.config.ts
.env.example
src/db/{index,schema}.ts
src/lib/auth.ts Better Auth server config
src/lib/auth-client.ts
src/lib/auth.functions.ts getSession / ensureSession / authInfo
src/lib/dashboard.functions.ts links, settings, suggestions
src/lib/search.ts search URL builder (+ test)
src/routes/api/auth/$.ts
src/routes/api/wallpaper.ts
src/routes/login.tsx
src/routes/index.tsx
src/routes/settings.tsx
src/components/{clock,search-bar,link-tile,link-dialog,glass,wallpaper}.tsx
src/vendor/collabry/ copied Collabry components (do not edit)
scripts/sync-collabry.sh copies them from upstream at a pinned commit
```
## Steps
- [x] 1. Deps, docker-compose, env, Drizzle schema + first migration
- [x] 2. Better Auth (server, client, handler route, session helpers)
- [x] 3. Server functions: links, settings, suggestions; wallpaper route
- [x] 4. UI: login, dashboard, dialogs, search bar
- [x] 5. Verify: typecheck, lint, build, end-to-end against real Postgres, screenshot vs reference
- [x] 6. Independent review (subagent), fix findings, README
- [x] 7. Blurred card behind the top-row icons
- [x] 8. Collabry components: Button, Card, Field, Input, Checkbox, SegmentedControl, Dialog, Kbd,
ThemeProvider. Kept: wallpaper, serif clock, glass panels, Inter. Accent is near white.
- [x] 9. Settings page (`/settings`) replaces the settings dialog: General, Search, Wallpaper,
Account. Each setting saves on its own (`saveSettings` takes a patch).
- [x] 10. Cards: table `card`, `link.cardId` + `link.position` (replaces `pinned` and the
"Everything else" section; migration `0001_cards` moves existing links into cards).
Links are dragged inside and between cards with dnd-kit (`src/components/card-grid.tsx`,
layout logic and its test in `src/lib/layout.ts`).
- [x] 11. Image and CI: `Dockerfile` (multi-arch without emulation), `.gitea/workflows/images.yml`
(check, build, push to the Harbor registry on main, as in typst-workspace). The server applies
the migrations on start (`src/db/index.ts`).
- [x] 12. Renamed from "Home Dashboard" to Dahoam (slug `dahoam`): package, compose project, tab title,
default dashboard name, docs, CI examples.
## Not doing (not asked)
- Unraid version/uptime chip and the Sonarr/Plex notification pills from the screenshot
- Inline SearXNG result rendering (search opens the engine's result page)
- Reordering the cards themselves (they stay in the order they were made), free placement with
gaps in the grid, per-user SearXNG URL (SSRF risk — it is a server env)
- Email verification / password reset mail (needs an SMTP setup)
- In CI: version tags and releases, a Helm chart, an image vulnerability scan (typst-workspace has all three)
+75 -11
View File
@@ -1,21 +1,85 @@
# TanStack Start + shadcn/ui # Dahoam
This is a template for a new TanStack Start project with React, TypeScript, and shadcn/ui. A start page for your homelab: wallpaper, clock, search and your links.
TanStack Start, Collabry components, Better Auth, Drizzle and Postgres. See [PLAN.md](PLAN.md).
## Adding components ## Run
To add components to your app, run the following command:
```bash ```bash
npx shadcn@latest add button cp .env.example .env # then set BETTER_AUTH_SECRET (openssl rand -base64 32)
docker compose up -d # Postgres on localhost:5432
pnpm install
pnpm dev # http://localhost:3000
``` ```
This will place the ui components in the `components` directory. Production: `pnpm build && pnpm start` (reads `.env` when present, `PORT` sets the port).
## Using components The server applies the database migrations in `drizzle/` when it starts. If that fails, it stops.
To use the components in your app, import them as follows: ## Image and CI
```tsx `.gitea/workflows/images.yml` checks the code (typecheck, lint, tests) and builds the image for
import { Button } from "@/components/ui/button"; linux/amd64 and linux/arm64. A push to `main` also pushes it to the registry as
`$REGISTRY_PATH/web`, tagged `:<short sha>` and `:latest`. Pull requests only build.
The repository on Gitea needs:
- variable `REGISTRY_PATH`: registry and Harbor project, for example `reg.nhaiden.io/dahoam`
- secrets `HARBOR_USERNAME` and `HARBOR_PASSWORD`: a robot account that can push to that project
Run the image:
```bash
docker run -p 3000:3000 \
-e DATABASE_URL=postgres://user:password@host:5432/dashboard \
-e BETTER_AUTH_SECRET=... -e BETTER_AUTH_URL=https://home.example.com \
reg.nhaiden.io/dahoam/web:latest
``` ```
Build it yourself: `docker build -t dahoam .`
## Configuration
| Variable | Purpose |
|----------|---------|
| `DATABASE_URL` | Postgres connection string |
| `BETTER_AUTH_SECRET` | Signs sessions. Required. |
| `BETTER_AUTH_URL` | Public URL of the app |
| `TRUSTED_PROXIES` | IPs/CIDRs of your reverse proxy, comma separated. The login rate limit needs it to tell clients apart. |
| `DISABLE_SIGNUP` | `true` closes email/password registration. Set it after you made your account. |
| `OIDC_DISCOVERY_URL`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | Turns on the SSO button. Redirect URI: `<BETTER_AUTH_URL>/api/auth/callback/sso` |
| `OIDC_PROVIDER_NAME` | Text on the SSO button ("Continue with …") |
| `SEARXNG_URL` | Your SearXNG instance. Makes SearXNG selectable in Settings. |
## Use
- **Cards** group your links (Apps, Media, Bookmarks, ...). "New card" under the cards adds
one. Click a card's name to rename or delete it.
- **Links**: **+** at the top or on a card adds a link. Hover a link and click the pencil to
edit or delete it.
- **Move links** by dragging, inside a card or to another card. Touch: press and hold first.
Keyboard: focus a link, Space picks it up, arrow keys move it, Space puts it down.
- **Icons**: leave the field empty and the icon is looked up by name in
[dashboard-icons](https://github.com/homarr-labs/dashboard-icons), then from the
site's `/favicon.ico`. Or enter an icon name (`home-assistant`) or an image URL.
- **Search**: `/` focuses the bar. `!w cats` uses DuckDuckGo bangs. `/plex` jumps to
a link, `/settings`, `/add link`, `/add card` and `/sign out` run commands.
- **Wallpaper**: Settings (or the pencil at the bottom right) takes an image URL or an
upload (JPEG, PNG, WebP, AVIF, up to 10 MB).
## Notes
- Suggestions come from DuckDuckGo, or from SearXNG (`/autocompleter`) when it is the
selected engine. The server fetches them, the browser never calls those hosts directly.
- SSO does not take over an existing password account with the same email
(Better Auth blocks it, because password emails are not verified). Use one or the other per email.
- Icon lookups send the link name to the jsDelivr CDN.
- UI components come from [collabry-components](https://git.nhaiden.io/niklas/collabry-components),
copied into `src/vendor/collabry` at a pinned commit. Add or update one with
`scripts/sync-collabry.sh` (see `src/vendor/collabry/UPSTREAM.md`). The glass look is
applied from outside, in `src/components/glass.tsx` and `src/styles.css`.
- Schema changes: edit `src/db/schema.ts`, then `pnpm db:generate`. The server applies the new
migration on its next start (`pnpm db:migrate` does the same without a start).
- `pnpm test`, `pnpm typecheck`, `pnpm lint`.
Default wallpaper: photo by [Andrew Coelho](https://unsplash.com/photos/VB-w_3dnyvI) on Unsplash.
+1 -1
View File
@@ -14,7 +14,7 @@
"rtl": false, "rtl": false,
"aliases": { "aliases": {
"components": "@/components", "components": "@/components",
"utils": "@/lib/utils", "utils": "@/vendor/collabry/lib/cn",
"ui": "@/components/ui", "ui": "@/components/ui",
"lib": "@/lib", "lib": "@/lib",
"hooks": "@/hooks" "hooks": "@/hooks"
+21
View File
@@ -0,0 +1,21 @@
# Fixed, so the database volume (dahoam_db) does not depend on the directory name
name: dahoam
services:
db:
image: postgres:17-alpine
environment:
POSTGRES_USER: dashboard
POSTGRES_PASSWORD: dashboard
POSTGRES_DB: dashboard
ports:
- "127.0.0.1:5432:5432"
volumes:
- db:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U dashboard"]
interval: 2s
retries: 15
volumes:
db:
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "drizzle-kit"
try {
process.loadEnvFile()
} catch {
// no .env file: use the real environment
}
export default defineConfig({
dialect: "postgresql",
schema: "./src/db/schema.ts",
out: "./drizzle",
dbCredentials: { url: process.env.DATABASE_URL! },
})
+80
View File
@@ -0,0 +1,80 @@
CREATE TABLE "account" (
"id" text PRIMARY KEY NOT NULL,
"account_id" text NOT NULL,
"provider_id" text NOT NULL,
"user_id" text NOT NULL,
"access_token" text,
"refresh_token" text,
"id_token" text,
"access_token_expires_at" timestamp,
"refresh_token_expires_at" timestamp,
"scope" text,
"password" text,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "link" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" text NOT NULL,
"name" text NOT NULL,
"url" text NOT NULL,
"icon" text,
"pinned" boolean DEFAULT true NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "session" (
"id" text PRIMARY KEY NOT NULL,
"expires_at" timestamp NOT NULL,
"token" text NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
"ip_address" text,
"user_agent" text,
"user_id" text NOT NULL,
CONSTRAINT "session_token_unique" UNIQUE("token")
);
--> statement-breakpoint
CREATE TABLE "settings" (
"user_id" text PRIMARY KEY NOT NULL,
"title" text DEFAULT 'Home' NOT NULL,
"search_engine" text DEFAULT 'duckduckgo' NOT NULL,
"wallpaper_url" text
);
--> statement-breakpoint
CREATE TABLE "user" (
"id" text PRIMARY KEY NOT NULL,
"name" text NOT NULL,
"email" text NOT NULL,
"email_verified" boolean DEFAULT false NOT NULL,
"image" text,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
CONSTRAINT "user_email_unique" UNIQUE("email")
);
--> statement-breakpoint
CREATE TABLE "verification" (
"id" text PRIMARY KEY NOT NULL,
"identifier" text NOT NULL,
"value" text NOT NULL,
"expires_at" timestamp NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "wallpaper" (
"user_id" text PRIMARY KEY NOT NULL,
"mime" text NOT NULL,
"data" "bytea" NOT NULL
);
--> statement-breakpoint
ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "link" ADD CONSTRAINT "link_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "settings" ADD CONSTRAINT "settings_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "wallpaper" ADD CONSTRAINT "wallpaper_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "account_user_id_idx" ON "account" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "link_user_id_idx" ON "link" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "session_user_id_idx" ON "session" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "verification_identifier_idx" ON "verification" USING btree ("identifier");
+26
View File
@@ -0,0 +1,26 @@
CREATE TABLE "card" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" text NOT NULL,
"name" text NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "link" ADD COLUMN "card_id" uuid;--> statement-breakpoint
ALTER TABLE "link" ADD COLUMN "position" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
-- Hand-written: move existing links into cards. The old top row becomes "Apps",
-- the old "Everything else" section becomes a card of that name.
INSERT INTO "card" ("user_id", "name", "created_at")
SELECT DISTINCT "user_id", 'Apps', now() FROM "link" WHERE "pinned";--> statement-breakpoint
INSERT INTO "card" ("user_id", "name", "created_at")
SELECT DISTINCT "user_id", 'Everything else', now() + interval '1 second' FROM "link" WHERE NOT "pinned";--> statement-breakpoint
UPDATE "link" SET "card_id" = "card"."id" FROM "card"
WHERE "card"."user_id" = "link"."user_id"
AND "card"."name" = CASE WHEN "link"."pinned" THEN 'Apps' ELSE 'Everything else' END;--> statement-breakpoint
UPDATE "link" SET "position" = "ordered"."n" FROM (
SELECT "id", row_number() OVER (PARTITION BY "card_id" ORDER BY "created_at") - 1 AS "n" FROM "link"
) AS "ordered" WHERE "ordered"."id" = "link"."id";--> statement-breakpoint
ALTER TABLE "link" ALTER COLUMN "card_id" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "card" ADD CONSTRAINT "card_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "card_user_id_idx" ON "card" USING btree ("user_id");--> statement-breakpoint
ALTER TABLE "link" ADD CONSTRAINT "link_card_id_card_id_fk" FOREIGN KEY ("card_id") REFERENCES "public"."card"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "link_card_id_idx" ON "link" USING btree ("card_id");
+1
View File
@@ -0,0 +1 @@
ALTER TABLE "link" DROP COLUMN "pinned";
+3
View File
@@ -0,0 +1,3 @@
ALTER TABLE "settings" ALTER COLUMN "title" SET DEFAULT 'Dahoam';--> statement-breakpoint
-- Hand-written: rows that still carry the old default follow the rename.
UPDATE "settings" SET "title" = 'Dahoam' WHERE "title" = 'Home';
+562
View File
@@ -0,0 +1,562 @@
{
"id": "d6d3e10a-cbd0-4fad-aac1-74dece1c6a2f",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.account": {
"name": "account",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"account_id": {
"name": "account_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"access_token": {
"name": "access_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"id_token": {
"name": "id_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"access_token_expires_at": {
"name": "access_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"refresh_token_expires_at": {
"name": "refresh_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"scope": {
"name": "scope",
"type": "text",
"primaryKey": false,
"notNull": false
},
"password": {
"name": "password",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"account_user_id_idx": {
"name": "account_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"account_user_id_user_id_fk": {
"name": "account_user_id_user_id_fk",
"tableFrom": "account",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.link": {
"name": "link",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"url": {
"name": "url",
"type": "text",
"primaryKey": false,
"notNull": true
},
"icon": {
"name": "icon",
"type": "text",
"primaryKey": false,
"notNull": false
},
"pinned": {
"name": "pinned",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"link_user_id_idx": {
"name": "link_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"link_user_id_user_id_fk": {
"name": "link_user_id_user_id_fk",
"tableFrom": "link",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.session": {
"name": "session",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"ip_address": {
"name": "ip_address",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
}
},
"indexes": {
"session_user_id_idx": {
"name": "session_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"session_user_id_user_id_fk": {
"name": "session_user_id_user_id_fk",
"tableFrom": "session",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"session_token_unique": {
"name": "session_token_unique",
"nullsNotDistinct": false,
"columns": [
"token"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.settings": {
"name": "settings",
"schema": "",
"columns": {
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'Home'"
},
"search_engine": {
"name": "search_engine",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'duckduckgo'"
},
"wallpaper_url": {
"name": "wallpaper_url",
"type": "text",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {
"settings_user_id_user_id_fk": {
"name": "settings_user_id_user_id_fk",
"tableFrom": "settings",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.user": {
"name": "user",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email_verified": {
"name": "email_verified",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"user_email_unique": {
"name": "user_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.verification": {
"name": "verification",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"identifier": {
"name": "identifier",
"type": "text",
"primaryKey": false,
"notNull": true
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"verification_identifier_idx": {
"name": "verification_identifier_idx",
"columns": [
{
"expression": "identifier",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.wallpaper": {
"name": "wallpaper",
"schema": "",
"columns": {
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"mime": {
"name": "mime",
"type": "text",
"primaryKey": false,
"notNull": true
},
"data": {
"name": "data",
"type": "bytea",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {
"wallpaper_user_id_user_id_fk": {
"name": "wallpaper_user_id_user_id_fk",
"tableFrom": "wallpaper",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
+672
View File
@@ -0,0 +1,672 @@
{
"id": "cc18e0e4-b46a-47a3-81b5-2e76aa778b82",
"prevId": "d6d3e10a-cbd0-4fad-aac1-74dece1c6a2f",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.account": {
"name": "account",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"account_id": {
"name": "account_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"access_token": {
"name": "access_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"id_token": {
"name": "id_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"access_token_expires_at": {
"name": "access_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"refresh_token_expires_at": {
"name": "refresh_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"scope": {
"name": "scope",
"type": "text",
"primaryKey": false,
"notNull": false
},
"password": {
"name": "password",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"account_user_id_idx": {
"name": "account_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"account_user_id_user_id_fk": {
"name": "account_user_id_user_id_fk",
"tableFrom": "account",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.card": {
"name": "card",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"card_user_id_idx": {
"name": "card_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"card_user_id_user_id_fk": {
"name": "card_user_id_user_id_fk",
"tableFrom": "card",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.link": {
"name": "link",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"card_id": {
"name": "card_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"position": {
"name": "position",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"url": {
"name": "url",
"type": "text",
"primaryKey": false,
"notNull": true
},
"icon": {
"name": "icon",
"type": "text",
"primaryKey": false,
"notNull": false
},
"pinned": {
"name": "pinned",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"link_user_id_idx": {
"name": "link_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"link_card_id_idx": {
"name": "link_card_id_idx",
"columns": [
{
"expression": "card_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"link_user_id_user_id_fk": {
"name": "link_user_id_user_id_fk",
"tableFrom": "link",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"link_card_id_card_id_fk": {
"name": "link_card_id_card_id_fk",
"tableFrom": "link",
"tableTo": "card",
"columnsFrom": [
"card_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.session": {
"name": "session",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"ip_address": {
"name": "ip_address",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
}
},
"indexes": {
"session_user_id_idx": {
"name": "session_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"session_user_id_user_id_fk": {
"name": "session_user_id_user_id_fk",
"tableFrom": "session",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"session_token_unique": {
"name": "session_token_unique",
"nullsNotDistinct": false,
"columns": [
"token"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.settings": {
"name": "settings",
"schema": "",
"columns": {
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'Home'"
},
"search_engine": {
"name": "search_engine",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'duckduckgo'"
},
"wallpaper_url": {
"name": "wallpaper_url",
"type": "text",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {
"settings_user_id_user_id_fk": {
"name": "settings_user_id_user_id_fk",
"tableFrom": "settings",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.user": {
"name": "user",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email_verified": {
"name": "email_verified",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"user_email_unique": {
"name": "user_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.verification": {
"name": "verification",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"identifier": {
"name": "identifier",
"type": "text",
"primaryKey": false,
"notNull": true
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"verification_identifier_idx": {
"name": "verification_identifier_idx",
"columns": [
{
"expression": "identifier",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.wallpaper": {
"name": "wallpaper",
"schema": "",
"columns": {
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"mime": {
"name": "mime",
"type": "text",
"primaryKey": false,
"notNull": true
},
"data": {
"name": "data",
"type": "bytea",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {
"wallpaper_user_id_user_id_fk": {
"name": "wallpaper_user_id_user_id_fk",
"tableFrom": "wallpaper",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
+665
View File
@@ -0,0 +1,665 @@
{
"id": "f1546d58-4f33-4656-a009-ffb60031c504",
"prevId": "cc18e0e4-b46a-47a3-81b5-2e76aa778b82",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.account": {
"name": "account",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"account_id": {
"name": "account_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"access_token": {
"name": "access_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"id_token": {
"name": "id_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"access_token_expires_at": {
"name": "access_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"refresh_token_expires_at": {
"name": "refresh_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"scope": {
"name": "scope",
"type": "text",
"primaryKey": false,
"notNull": false
},
"password": {
"name": "password",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"account_user_id_idx": {
"name": "account_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"account_user_id_user_id_fk": {
"name": "account_user_id_user_id_fk",
"tableFrom": "account",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.card": {
"name": "card",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"card_user_id_idx": {
"name": "card_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"card_user_id_user_id_fk": {
"name": "card_user_id_user_id_fk",
"tableFrom": "card",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.link": {
"name": "link",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"card_id": {
"name": "card_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"position": {
"name": "position",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"url": {
"name": "url",
"type": "text",
"primaryKey": false,
"notNull": true
},
"icon": {
"name": "icon",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"link_user_id_idx": {
"name": "link_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"link_card_id_idx": {
"name": "link_card_id_idx",
"columns": [
{
"expression": "card_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"link_user_id_user_id_fk": {
"name": "link_user_id_user_id_fk",
"tableFrom": "link",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"link_card_id_card_id_fk": {
"name": "link_card_id_card_id_fk",
"tableFrom": "link",
"tableTo": "card",
"columnsFrom": [
"card_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.session": {
"name": "session",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"ip_address": {
"name": "ip_address",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
}
},
"indexes": {
"session_user_id_idx": {
"name": "session_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"session_user_id_user_id_fk": {
"name": "session_user_id_user_id_fk",
"tableFrom": "session",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"session_token_unique": {
"name": "session_token_unique",
"nullsNotDistinct": false,
"columns": [
"token"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.settings": {
"name": "settings",
"schema": "",
"columns": {
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'Home'"
},
"search_engine": {
"name": "search_engine",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'duckduckgo'"
},
"wallpaper_url": {
"name": "wallpaper_url",
"type": "text",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {
"settings_user_id_user_id_fk": {
"name": "settings_user_id_user_id_fk",
"tableFrom": "settings",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.user": {
"name": "user",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email_verified": {
"name": "email_verified",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"user_email_unique": {
"name": "user_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.verification": {
"name": "verification",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"identifier": {
"name": "identifier",
"type": "text",
"primaryKey": false,
"notNull": true
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"verification_identifier_idx": {
"name": "verification_identifier_idx",
"columns": [
{
"expression": "identifier",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.wallpaper": {
"name": "wallpaper",
"schema": "",
"columns": {
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"mime": {
"name": "mime",
"type": "text",
"primaryKey": false,
"notNull": true
},
"data": {
"name": "data",
"type": "bytea",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {
"wallpaper_user_id_user_id_fk": {
"name": "wallpaper_user_id_user_id_fk",
"tableFrom": "wallpaper",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
+665
View File
@@ -0,0 +1,665 @@
{
"id": "d6c6160d-4a0a-4e19-a093-40a1963aab9d",
"prevId": "f1546d58-4f33-4656-a009-ffb60031c504",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.account": {
"name": "account",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"account_id": {
"name": "account_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"access_token": {
"name": "access_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"id_token": {
"name": "id_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"access_token_expires_at": {
"name": "access_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"refresh_token_expires_at": {
"name": "refresh_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"scope": {
"name": "scope",
"type": "text",
"primaryKey": false,
"notNull": false
},
"password": {
"name": "password",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"account_user_id_idx": {
"name": "account_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"account_user_id_user_id_fk": {
"name": "account_user_id_user_id_fk",
"tableFrom": "account",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.card": {
"name": "card",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"card_user_id_idx": {
"name": "card_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"card_user_id_user_id_fk": {
"name": "card_user_id_user_id_fk",
"tableFrom": "card",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.link": {
"name": "link",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"card_id": {
"name": "card_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"position": {
"name": "position",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"url": {
"name": "url",
"type": "text",
"primaryKey": false,
"notNull": true
},
"icon": {
"name": "icon",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"link_user_id_idx": {
"name": "link_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"link_card_id_idx": {
"name": "link_card_id_idx",
"columns": [
{
"expression": "card_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"link_user_id_user_id_fk": {
"name": "link_user_id_user_id_fk",
"tableFrom": "link",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"link_card_id_card_id_fk": {
"name": "link_card_id_card_id_fk",
"tableFrom": "link",
"tableTo": "card",
"columnsFrom": [
"card_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.session": {
"name": "session",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"ip_address": {
"name": "ip_address",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
}
},
"indexes": {
"session_user_id_idx": {
"name": "session_user_id_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"session_user_id_user_id_fk": {
"name": "session_user_id_user_id_fk",
"tableFrom": "session",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"session_token_unique": {
"name": "session_token_unique",
"nullsNotDistinct": false,
"columns": [
"token"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.settings": {
"name": "settings",
"schema": "",
"columns": {
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'Dahoam'"
},
"search_engine": {
"name": "search_engine",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'duckduckgo'"
},
"wallpaper_url": {
"name": "wallpaper_url",
"type": "text",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {
"settings_user_id_user_id_fk": {
"name": "settings_user_id_user_id_fk",
"tableFrom": "settings",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.user": {
"name": "user",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email_verified": {
"name": "email_verified",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"user_email_unique": {
"name": "user_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.verification": {
"name": "verification",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"identifier": {
"name": "identifier",
"type": "text",
"primaryKey": false,
"notNull": true
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"verification_identifier_idx": {
"name": "verification_identifier_idx",
"columns": [
{
"expression": "identifier",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.wallpaper": {
"name": "wallpaper",
"schema": "",
"columns": {
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"mime": {
"name": "mime",
"type": "text",
"primaryKey": false,
"notNull": true
},
"data": {
"name": "data",
"type": "bytea",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {
"wallpaper_user_id_user_id_fk": {
"name": "wallpaper_user_id_user_id_fk",
"tableFrom": "wallpaper",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
+34
View File
@@ -0,0 +1,34 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1794908415585,
"tag": "0000_clumsy_the_hood",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1794910656991,
"tag": "0001_cards",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1794910673375,
"tag": "0002_drop_pinned",
"breakpoints": true
},
{
"idx": 3,
"version": "7",
"when": 1794956525569,
"tag": "0003_default_title",
"breakpoints": true
}
]
}
+1 -1
View File
@@ -16,6 +16,6 @@ export default [
}, },
}, },
{ {
ignores: ["eslint.config.js", ".prettierrc"], ignores: ["eslint.config.js", ".prettierrc", ".output", "src/vendor"],
}, },
] ]
+19 -5
View File
@@ -1,7 +1,8 @@
{ {
"name": "home-dashboard", "name": "dahoam",
"private": true, "private": true,
"type": "module", "type": "module",
"packageManager": "pnpm@12.18.0",
"scripts": { "scripts": {
"dev": "vite dev --port 3000", "dev": "vite dev --port 3000",
"generate-routes": "tsr generate", "generate-routes": "tsr generate",
@@ -10,24 +11,36 @@
"lint": "eslint", "lint": "eslint",
"format": "prettier --write \"**/*.{ts,tsx,js,jsx}\"", "format": "prettier --write \"**/*.{ts,tsx,js,jsx}\"",
"check": "prettier --check \"**/*.{ts,tsx,js,jsx}\"", "check": "prettier --check \"**/*.{ts,tsx,js,jsx}\"",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit",
"start": "node --env-file-if-exists=.env .output/server/index.mjs",
"test": "node --test \"src/**/*.test.ts\"",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate"
}, },
"dependencies": { "dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/inter": "^5.3.0", "@fontsource-variable/inter": "^5.3.0",
"@fontsource/dm-serif-display": "^5.3.0",
"@tailwindcss/vite": "^4", "@tailwindcss/vite": "^4",
"@tanstack/react-devtools": "latest", "@tanstack/react-devtools": "latest",
"@tanstack/react-router": "latest", "@tanstack/react-router": "latest",
"@tanstack/react-router-devtools": "latest", "@tanstack/react-router-devtools": "latest",
"@tanstack/react-start": "latest", "@tanstack/react-start": "latest",
"better-auth": "^1.7.25",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"cn": "^0.5.2", "clsx": "^2.1.1",
"drizzle-orm": "^0.45.4",
"lucide-react": "^1.73.0", "lucide-react": "^1.73.0",
"nitro": "3.0.261103-rc",
"postgres": "^4.1.1",
"radix-ui": "^1.8.1", "radix-ui": "^1.8.1",
"react": "^19.3.1", "react": "^19.3.1",
"react-dom": "^19.3.1", "react-dom": "^19.3.1",
"shadcn": "^4.23.0", "tailwind-merge": "^3.7.0",
"tailwindcss": "^4", "tailwindcss": "^4",
"tw-animate-css": "^1.4.0" "zod": "^4.6.7"
}, },
"devDependencies": { "devDependencies": {
"@tanstack/devtools-vite": "latest", "@tanstack/devtools-vite": "latest",
@@ -37,6 +50,7 @@
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@vitejs/plugin-react": "^6", "@vitejs/plugin-react": "^6",
"drizzle-kit": "^0.31.11",
"eslint": "^10", "eslint": "^10",
"prettier": "^3.9.10", "prettier": "^3.9.10",
"prettier-plugin-tailwindcss": "^0.8.1", "prettier-plugin-tailwindcss": "^0.8.1",
+1523 -1324
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"short_name": "TanStack App", "short_name": "Dahoam",
"name": "Create TanStack App Sample", "name": "Dahoam",
"icons": [ "icons": [
{ {
"src": "favicon.ico", "src": "favicon.ico",
Binary file not shown.

After

Width:  |  Height:  |  Size: 719 KiB

+68
View File
@@ -0,0 +1,68 @@
#!/bin/sh
# Copies the Collabry components this app uses into src/vendor/collabry.
# Usage: scripts/sync-collabry.sh [ref] (branch, tag or SHA; default: the pinned commit)
set -eu
UPSTREAM=https://git.nhaiden.io/niklas/collabry-components.git
REF=${1:-f94d10e8e9137724350cfd62389d9b84018b4f40}
DEST=src/vendor/collabry
# A part and the ui/ primitives it imports. Add a line, run the script again.
FILES="
lib/cn.ts
lib/portal.ts
styles/index.css
styles/tokens.css
components/ThemeProvider/ThemeProvider.tsx
components/Button/Button.tsx
components/Spinner/Spinner.tsx
components/Card/Card.tsx
components/Field/Field.tsx
components/Layout/Layout.tsx
components/Settings/Settings.tsx
components/SegmentedControl/SegmentedControl.tsx
components/ui/button.tsx
components/ui/card.tsx
components/ui/dialog.tsx
components/ui/input.tsx
components/ui/kbd.tsx
components/ui/label.tsx
components/ui/native-select.tsx
components/ui/radio-group.tsx
components/ui/textarea.tsx
components/ui/toggle.tsx
components/ui/toggle-group.tsx
"
cd "$(dirname "$0")/.."
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
git clone --quiet "$UPSTREAM" "$tmp"
git -C "$tmp" checkout --quiet "$REF"
rm -rf "$DEST"
for file in $FILES; do
mkdir -p "$DEST/$(dirname "$file")"
cp "$tmp/src/$file" "$DEST/$file"
done
cat > "$DEST/UPSTREAM.md" <<MD
# Vendored: Collabry components
Do not edit the files in this directory. They are copies of upstream \`src/\`, so a diff
against upstream stays empty. App components go in \`src/components/\`.
- Upstream: $UPSTREAM
- Commit: \`$(git -C "$tmp" rev-parse HEAD)\`
- Copied: only the files listed in \`scripts/sync-collabry.sh\`
- Local patches: none
Update or add a component: edit the list in \`scripts/sync-collabry.sh\`, then run
\`scripts/sync-collabry.sh [ref]\` and \`pnpm typecheck && pnpm build\`.
Upstream files import \`@/lib/…\` and \`@/components/ui/…\`. \`tsconfig.json\` maps \`@/*\` to
\`src/*\` first and to this directory second, so they resolve here without a rewrite.
Do not create \`src/lib/cn.ts\`, \`src/lib/portal.ts\` or \`src/components/ui/\`: they would
take the place of the vendored files.
The look is changed from outside: tokens in \`src/styles.css\`, classes in \`src/components/\`.
MD
+122
View File
@@ -0,0 +1,122 @@
import { useState } from "react"
import { useRouter } from "@tanstack/react-router"
import { Trash2 } from "lucide-react"
import { GlassDialogContent } from "@/components/glass"
import { deleteCard, saveCard } from "@/lib/dashboard.functions"
import { Button } from "@/vendor/collabry/components/Button/Button"
import {
Field,
FieldError,
FieldLabel,
Input,
} from "@/vendor/collabry/components/Field/Field"
import {
Dialog,
DialogBody,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/vendor/collabry/components/ui/dialog"
export type CardTarget = { id: string; name: string; links: unknown[] } | "new"
/** `card` is the card to edit, "new" to add one, or null when closed. */
export function CardDialog({
card,
onClose,
}: {
card: CardTarget | null
onClose: () => void
}) {
return (
<Dialog open={!!card} onOpenChange={(open) => !open && onClose()}>
<GlassDialogContent>
{card && (
<CardForm card={card === "new" ? null : card} onClose={onClose} />
)}
</GlassDialogContent>
</Dialog>
)
}
function CardForm({
card,
onClose,
}: {
card: Exclude<CardTarget, "new"> | null
onClose: () => void
}) {
const router = useRouter()
const [busy, setBusy] = useState(false)
const [error, setError] = useState("")
// deleting a card deletes its links, so it takes a second click
const [confirming, setConfirming] = useState(false)
const count = card?.links.length ?? 0
const submit = async (action: () => Promise<void>) => {
setBusy(true)
setError("")
try {
await action()
await router.invalidate()
onClose()
} catch {
setError("Could not save. Try again.")
setBusy(false)
}
}
return (
<form
onSubmit={(e) => {
e.preventDefault()
const name = String(new FormData(e.currentTarget).get("name"))
void submit(() => saveCard({ data: { id: card?.id, name } }))
}}
>
<DialogHeader>
<DialogTitle>{card ? "Edit card" : "New card"}</DialogTitle>
<DialogDescription>
A card groups links, for example Media, Network or Bookmarks.
</DialogDescription>
</DialogHeader>
<DialogBody>
<Field>
<FieldLabel>Name</FieldLabel>
<Input
name="name"
defaultValue={card?.name}
placeholder="Media"
maxLength={40}
required
/>
</Field>
{error && <FieldError role="alert">{error}</FieldError>}
</DialogBody>
<DialogFooter className="justify-between">
{card ? (
<Button
variant={confirming ? "danger" : "danger-outline"}
disabled={busy}
onClick={() =>
confirming || count === 0
? submit(() => deleteCard({ data: { id: card.id } }))
: setConfirming(true)
}
>
<Trash2 size={15} />
{confirming
? `Yes, delete the card and its ${count} ${count === 1 ? "link" : "links"}`
: "Delete"}
</Button>
) : (
<span />
)}
<Button type="submit" variant="primary" disabled={busy}>
{card ? "Save" : "Add card"}
</Button>
</DialogFooter>
</form>
)
}
+250
View File
@@ -0,0 +1,250 @@
import { useId, useRef, useState } from "react"
import { useRouter } from "@tanstack/react-router"
import {
DndContext,
DragOverlay,
KeyboardSensor,
MouseSensor,
TouchSensor,
closestCenter,
pointerWithin,
useDroppable,
useSensor,
useSensors,
} from "@dnd-kit/core"
import type {
Announcements,
CollisionDetection,
UniqueIdentifier,
} from "@dnd-kit/core"
import {
SortableContext,
rectSortingStrategy,
sortableKeyboardCoordinates,
} from "@dnd-kit/sortable"
import { Plus } from "lucide-react"
import { glass } from "@/components/glass"
import { LinkTile, TileFace } from "@/components/link-tile"
import type { HomeLink } from "@/components/link-tile"
import { moveLinks } from "@/lib/dashboard.functions"
import { drop, moveOver, order } from "@/lib/layout"
import { Button } from "@/vendor/collabry/components/Button/Button"
import { cn } from "@/vendor/collabry/lib/cn"
export type DashCard = { id: string; name: string; links: HomeLink[] }
type Handlers = {
onAddLink: (card: DashCard) => void
onEditLink: (link: HomeLink) => void
onEditCard: (card: DashCard) => void
}
/** The cards with their links. Links can be dragged inside a card and between cards. */
export function CardGrid({
cards: saved,
onAddCard,
...handlers
}: { cards: DashCard[]; onAddCard: () => void } & Handlers) {
const router = useRouter()
// the layout while a link is dragged, and until the server has stored it
const [dragged, setDragged] = useState<DashCard[] | null>(null)
const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null)
const drags = useRef(0)
const cards = dragged ?? saved
const links = cards.flatMap((c) => c.links)
const active = links.find((l) => l.id === activeId)
const sensors = useSensors(
// a few pixels of slack, so a plain click still opens the link
useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),
// long press, so a swipe still scrolls the page
useSensor(TouchSensor, {
activationConstraint: { delay: 220, tolerance: 8 },
}),
// Space picks up and puts down. Enter stays free to open the link.
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
keyboardCodes: {
start: ["Space"],
cancel: ["Escape"],
end: ["Space", "Enter"],
},
})
)
// First the card under the pointer, then the nearest link inside that card.
// Plain closestCenter picks the card's own center too often to sort inside it.
const collision: CollisionDetection = (args) => {
const only = (ids: string[]) => ({
...args,
droppableContainers: args.droppableContainers.filter((d) =>
ids.includes(String(d.id))
),
})
const cardArgs = only(cards.map((c) => c.id))
// the keyboard has no pointer: take the nearest card then
const hit = pointerWithin(cardArgs).at(0) ?? closestCenter(cardArgs).at(0)
const card = cards.find((c) => c.id === hit?.id)
if (!hit || !card) return []
const nearest = closestCenter(only(card.links.map((l) => l.id)))
return nearest.length ? nearest : [hit]
}
const finish = async (next: DashCard[]) => {
setActiveId(null)
if (JSON.stringify(order(next)) === JSON.stringify(order(saved)))
return setDragged(null)
setDragged(next)
const drag = drags.current
// on failure the reload below puts the links back where they were
await moveLinks({ data: { cards: order(next) } }).catch(() => {})
await router.invalidate()
// a newer drag owns the layout by now
if (drags.current === drag) setDragged(null)
}
// screen readers hear names, not ids
const name = (id: UniqueIdentifier) =>
links.find((l) => l.id === id)?.name ?? cards.find((c) => c.id === id)?.name
const cardName = (id: UniqueIdentifier) =>
cards.find((c) => c.id === id || c.links.some((l) => l.id === id))?.name
const announcements: Announcements = {
onDragStart: ({ active: a }) => `Picked up ${name(a.id)}.`,
onDragOver: ({ active: a, over }) =>
over ? `${name(a.id)} is in ${cardName(over.id)}.` : undefined,
onDragEnd: ({ active: a, over }) =>
over
? `${name(a.id)} was put down in ${cardName(over.id)}.`
: `${name(a.id)} was put back.`,
onDragCancel: ({ active: a }) => `${name(a.id)} was put back.`,
}
return (
<DndContext
// a fixed id keeps the generated ARIA ids equal on server and client
id="cards"
sensors={sensors}
collisionDetection={collision}
accessibility={{ announcements }}
onDragStart={({ active: a }) => {
drags.current++
setActiveId(a.id)
setDragged(cards)
}}
onDragOver={({ active: a, over }) => {
if (over) setDragged(moveOver(cards, String(a.id), String(over.id)))
}}
onDragEnd={({ active: a, over }) =>
finish(over ? drop(cards, String(a.id), String(over.id)) : cards)
}
onDragCancel={() => {
setActiveId(null)
setDragged(null)
}}
>
<div className="flex w-full max-w-6xl flex-wrap items-start justify-center gap-4">
{cards.map((card) => (
<CardPanel
key={card.id}
card={card}
// the card the dragged link would land in
target={card.links.some((l) => l.id === activeId)}
{...handlers}
/>
))}
</div>
<Button
variant="ghost"
className="mt-4 rounded-full text-white/60 hover:bg-white/10 hover:text-white"
onClick={onAddCard}
>
<Plus className="size-4" /> New card
</Button>
<DragOverlay>
{active && (
<TileFace
link={active}
className="cursor-grabbing rounded-2xl bg-white/15 shadow-2xl"
/>
)}
</DragOverlay>
</DndContext>
)
}
function CardPanel({
card,
target,
onAddLink,
onEditLink,
onEditCard,
}: { card: DashCard; target: boolean } & Handlers) {
const titleId = useId()
const { setNodeRef } = useDroppable({ id: card.id })
const subtle =
"rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-white/60"
return (
<section
ref={setNodeRef}
aria-labelledby={titleId}
className={cn(
glass,
"group/card max-w-full rounded-3xl p-2 transition-colors",
target && "border-white/30"
)}
>
<header className="flex h-8 items-center gap-2 pr-1 pl-3">
<h2 id={titleId} className="m-0 min-w-0 text-sm">
<button
type="button"
title="Rename or delete this card"
onClick={() => onEditCard(card)}
className={cn(
subtle,
"max-w-full truncate font-bold text-white/70 hover:text-white"
)}
>
{card.name}
</button>
</h2>
<button
type="button"
aria-label={`Add a link to ${card.name}`}
onClick={() => onAddLink(card)}
className={cn(
subtle,
"ml-auto grid size-7 flex-none place-items-center text-white/70 opacity-0 transition-opacity group-hover/card:opacity-100 hover:bg-white/10 hover:text-white focus-visible:opacity-100 pointer-coarse:opacity-100"
)}
>
<Plus className="size-4" />
</button>
</header>
<SortableContext
items={card.links.map((l) => l.id)}
strategy={rectSortingStrategy}
>
<div className="flex min-h-[7.5rem] max-w-[50rem] min-w-52 flex-wrap gap-x-1 gap-y-2">
{card.links.map((link) => (
<LinkTile
key={link.id}
link={link}
onEdit={() => onEditLink(link)}
/>
))}
{card.links.length === 0 && (
<button
type="button"
onClick={() => onAddLink(card)}
className={cn(
subtle,
"min-h-[7.5rem] flex-1 rounded-2xl px-4 text-sm text-white/50 hover:bg-white/5 hover:text-white/80"
)}
>
Add a link, or drag one here
</button>
)}
</div>
</SortableContext>
</section>
)
}
+61
View File
@@ -0,0 +1,61 @@
import { useSyncExternalStore } from "react"
import { cn } from "@/vendor/collabry/lib/cn"
const subscribe = (tick: () => void) => {
const timer = setInterval(tick, 1000)
return () => clearInterval(timer)
}
// changes once a minute, so the clock re-renders once a minute
const currentMinute = () => Math.floor(Date.now() / 60_000)
export function Clock() {
// null on the server: its clock and locale are not the visitor's
const minute = useSyncExternalStore<number | null>(
subscribe,
currentMinute,
() => null
)
const now = minute === null ? null : new Date(minute * 60_000)
const parts = now
? new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
}).formatToParts(now)
: []
const time = parts
.filter((p) => p.type !== "dayPeriod")
.map((p) => p.value)
.join("")
.trim()
const period = parts.find((p) => p.type === "dayPeriod")?.value
return (
<div
className={cn(
"flex flex-col items-center text-white transition-opacity duration-500 [text-shadow:0_2px_24px_rgb(0_0_0/0.45)]",
!now && "opacity-0"
)}
>
<p className="text-lg font-medium sm:text-xl">
{now
? now.toLocaleDateString(undefined, {
weekday: "long",
month: "long",
day: "numeric",
})
: "\u00a0"}
</p>
<time
dateTime={now?.toISOString()}
className="relative mt-2 font-serif text-7xl leading-none tracking-wide sm:text-[9.5rem]"
>
{time || "0:00"}
{period && (
<span className="absolute top-1 left-full ml-2 text-xl tracking-normal sm:top-3 sm:ml-4 sm:text-3xl">
{period}
</span>
)}
</time>
</div>
)
}
+45
View File
@@ -0,0 +1,45 @@
import type { ComponentProps } from "react"
import { X } from "lucide-react"
import {
DialogClose,
DialogContent,
closeButtonClass,
} from "@/vendor/collabry/components/ui/dialog"
import { cn } from "@/vendor/collabry/lib/cn"
/** The dark blurred panel that every surface on the wallpaper uses. */
export const glass =
"border border-white/10 bg-black/45 shadow-2xl shadow-black/40 backdrop-blur-xl"
/** For Collabry's `CardFrame` (and `SettingsSection`): glass rim, glass card inside. */
export const glassFrame = cn(
glass,
"bg-black/25 [&>*]:border-white/10 [&>*]:bg-black/45"
)
/** Collabry dialog as a glass panel, with an English label on the close button. */
export function GlassDialogContent({
className,
children,
...props
}: ComponentProps<typeof DialogContent>) {
return (
<DialogContent
showCloseButton={false}
className={cn(
glass,
"w-[440px] bg-black/65 backdrop-blur-2xl",
className
)}
{...props}
>
{children}
<DialogClose
aria-label="Close"
className={cn(closeButtonClass, "absolute top-5 right-4")}
>
<X size={16} strokeWidth={1.75} />
</DialogClose>
</DialogContent>
)
}
+165
View File
@@ -0,0 +1,165 @@
import { useState } from "react"
import { useRouter } from "@tanstack/react-router"
import { Trash2 } from "lucide-react"
import { GlassDialogContent } from "@/components/glass"
import type { HomeLink } from "@/components/link-tile"
import { deleteLink, saveLink } from "@/lib/dashboard.functions"
import { Button } from "@/vendor/collabry/components/Button/Button"
import {
Field,
FieldDescription,
FieldError,
FieldLabel,
FieldNote,
Input,
Select,
SelectOption,
} from "@/vendor/collabry/components/Field/Field"
import {
Dialog,
DialogBody,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/vendor/collabry/components/ui/dialog"
/** A link to edit, or only the card that a new link starts in. */
export type LinkTarget = HomeLink | { cardId: string }
export function LinkDialog({
target,
cards,
onClose,
}: {
target: LinkTarget | null
cards: { id: string; name: string }[]
onClose: () => void
}) {
return (
<Dialog open={!!target} onOpenChange={(open) => !open && onClose()}>
<GlassDialogContent>
{target && <LinkForm target={target} cards={cards} onClose={onClose} />}
</GlassDialogContent>
</Dialog>
)
}
function LinkForm({
target,
cards,
onClose,
}: {
target: LinkTarget
cards: { id: string; name: string }[]
onClose: () => void
}) {
const link = "id" in target ? target : null
const router = useRouter()
const [busy, setBusy] = useState(false)
const [error, setError] = useState("")
const submit = async (action: () => Promise<void>) => {
setBusy(true)
setError("")
try {
await action()
await router.invalidate()
onClose()
} catch {
setError("Could not save. Check the address and try again.")
setBusy(false)
}
}
return (
<form
onSubmit={(e) => {
e.preventDefault()
const form = new FormData(e.currentTarget)
void submit(() =>
saveLink({
data: {
id: link?.id,
cardId: String(form.get("cardId")),
name: String(form.get("name")),
url: String(form.get("url")),
icon: String(form.get("icon")).trim() || null,
},
})
)
}}
>
<DialogHeader>
<DialogTitle>{link ? "Edit link" : "Add link"}</DialogTitle>
<DialogDescription>
An application or a website. Drag it on the dashboard to move it.
</DialogDescription>
</DialogHeader>
<DialogBody>
<Field>
<FieldLabel>Name</FieldLabel>
<Input
name="name"
defaultValue={link?.name}
placeholder="Plex"
maxLength={60}
required
/>
</Field>
<Field>
<FieldLabel>Address</FieldLabel>
<Input
name="url"
type="url"
defaultValue={link?.url}
placeholder="https://plex.example.com"
pattern="https?://.+"
title="An address that starts with http:// or https://"
required
/>
</Field>
<Field>
<FieldLabel>
Icon <FieldNote>(optional)</FieldNote>
</FieldLabel>
<Input
name="icon"
defaultValue={link?.icon ?? ""}
placeholder="Image URL or icon name, e.g. plex"
/>
<FieldDescription>
Empty: found from the name, then from the site's favicon.
</FieldDescription>
</Field>
<Field>
<FieldLabel>Card</FieldLabel>
<Select name="cardId" defaultValue={target.cardId}>
{cards.map((card) => (
<SelectOption key={card.id} value={card.id}>
{card.name}
</SelectOption>
))}
</Select>
</Field>
{error && <FieldError role="alert">{error}</FieldError>}
</DialogBody>
<DialogFooter className="justify-between">
{link ? (
<Button
variant="danger-outline"
disabled={busy}
onClick={() => submit(() => deleteLink({ data: { id: link.id } }))}
>
<Trash2 size={15} /> Delete
</Button>
) : (
<span />
)}
<Button type="submit" variant="primary" disabled={busy}>
{link ? "Save" : "Add link"}
</Button>
</DialogFooter>
</form>
)
}
+137
View File
@@ -0,0 +1,137 @@
import { useEffect, useRef, useState } from "react"
import { useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { Pencil } from "lucide-react"
import { cn } from "@/vendor/collabry/lib/cn"
export type HomeLink = {
id: string
cardId: string
name: string
url: string
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. */
export function LinkIcon(props: IconProps) {
const { id, name, url, icon } = props.link
return <Icon key={[id, name, url, icon].join("|")} {...props} />
}
function Icon({ link, className }: IconProps) {
const sources = iconSources(link)
const [index, setIndex] = useState(0)
const img = useRef<HTMLImageElement>(null)
const next = () => setIndex((i) => i + 1)
// an image that failed before hydration never fires onError
useEffect(() => {
if (img.current?.complete && img.current.naturalWidth === 0) next()
}, [index])
if (index >= sources.length)
return (
<span
className={cn(
"grid place-items-center rounded-2xl bg-white/15 font-serif text-2xl text-white uppercase",
className
)}
>
{link.name[0]}
</span>
)
return (
<img
ref={img}
src={sources[index]}
alt=""
referrerPolicy="no-referrer"
draggable={false}
onError={next}
className={cn("rounded-2xl object-contain drop-shadow-lg", className)}
/>
)
}
const tile =
"flex w-24 flex-col items-center gap-2.5 rounded-2xl px-2 py-3 text-base text-white/90"
/** Icon and name. Also what follows the pointer while a link is dragged. */
export function TileFace({
link,
className,
}: {
link: HomeLink
className?: string
}) {
return (
<span className={cn(tile, className)}>
<LinkIcon link={link} className="size-14" />
<span className="line-clamp-2 w-full text-center leading-tight break-words [text-shadow:0_1px_8px_rgb(0_0_0/0.6)]">
{link.name}
</span>
</span>
)
}
/** A link in a card. Drag it (mouse, long press, or Space and the arrow keys) to move it. */
export function LinkTile({
link,
onEdit,
}: {
link: HomeLink
onEdit: () => void
}) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: link.id })
return (
<div
ref={setNodeRef}
style={{ transform: CSS.Translate.toString(transform), transition }}
className={cn("group relative", isDragging && "opacity-30")}
>
<a
href={link.url}
rel="noreferrer"
// the browser's own link drag would win over ours
draggable={false}
aria-describedby={attributes["aria-describedby"]}
{...listeners}
className="block touch-manipulation rounded-2xl transition-colors outline-none select-none [-webkit-touch-callout:none] hover:bg-white/10 focus-visible:bg-white/10 focus-visible:ring-2 focus-visible:ring-white/60"
>
<TileFace link={link} />
</a>
<button
type="button"
aria-label={`Edit ${link.name}`}
onClick={onEdit}
className="absolute top-1 right-1 grid size-6 place-items-center rounded-full bg-black/70 text-white opacity-0 transition-opacity outline-none group-hover:opacity-100 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-white/60 pointer-coarse:opacity-80"
>
<Pencil className="size-3" />
</button>
</div>
)
}
+178
View File
@@ -0,0 +1,178 @@
import { useEffect, useRef, useState } from "react"
import type { ReactNode } from "react"
import { Search } from "lucide-react"
import { glass } from "@/components/glass"
import { Kbd } from "@/vendor/collabry/components/ui/kbd"
import { cn } from "@/vendor/collabry/lib/cn"
import { LinkIcon } from "@/components/link-tile"
import type { HomeLink } from "@/components/link-tile"
import { suggest } from "@/lib/dashboard.functions"
import { ENGINE_NAMES, effectiveEngine, searchUrl } from "@/lib/search"
import type { Engine } from "@/lib/search"
export type Command = { label: string; icon: ReactNode; run: () => void }
export function SearchBar({
links,
commands,
engine,
searxngUrl,
}: {
links: HomeLink[]
commands: Command[]
engine: Engine
searxngUrl: string | null
}) {
const [value, setValue] = useState("")
const [fetched, setFetched] = useState<string[]>([])
const [active, setActive] = useState(-1)
const [focused, setFocused] = useState(false)
const input = useRef<HTMLInputElement>(null)
const used = effectiveEngine(engine, searxngUrl)
const query = value.trim()
const commandMode = value.startsWith("/")
const search = (q: string) =>
window.location.assign(searchUrl(q, engine, searxngUrl))
// "/" anywhere on the page jumps to the search bar
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key !== "/" || e.metaKey || e.ctrlKey || e.altKey) return
if ((e.target as Element).closest("input, textarea, [role=dialog]"))
return
e.preventDefault()
input.current?.focus()
}
window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
}, [])
useEffect(() => {
if (!query || commandMode) return
let stale = false
const timer = setTimeout(async () => {
const result = await suggest({
data: { q: query, searxng: used === "searxng" },
}).catch(() => [])
if (stale) return
setFetched(result)
setActive(-1) // the highlighted row now holds another suggestion
}, 150)
return () => {
stale = true
clearTimeout(timer)
}
}, [query, commandMode, used])
const needle = value.slice(1).trim().toLowerCase()
const items: Command[] = commandMode
? [
...links.map((link) => ({
label: link.name,
icon: <LinkIcon link={link} className="size-5 rounded-md" />,
run: () => window.location.assign(link.url),
})),
...commands,
].filter((item) => item.label.toLowerCase().includes(needle))
: query
? fetched.map((s) => ({
label: s,
icon: <Search className="size-4 opacity-60" />,
run: () => search(s),
}))
: []
const open = focused && items.length > 0
const run = (item: Command) => {
setValue("")
input.current?.blur()
item.run()
}
return (
<form
role="search"
className="relative w-full max-w-[680px]"
onSubmit={(e) => {
e.preventDefault()
// in command mode Enter takes the best match
const item =
active >= 0 ? items[active] : commandMode ? items[0] : undefined
if (item) run(item)
else if (query && !commandMode) search(query)
}}
>
<label
className={cn(
glass,
"flex h-14 items-center gap-3.5 rounded-2xl px-5 text-white focus-within:border-white/25"
)}
>
<Search className="size-[18px] shrink-0 opacity-70" />
<input
ref={input}
value={value}
onChange={(e) => {
setValue(e.target.value)
setActive(-1)
}}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onKeyDown={(e) => {
if (e.key === "Escape") e.currentTarget.blur()
if (!open || (e.key !== "ArrowDown" && e.key !== "ArrowUp")) return
e.preventDefault()
const step = e.key === "ArrowDown" ? 1 : -1
setActive((active + step + items.length) % items.length)
}}
placeholder={`Search ${ENGINE_NAMES[used]}, or type / for commands`}
aria-label="Search"
role="combobox"
aria-expanded={open}
aria-controls="search-items"
aria-activedescendant={
active >= 0 ? `search-item-${active}` : undefined
}
autoComplete="off"
autoCapitalize="off"
spellCheck={false}
className="h-full min-w-0 flex-1 bg-transparent text-lg outline-none placeholder:text-white/60"
/>
<Kbd className="border-white/20 bg-transparent text-white/60">/</Kbd>
</label>
{open && (
<ul
id="search-items"
role="listbox"
// keep the input focused while an item is clicked
onMouseDown={(e) => e.preventDefault()}
className={cn(
glass,
"absolute inset-x-0 top-full z-20 m-0 mt-2 max-h-80 list-none overflow-y-auto rounded-2xl bg-black/75 p-1.5 text-md text-white"
)}
>
{items.map((item, i) => (
<li
key={i}
id={`search-item-${i}`}
role="option"
aria-selected={i === active}
onClick={() => run(item)}
onMouseMove={() => setActive(i)}
className={cn(
"flex cursor-pointer items-center gap-3 rounded-xl px-3.5 py-2.5",
i === active && "bg-white/10"
)}
>
<span className="grid size-5 place-items-center">
{item.icon}
</span>
<span className="truncate">{item.label}</span>
</li>
))}
</ul>
)}
</form>
)
}
-66
View File
@@ -1,66 +0,0 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { Slot } from "radix-ui"
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/80",
outline:
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
destructive:
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default:
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
icon: "size-8",
"icon-xs":
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
"icon-sm":
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
"icon-lg": "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
+23
View File
@@ -0,0 +1,23 @@
export const DEFAULT_WALLPAPER = "/wallpaper.jpg"
function showDefault(img: HTMLImageElement) {
if (!img.src.endsWith(DEFAULT_WALLPAPER)) img.src = DEFAULT_WALLPAPER
}
export function Wallpaper({ src }: { src?: string | null }) {
return (
<div className="fixed inset-0 -z-10 bg-black" aria-hidden>
<img
src={src ?? DEFAULT_WALLPAPER}
alt=""
className="size-full object-cover"
// an image that failed before hydration never fires onError
ref={(img) => {
if (img?.complete && img.naturalWidth === 0) showDefault(img)
}}
onError={(e) => showDefault(e.currentTarget)}
/>
<div className="absolute inset-0 wallpaper-dither" />
</div>
)
}
+22
View File
@@ -0,0 +1,22 @@
import { drizzle } from "drizzle-orm/postgres-js"
import { migrate } from "drizzle-orm/postgres-js/migrator"
import * as schema from "./schema"
if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is not set")
export const db = drizzle({
schema,
connection: {
url: process.env.DATABASE_URL,
// the migrator's "already exists, skipping" on every start looks like an error in the log
onnotice: () => {},
},
})
// The server brings the database up to date before it answers its first request
// (the image has no drizzle-kit). A server on an old schema must not run: stop,
// so that the restart policy tries again.
await migrate(db, { migrationsFolder: "drizzle" }).catch((error) => {
console.error("Database migration failed:", error)
process.exit(1)
})
+138
View File
@@ -0,0 +1,138 @@
import {
boolean,
customType,
index,
integer,
pgTable,
text,
timestamp,
uuid,
} from "drizzle-orm/pg-core"
// ---- Better Auth core tables ----
export const user = pgTable("user", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: boolean("email_verified").notNull().default(false),
image: text("image"),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
})
export const session = pgTable(
"session",
{
id: text("id").primaryKey(),
expiresAt: timestamp("expires_at").notNull(),
token: text("token").notNull().unique(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
},
(t) => [index("session_user_id_idx").on(t.userId)]
)
export const account = pgTable(
"account",
{
id: text("id").primaryKey(),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
idToken: text("id_token"),
accessTokenExpiresAt: timestamp("access_token_expires_at"),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
scope: text("scope"),
password: text("password"),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
},
(t) => [index("account_user_id_idx").on(t.userId)]
)
export const verification = pgTable(
"verification",
{
id: text("id").primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
},
(t) => [index("verification_identifier_idx").on(t.identifier)]
)
// ---- Dashboard tables ----
const bytea = customType<{ data: Uint8Array }>({ dataType: () => "bytea" })
/** A named group of links on the dashboard. */
export const card = pgTable(
"card",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
name: text("name").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
},
(t) => [index("card_user_id_idx").on(t.userId)]
)
export const link = pgTable(
"link",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
cardId: uuid("card_id")
.notNull()
.references(() => card.id, { onDelete: "cascade" }),
// order inside the card
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
icon: text("icon"),
createdAt: timestamp("created_at").notNull().defaultNow(),
},
(t) => [
index("link_user_id_idx").on(t.userId),
index("link_card_id_idx").on(t.cardId),
]
)
export const settings = pgTable("settings", {
userId: text("user_id")
.primaryKey()
.references(() => user.id, { onDelete: "cascade" }),
title: text("title").notNull().default("Dahoam"),
searchEngine: text("search_engine", {
enum: ["duckduckgo", "searxng", "google"],
})
.notNull()
.default("duckduckgo"),
// null = bundled default wallpaper
wallpaperUrl: text("wallpaper_url"),
})
export const wallpaper = pgTable("wallpaper", {
userId: text("user_id")
.primaryKey()
.references(() => user.id, { onDelete: "cascade" }),
mime: text("mime").notNull(),
data: bytea("data").notNull(),
})
+3
View File
@@ -0,0 +1,3 @@
import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient()
+54
View File
@@ -0,0 +1,54 @@
import { betterAuth } from "better-auth"
import { drizzleAdapter } from "better-auth/adapters/drizzle"
import { genericOAuth } from "better-auth/plugins"
import { tanstackStartCookies } from "better-auth/tanstack-start"
import { getRequestHeaders } from "@tanstack/react-start/server"
import { db } from "@/db"
import * as schema from "@/db/schema"
const {
OIDC_DISCOVERY_URL: discoveryUrl,
OIDC_CLIENT_ID: clientId,
OIDC_CLIENT_SECRET: clientSecret,
} = process.env
const sso = discoveryUrl && clientId && clientSecret
export const SSO_PROVIDER_ID = "sso"
export const ssoName = sso ? process.env.OIDC_PROVIDER_NAME || "SSO" : null
export const signUpEnabled = process.env.DISABLE_SIGNUP !== "true"
export const auth = betterAuth({
baseURL: process.env.BETTER_AUTH_URL,
database: drizzleAdapter(db, { provider: "pg", schema }),
emailAndPassword: { enabled: true, disableSignUp: !signUpEnabled },
// without this the login rate limit cannot tell clients apart behind a proxy
advanced: {
ipAddress: {
trustedProxies: process.env.TRUSTED_PROXIES?.split(",").filter(Boolean),
},
},
plugins: [
...(sso
? [
genericOAuth({
config: [
{
providerId: SSO_PROVIDER_ID,
discoveryUrl,
clientId,
clientSecret,
scopes: ["openid", "email", "profile"],
},
],
}),
]
: []),
tanstackStartCookies(), // must stay last
],
})
export async function requireUser() {
const session = await auth.api.getSession({ headers: getRequestHeaders() })
if (!session) throw new Error("Unauthorized")
return session.user
}
+221
View File
@@ -0,0 +1,221 @@
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 { db } from "@/db"
import { card, link, settings, wallpaper } from "@/db/schema"
import { auth, requireUser, signUpEnabled, ssoName } from "@/lib/auth"
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")
}
/** 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. */
export const getDashboard = createServerFn({ method: "GET" }).handler(
async () => {
const session = await auth.api.getSession({ headers: getRequestHeaders() })
if (!session) return null
const userId = session.user.id
const [cards, links, rows] = await Promise.all([
db
.select({ id: card.id, name: card.name })
.from(card)
.where(eq(card.userId, userId))
.orderBy(asc(card.createdAt)),
db
.select({
id: link.id,
cardId: link.cardId,
name: link.name,
url: link.url,
icon: link.icon,
})
.from(link)
.where(eq(link.userId, userId))
.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" })
.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 },
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,
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),
})
)
.handler(async ({ data: { id, name } }) => {
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 db.insert(card).values({ name, userId: user.id })
}
})
/** 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),
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(),
})
.partial()
.refine((patch) => Object.keys(patch).length > 0)
)
.handler(async ({ data }) => {
const user = await requireUser()
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
}
})
+38
View File
@@ -0,0 +1,38 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { drop, moveOver, order } from "./layout.ts"
const cards = () => [
{ id: "apps", links: [{ id: "a" }, { id: "b" }, { id: "c" }] },
{ id: "web", links: [{ id: "x" }] },
{ id: "empty", links: [] },
]
const ids = (layout: ReturnType<typeof cards>) =>
order(layout).map((c) => c.linkIds.join(""))
test("drop reorders inside a card", () => {
assert.deepEqual(ids(drop(cards(), "a", "c")), ["bca", "x", ""])
assert.deepEqual(ids(drop(cards(), "c", "a")), ["cab", "x", ""])
})
test("drop on itself or on its own card changes nothing", () => {
const before = cards()
assert.equal(drop(before, "a", "a"), before)
assert.equal(drop(before, "a", "apps"), before)
})
test("a link moves to another card, at the link it is over", () => {
assert.deepEqual(ids(moveOver(cards(), "a", "x")), ["bc", "ax", ""])
assert.deepEqual(ids(drop(cards(), "a", "x")), ["bc", "ax", ""])
})
test("a link dropped on a card goes to its end", () => {
assert.deepEqual(ids(drop(cards(), "a", "web")), ["bc", "xa", ""])
assert.deepEqual(ids(drop(cards(), "a", "empty")), ["bc", "x", "a"])
})
test("unknown ids change nothing", () => {
const before = cards()
assert.equal(drop(before, "nope", "x"), before)
assert.equal(drop(before, "a", "nope"), before)
})
+50
View File
@@ -0,0 +1,50 @@
// Where links sit in their cards. Pure, so drag and drop can be tested without a browser.
type Card = { id: string; links: { id: string }[] }
/** The card with this id, or the card that holds the link with this id. */
const cardOf = <TCard extends Card>(cards: TCard[], id: string) =>
cards.find((c) => c.id === id || c.links.some((l) => l.id === id))
/** While dragging: a link that hovers over another card moves into that card. */
export function moveOver<TCard extends Card>(
cards: TCard[],
linkId: string,
overId: string
): TCard[] {
const from = cardOf(cards, linkId)
const to = cardOf(cards, overId)
const link = from?.links.find((l) => l.id === linkId)
if (!from || !to || !link || from === to) return cards
// over a link: take its place. Over the card itself: go to the end.
const overIndex = to.links.findIndex((l) => l.id === overId)
const at = overIndex < 0 ? to.links.length : overIndex
return cards.map((c) =>
c === from
? { ...c, links: c.links.filter((l) => l !== link) }
: c === to
? { ...c, links: [...c.links.slice(0, at), link, ...c.links.slice(at)] }
: c
)
}
/** On drop: the link takes the place of the link it was dropped on. */
export function drop<TCard extends Card>(
cards: TCard[],
linkId: string,
overId: string
): TCard[] {
const moved = moveOver(cards, linkId, overId)
if (moved !== cards) return moved // it changed cards, that put it in place
const card = cardOf(cards, linkId)
const from = card?.links.findIndex((l) => l.id === linkId) ?? -1
const to = card?.links.findIndex((l) => l.id === overId) ?? -1
if (!card || from < 0 || to < 0 || from === to) return cards
const links = [...card.links]
links.splice(to, 0, ...links.splice(from, 1))
return cards.map((c) => (c === card ? { ...c, links } : c))
}
/** What the server stores: per card, its link ids in order. */
export const order = (cards: Card[]) =>
cards.map((c) => ({ id: c.id, linkIds: c.links.map((l) => l.id) }))
+35
View File
@@ -0,0 +1,35 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { parseSuggestions, searchUrl } from "./search.ts"
test("searchUrl", () => {
assert.equal(
searchUrl(" a b&c ", "duckduckgo", null),
"https://duckduckgo.com/?q=a%20b%26c"
)
assert.equal(
searchUrl("cats", "searxng", "https://sx.lan/"),
"https://sx.lan/search?q=cats"
)
// SearXNG selected but not configured
assert.equal(
searchUrl("cats", "searxng", null),
"https://duckduckgo.com/?q=cats"
)
assert.equal(
searchUrl("cats", "google", null),
"https://www.google.com/search?q=cats"
)
// bangs go to DuckDuckGo
assert.equal(
searchUrl("!w cats", "google", null),
"https://duckduckgo.com/?q=!w%20cats"
)
})
test("parseSuggestions", () => {
assert.deepEqual(parseSuggestions(["ca", ["cat", "car"]]), ["cat", "car"])
assert.deepEqual(parseSuggestions(["cat", "car"]), ["cat", "car"])
assert.deepEqual(parseSuggestions({ error: 1 }), [])
assert.deepEqual(parseSuggestions(["q", [{ phrase: "x" }, "ok"]]), ["ok"])
})
+38
View File
@@ -0,0 +1,38 @@
export const ENGINES = ["duckduckgo", "searxng", "google"] as const
export type Engine = (typeof ENGINES)[number]
export const ENGINE_NAMES: Record<Engine, string> = {
duckduckgo: "DuckDuckGo",
searxng: "SearXNG",
google: "Google",
}
/** SearXNG without a configured instance falls back to DuckDuckGo. */
export function effectiveEngine(engine: Engine, searxngUrl: string | null) {
return engine === "searxng" && !searxngUrl ? "duckduckgo" : engine
}
export function searchUrl(
query: string,
engine: Engine,
searxngUrl: string | null
) {
const q = encodeURIComponent(query.trim())
switch (effectiveEngine(engine, searxngUrl)) {
case "searxng":
return `${searxngUrl!.replace(/\/+$/, "")}/search?q=${q}`
case "google":
// !bangs are a DuckDuckGo feature, Google would search them literally
if (!query.trim().startsWith("!"))
return `https://www.google.com/search?q=${q}`
}
return `https://duckduckgo.com/?q=${q}`
}
/** Both DuckDuckGo and SearXNG answer in OpenSearch form: [query, [suggestions]] */
export function parseSuggestions(body: unknown): string[] {
const list = Array.isArray(body) && Array.isArray(body[1]) ? body[1] : body
return Array.isArray(list)
? list.filter((s) => typeof s === "string").slice(0, 8)
: []
}
-1
View File
@@ -1 +0,0 @@
export { cn } from "cn"
+91 -18
View File
@@ -8,59 +8,132 @@
// You should NOT make any changes in this file as it will be overwritten. // You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from "./routes/__root" import { Route as rootRouteImport } from './routes/__root'
import { Route as IndexRouteImport } from "./routes/index" import { Route as IndexRouteImport } from './routes/index'
import { Route as LoginRouteImport } from './routes/login'
import { Route as SettingsRouteImport } from './routes/settings'
import { Route as ApiWallpaperRouteImport } from './routes/api/wallpaper'
import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$'
const IndexRoute = IndexRouteImport.update({ const IndexRoute = IndexRouteImport.update({
id: "/", id: '/',
path: "/", path: '/',
getParentRoute: () => rootRouteImport,
} as any)
const LoginRoute = LoginRouteImport.update({
id: '/login',
path: '/login',
getParentRoute: () => rootRouteImport,
} as any)
const SettingsRoute = SettingsRouteImport.update({
id: '/settings',
path: '/settings',
getParentRoute: () => rootRouteImport,
} as any)
const ApiWallpaperRoute = ApiWallpaperRouteImport.update({
id: '/api/wallpaper',
path: '/api/wallpaper',
getParentRoute: () => rootRouteImport,
} as any)
const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({
id: '/api/auth/$',
path: '/api/auth/$',
getParentRoute: () => rootRouteImport, getParentRoute: () => rootRouteImport,
} as any) } as any)
export interface FileRoutesByFullPath { export interface FileRoutesByFullPath {
"/": typeof IndexRoute '/': typeof IndexRoute
'/login': typeof LoginRoute
'/settings': typeof SettingsRoute
'/api/wallpaper': typeof ApiWallpaperRoute
'/api/auth/$': typeof ApiAuthSplatRoute
} }
export interface FileRoutesByTo { export interface FileRoutesByTo {
"/": typeof IndexRoute '/': typeof IndexRoute
'/login': typeof LoginRoute
'/settings': typeof SettingsRoute
'/api/wallpaper': typeof ApiWallpaperRoute
'/api/auth/$': typeof ApiAuthSplatRoute
} }
export interface FileRoutesById { export interface FileRoutesById {
__root__: typeof rootRouteImport __root__: typeof rootRouteImport
"/": typeof IndexRoute '/': typeof IndexRoute
'/login': typeof LoginRoute
'/settings': typeof SettingsRoute
'/api/wallpaper': typeof ApiWallpaperRoute
'/api/auth/$': typeof ApiAuthSplatRoute
} }
export interface FileRouteTypes { export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: "/" fullPaths: '/' | '/login' | '/settings' | '/api/wallpaper' | '/api/auth/$'
fileRoutesByTo: FileRoutesByTo fileRoutesByTo: FileRoutesByTo
to: "/" to: '/' | '/login' | '/settings' | '/api/wallpaper' | '/api/auth/$'
id: "__root__" | "/" id:
'__root__' | '/' | '/login' | '/settings' | '/api/wallpaper' | '/api/auth/$'
fileRoutesById: FileRoutesById fileRoutesById: FileRoutesById
} }
export interface RootRouteChildren { export interface RootRouteChildren {
IndexRoute: typeof IndexRoute IndexRoute: typeof IndexRoute
LoginRoute: typeof LoginRoute
SettingsRoute: typeof SettingsRoute
ApiWallpaperRoute: typeof ApiWallpaperRoute
ApiAuthSplatRoute: typeof ApiAuthSplatRoute
} }
declare module "@tanstack/react-router" { declare module '@tanstack/react-router' {
interface FileRoutesByPath { interface FileRoutesByPath {
"/": { '/': {
id: "/" id: '/'
path: "/" path: '/'
fullPath: "/" fullPath: '/'
preLoaderRoute: typeof IndexRouteImport preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport parentRoute: typeof rootRouteImport
} }
'/login': {
id: '/login'
path: '/login'
fullPath: '/login'
preLoaderRoute: typeof LoginRouteImport
parentRoute: typeof rootRouteImport
}
'/settings': {
id: '/settings'
path: '/settings'
fullPath: '/settings'
preLoaderRoute: typeof SettingsRouteImport
parentRoute: typeof rootRouteImport
}
'/api/wallpaper': {
id: '/api/wallpaper'
path: '/api/wallpaper'
fullPath: '/api/wallpaper'
preLoaderRoute: typeof ApiWallpaperRouteImport
parentRoute: typeof rootRouteImport
}
'/api/auth/$': {
id: '/api/auth/$'
path: '/api/auth/$'
fullPath: '/api/auth/$'
preLoaderRoute: typeof ApiAuthSplatRouteImport
parentRoute: typeof rootRouteImport
}
} }
} }
const rootRouteChildren: RootRouteChildren = { const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute, IndexRoute: IndexRoute,
LoginRoute: LoginRoute,
SettingsRoute: SettingsRoute,
ApiWallpaperRoute: ApiWallpaperRoute,
ApiAuthSplatRoute: ApiAuthSplatRoute,
} }
export const routeTree = rootRouteImport export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren) ._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>() ._addFileTypes<FileRouteTypes>()
import type { getRouter } from "./router.tsx" import type { getRouter } from './router.tsx'
import type { createStart } from "@tanstack/react-start" import type { createStart } from '@tanstack/react-start'
declare module "@tanstack/react-start" { declare module '@tanstack/react-start' {
interface Register { interface Register {
ssr: true ssr: true
router: Awaited<ReturnType<typeof getRouter>> router: Awaited<ReturnType<typeof getRouter>>
+3
View File
@@ -8,6 +8,9 @@ export function getRouter() {
scrollRestoration: true, scrollRestoration: true,
defaultPreload: "intent", defaultPreload: "intent",
defaultPreloadStaleTime: 0, defaultPreloadStaleTime: 0,
// no cached pages: after a change in settings the dashboard must not
// show the old title or wallpaper first
defaultGcTime: 0,
}) })
return router return router
+5 -4
View File
@@ -2,6 +2,7 @@ import { HeadContent, Scripts, createRootRoute } from "@tanstack/react-router"
import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools" import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools"
import { TanStackDevtools } from "@tanstack/react-devtools" import { TanStackDevtools } from "@tanstack/react-devtools"
import { ThemeProvider } from "@/vendor/collabry/components/ThemeProvider/ThemeProvider"
import appCss from "../styles.css?url" import appCss from "../styles.css?url"
export const Route = createRootRoute({ export const Route = createRootRoute({
@@ -15,7 +16,7 @@ export const Route = createRootRoute({
content: "width=device-width, initial-scale=1", content: "width=device-width, initial-scale=1",
}, },
{ {
title: "TanStack Start Starter", title: "Dahoam",
}, },
], ],
links: [ links: [
@@ -36,15 +37,15 @@ export const Route = createRootRoute({
function RootDocument({ children }: { children: React.ReactNode }) { function RootDocument({ children }: { children: React.ReactNode }) {
return ( return (
<html lang="en"> <html lang="en" className="scroll-smooth">
<head> <head>
<HeadContent /> <HeadContent />
</head> </head>
<body> <body>
{children} <ThemeProvider accent="#f5f5f5">{children}</ThemeProvider>
<TanStackDevtools <TanStackDevtools
config={{ config={{
position: "bottom-right", position: "bottom-left",
}} }}
plugins={[ plugins={[
{ {
+11
View File
@@ -0,0 +1,11 @@
import { createFileRoute } from "@tanstack/react-router"
import { auth } from "@/lib/auth"
export const Route = createFileRoute("/api/auth/$")({
server: {
handlers: {
GET: ({ request }) => auth.handler(request),
POST: ({ request }) => auth.handler(request),
},
},
})
+78
View File
@@ -0,0 +1,78 @@
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"
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
}
export const Route = createFileRoute("/api/wallpaper")({
server: {
handlers: {
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",
},
})
},
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 wallpaperUrl = `/api/wallpaper?v=${Date.now()}`
await db.transaction(async (tx) => {
await tx
.insert(wallpaper)
.values({ userId: id, mime, data })
.onConflictDoUpdate({
target: wallpaper.userId,
set: { mime, data },
})
await tx
.insert(settings)
.values({ userId: id, wallpaperUrl })
.onConflictDoUpdate({
target: settings.userId,
set: { wallpaperUrl },
})
})
return Response.json({ wallpaperUrl })
},
},
},
})
+147 -11
View File
@@ -1,19 +1,155 @@
import { createFileRoute } from "@tanstack/react-router" import { useState } from "react"
import { Button } from "@/components/ui/button" import {
Link,
createFileRoute,
redirect,
useRouter,
} from "@tanstack/react-router"
import {
Flower2,
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"
import { Clock } from "@/components/clock"
import { LinkDialog } from "@/components/link-dialog"
import type { LinkTarget } from "@/components/link-dialog"
import { SearchBar } from "@/components/search-bar"
import { Wallpaper } from "@/components/wallpaper"
import { authClient } from "@/lib/auth-client"
import { getDashboard } from "@/lib/dashboard.functions"
import { Button } from "@/vendor/collabry/components/Button/Button"
import { cn } from "@/vendor/collabry/lib/cn"
export const Route = createFileRoute("/")({ component: App }) export const Route = createFileRoute("/")({
loader: async () => {
const data = await getDashboard()
if (!data) throw redirect({ to: "/login" })
return data
},
component: Dashboard,
})
// Collabry ghost button, restyled to sit on the wallpaper
const onWallpaper =
"rounded-full text-white/80 hover:bg-white/10 hover:text-white"
function Dashboard() {
const data = Route.useLoaderData()
const router = useRouter()
const [link, setLink] = useState<LinkTarget | null>(null)
const [card, setCard] = useState<CardTarget | null>(null)
// the server makes sure there is always a card
const addLink = () => setLink({ cardId: data.cards[0].id })
function App() {
return ( return (
<div className="flex min-h-svh p-6"> <div className="relative isolate text-white">
<div className="flex max-w-md min-w-0 flex-col gap-4 text-sm leading-loose"> <Wallpaper src={data.wallpaperUrl} />
<div>
<h1 className="font-medium">Project ready!</h1> <main className="flex min-h-svh flex-col items-center px-4">
<p>You may now add components and start building.</p> <header className="flex h-28 w-full max-w-[1200px] items-center gap-4 px-2 sm:px-8">
<p>We&apos;ve already added the button component for you.</p> <Flower2 className="size-6" aria-hidden />
<Button className="mt-2">Button</Button> <h1 className="m-0 text-md font-semibold">{data.title}</h1>
<span className="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")}
onClick={addLink}
>
<Plus className="size-5" />
</Button>
<Button asChild variant="ghost" iconOnly className={onWallpaper}>
<Link to="/settings" aria-label="Settings">
<Settings2 className="size-5" />
</Link>
</Button>
</header>
<div className="mt-[11vh]">
<Clock />
</div> </div>
<div className="mt-10 flex w-full justify-center sm:mt-14">
<SearchBar
links={data.cards.flatMap((c) => c.links)}
engine={data.searchEngine}
searxngUrl={data.searxngUrl}
commands={[
{
label: "Add link",
icon: <Plus className="size-4" />,
run: addLink,
},
{
label: "Add card",
icon: <LayoutGrid className="size-4" />,
run: () => setCard("new"),
},
{
label: "Settings",
icon: <Settings2 className="size-4" />,
run: () => router.navigate({ to: "/settings" }),
},
{
label: "Sign out",
icon: <LogOut className="size-4" />,
run: async () => {
await authClient.signOut()
await router.navigate({ to: "/login" })
},
},
]}
/>
</div> </div>
<div className="mt-[9vh] flex w-full flex-col items-center">
<CardGrid
cards={data.cards}
onAddCard={() => setCard("new")}
onAddLink={(c) => setLink({ cardId: c.id })}
onEditLink={setLink}
onEditCard={setCard}
/>
</div>
<footer className="mt-auto flex w-full items-center justify-end gap-3 pt-10 pb-5 text-sm text-white/60 sm:px-2">
{!data.wallpaperUrl && (
<span>
Photo by{" "}
<a
className="text-white/90 underline underline-offset-4"
href="https://unsplash.com/photos/VB-w_3dnyvI"
rel="noreferrer"
>
Andrew Coelho
</a>{" "}
on Unsplash
</span>
)}
<Button asChild variant="ghost" iconOnly className={onWallpaper}>
<Link to="/settings" hash="wallpaper" aria-label="Change wallpaper">
<Pencil className="size-4" />
</Link>
</Button>
</footer>
</main>
<LinkDialog
target={link}
cards={data.cards}
onClose={() => setLink(null)}
/>
<CardDialog card={card} onClose={() => setCard(null)} />
</div> </div>
) )
} }
+166
View File
@@ -0,0 +1,166 @@
import { useState } from "react"
import { createFileRoute, redirect, useRouter } from "@tanstack/react-router"
import { KeyRound } from "lucide-react"
import { glassFrame } from "@/components/glass"
import { Wallpaper } from "@/components/wallpaper"
import { authClient } from "@/lib/auth-client"
import { getAuthInfo } from "@/lib/dashboard.functions"
import { Button } from "@/vendor/collabry/components/Button/Button"
import { Card, CardFrame } from "@/vendor/collabry/components/Card/Card"
import {
Field,
FieldError,
FieldLabel,
Input,
} from "@/vendor/collabry/components/Field/Field"
import { cn } from "@/vendor/collabry/lib/cn"
export const Route = createFileRoute("/login")({
loader: async () => {
const info = await getAuthInfo()
if (info.signedIn) throw redirect({ to: "/" })
return info
},
component: Login,
})
function Login() {
const { ssoName, signUpEnabled } = Route.useLoaderData()
const router = useRouter()
const [signUp, setSignUp] = useState(false)
const [busy, setBusy] = useState(false)
const [error, setError] = useState("")
// Better Auth returns { error } instead of throwing
const run = async (
action: () => Promise<{ error: { message?: string } | null }>
) => {
setBusy(true)
setError("")
// a dropped connection throws
const { error: failure } = await action().catch(() => ({
error: { message: "" },
}))
if (failure) {
setError(failure.message || "Something went wrong. Try again.")
setBusy(false)
} else {
await router.navigate({ to: "/" })
}
}
return (
<main className="relative isolate grid min-h-svh place-items-center p-4">
<Wallpaper />
{/* Collabry's double frame, as glass */}
<CardFrame className={cn(glassFrame, "w-full max-w-sm")}>
<Card className="gap-0 p-7">
<h1 className="m-0 font-serif text-4xl font-normal text-white">
{signUp ? "Create account" : "Welcome back"}
</h1>
<p className="mt-1.5 mb-0 text-fg-muted">
{signUp ? "Set up your own Dahoam." : "Sign in to Dahoam."}
</p>
<form
className="mt-6 flex flex-col gap-4"
onSubmit={(e) => {
e.preventDefault()
const form = new FormData(e.currentTarget)
const email = String(form.get("email"))
const password = String(form.get("password"))
void run(() =>
signUp
? authClient.signUp.email({
name: String(form.get("name")),
email,
password,
})
: authClient.signIn.email({ email, password })
)
}}
>
{signUp && (
<Field>
<FieldLabel>Name</FieldLabel>
<Input size="lg" name="name" autoComplete="name" required />
</Field>
)}
<Field>
<FieldLabel>Email</FieldLabel>
<Input
size="lg"
name="email"
type="email"
autoComplete="email"
required
/>
</Field>
<Field>
<FieldLabel>Password</FieldLabel>
<Input
size="lg"
name="password"
type="password"
autoComplete={signUp ? "new-password" : "current-password"}
minLength={8}
required
/>
</Field>
{error && <FieldError role="alert">{error}</FieldError>}
<Button
type="submit"
variant="primary"
size="xl"
fullWidth
disabled={busy}
>
{signUp ? "Create account" : "Sign in"}
</Button>
</form>
{ssoName && (
<>
<div className="my-5 flex items-center gap-3 text-xs text-fg-subtle">
<span className="h-px flex-1 bg-white/15" />
or
<span className="h-px flex-1 bg-white/15" />
</div>
<Button
size="xl"
fullWidth
disabled={busy}
onClick={() =>
run(() =>
authClient.signIn.social({
provider: "sso",
callbackURL: "/",
})
)
}
>
<KeyRound size={16} /> Continue with {ssoName}
</Button>
</>
)}
{signUpEnabled && (
<p className="mt-6 mb-0 text-center text-fg-muted">
{signUp ? "Already have an account?" : "No account yet?"}{" "}
<button
type="button"
className="font-bold text-white underline-offset-4 hover:underline"
onClick={() => {
setSignUp(!signUp)
setError("")
}}
>
{signUp ? "Sign in" : "Sign up"}
</button>
</p>
)}
</Card>
</CardFrame>
</main>
)
}
+372
View File
@@ -0,0 +1,372 @@
import { useRef, useState } from "react"
import {
Link,
createFileRoute,
redirect,
useLocation,
useRouter,
} from "@tanstack/react-router"
import {
ArrowLeft,
Check,
CircleUser,
Flower2,
Image,
LogOut,
Search,
SlidersHorizontal,
Upload,
} from "lucide-react"
import { DEFAULT_WALLPAPER } from "@/components/wallpaper"
import { authClient } from "@/lib/auth-client"
import { getDashboard, 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"
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")({
loader: async () => {
const data = await getDashboard()
if (!data) throw redirect({ to: "/login" })
return data
},
head: () => ({ meta: [{ title: "Settings" }] }),
component: Settings,
})
const SECTIONS = [
{ id: "general", label: "General", icon: SlidersHorizontal },
{ 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"
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("")
// 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
searchEngine?: Engine
wallpaperUrl?: string | null
}) => run(() => saveSettings({ data: patch }))
const upload = (image: File) =>
run(async () => {
const res = await fetch("/api/wallpaper", {
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">
<Flower2 className="size-5 text-fg" aria-hidden />
<span className="min-w-0 truncate font-bold">{data.title}</span>
<Button asChild size="sm" className="ml-auto">
<Link to="/">
<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}
// 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 dashboard is called.
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsRow>
<SettingsRowText>
<SettingsRowLabel htmlFor="settings-title">
Dashboard name
</SettingsRowLabel>
<SettingsRowDescription>
Shown at the top left of the dashboard.
</SettingsRowDescription>
</SettingsRowText>
<SettingsRowControl>
<Input
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
}}
/>
</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 your dashboard. Upload one (JPEG, PNG,
WebP or AVIF, up to 10 MB) or use any image on the web.
</SettingsSectionDescription>
</SettingsSectionHeader>
<SettingsRow stacked>
<div className="flex flex-wrap items-start gap-x-6 gap-y-4">
<img
src={data.wallpaperUrl ?? DEFAULT_WALLPAPER}
alt="Current wallpaper"
className="aspect-video w-60 flex-none rounded-xl border border-line object-cover"
/>
<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 save({ 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={() => save({ wallpaperUrl: null })}
>
Use default
</Button>
</div>
</div>
</div>
</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>
)
}
+27 -122
View File
@@ -1,133 +1,38 @@
@import "tailwindcss"; /* Tailwind, the Collabry tokens and its theme */
@import "tw-animate-css"; @import "./vendor/collabry/styles/index.css";
@import "shadcn/tailwind.css";
@import "@fontsource-variable/inter"; @import "@fontsource-variable/inter";
@import "@fontsource/dm-serif-display";
@custom-variant dark (&:is(.dark *));
@theme inline { @theme inline {
--font-heading: var(--font-sans); --font-sans: "Inter Variable", system-ui, sans-serif;
--font-sans: 'Inter Variable', sans-serif; --font-serif: "DM Serif Display", ui-serif, Georgia, serif;
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--color-foreground: var(--foreground);
--color-background: var(--background);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
} }
:root { /* The accent is near white here (set on ThemeProvider), so text on it is dark */
--background: oklch(1 0 0); :root,
--foreground: oklch(0.145 0 0); [data-cl-theme] {
--card: oklch(1 0 0); --cl-white: #111111;
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
} }
@layer base { @layer base {
* {
@apply border-border outline-ring/50;
}
body { body {
@apply bg-background text-foreground; margin: 0;
} background: black;
button:not(:disabled), [role="button"]:not(:disabled) {
cursor: pointer;
}
html {
@apply font-sans;
} }
} }
/* Halftone dots plus a fade to black, as on the reference start page */
@utility wallpaper-dither {
background-image:
linear-gradient(
to bottom,
rgb(0 0 0 / 0.45),
rgb(0 0 0 / 0.25) 30%,
rgb(0 0 0 / 0.4) 65%,
rgb(0 0 0 / 0.95) 100%
),
radial-gradient(rgb(0 0 0 / 0.45) 1px, transparent 1.5px);
background-size:
auto,
4px 4px;
}
+19
View File
@@ -0,0 +1,19 @@
# Vendored: Collabry components
Do not edit the files in this directory. They are copies of upstream `src/`, so a diff
against upstream stays empty. App components go in `src/components/`.
- Upstream: https://git.nhaiden.io/niklas/collabry-components.git
- Commit: `f94d10e8e9137724350cfd62389d9b84018b4f40`
- Copied: only the files listed in `scripts/sync-collabry.sh`
- Local patches: none
Update or add a component: edit the list in `scripts/sync-collabry.sh`, then run
`scripts/sync-collabry.sh [ref]` and `pnpm typecheck && pnpm build`.
Upstream files import `@/lib/…` and `@/components/ui/…`. `tsconfig.json` maps `@/*` to
`src/*` first and to this directory second, so they resolve here without a rewrite.
Do not create `src/lib/cn.ts`, `src/lib/portal.ts` or `src/components/ui/`: they would
take the place of the vendored files.
The look is changed from outside: tokens in `src/styles.css`, classes in `src/components/`.
+87
View File
@@ -0,0 +1,87 @@
import type { ComponentProps } from "react"
import { cn } from "../../lib/cn"
import { Button as UiButton, buttonVariants } from "../ui/button"
import { Spinner, SuccessCheck } from "../Spinner/Spinner"
export { buttonVariants }
export type ButtonVariant =
"primary" | "secondary" | "ghost" | "danger" | "danger-outline"
export type ButtonSize = "xs" | "sm" | "md" | "lg" | "xl"
export type ButtonState = "idle" | "loading" | "success"
const spinnerSize: Record<ButtonSize, number> = {
xs: 12,
sm: 14,
md: 14,
lg: 16,
xl: 18,
}
export interface ButtonProps extends ComponentProps<typeof UiButton> {
/** Async feedback: the label hides behind a spinner, then a checkmark. Ignored with `asChild`. */
state?: ButtonState
}
/**
* Put icons in `children` next to the label. Use `asChild` to render a link as a button:
* `<Button asChild><a href="…">Alle Aufgaben</a></Button>`.
*/
export function Button({
size = "md",
state = "idle",
disabled,
type = "button",
asChild,
className,
children,
...props
}: ButtonProps) {
if (asChild) {
return (
<UiButton asChild size={size} className={className} {...props}>
{children}
</UiButton>
)
}
const busy = state !== "idle"
const spinner = spinnerSize[size ?? "md"]
return (
<UiButton
type={type}
size={size}
disabled={disabled || busy}
aria-busy={state === "loading" || undefined}
className={cn(
disabled && !busy && "opacity-50 hover:brightness-100",
className
)}
{...props}
>
<span
className={cn(
"inline-flex items-center justify-center gap-[inherit]",
busy && "invisible"
)}
>
{children}
</span>
{busy && (
<span className="pointer-events-none absolute inset-0 flex items-center justify-center">
{state === "loading" ? (
<Spinner size={spinner} />
) : (
<SuccessCheck size={spinner} />
)}
</span>
)}
<span className="sr-only" aria-live="polite">
{state === "loading"
? "Wird ausgeführt …"
: state === "success"
? "Erledigt"
: ""}
</span>
</UiButton>
)
}
+49
View File
@@ -0,0 +1,49 @@
import type { ComponentProps } from "react"
import { cn } from "../../lib/cn"
import { Card as UiCard } from "../ui/card"
export {
CardAction,
CardDescription,
CardFooter,
CardHeader,
CardHeading,
CardTitle,
} from "../ui/card"
/**
* The dark 5px rim of the design's signature double frame. Wrap a `Card` in it:
* `<CardFrame><Card>…</Card></CardFrame>`. Place and size the pair through the frame.
*/
export function CardFrame({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="card-frame"
className={cn(
"flex min-w-0 rounded-[18px] border border-line-frame bg-frame p-[5px]",
className
)}
{...props}
/>
)
}
export interface CardProps extends ComponentProps<typeof UiCard> {
/** Inner padding. `none` lets rows run edge to edge (settings, task list). */
padding?: "none" | "sm" | "md"
}
/** The raised surface. Use `asChild` for `section`, `article` or `form`. */
export function Card({ padding = "md", className, ...props }: CardProps) {
return (
<UiCard
data-padding={padding}
className={cn(
padding === "md" && "gap-3.5 px-[22px] py-5",
padding === "sm" && "gap-4 px-[18px] pt-[18px] pb-4",
className
)}
{...props}
/>
)
}
+321
View File
@@ -0,0 +1,321 @@
import {
createContext,
useCallback,
useContext,
useId,
useLayoutEffect,
useMemo,
useState,
type ComponentProps,
} from "react"
import { AlertCircle, Eye, EyeOff } from "lucide-react"
import { cn } from "../../lib/cn"
import { Input as UiInput } from "../ui/input"
import { Label } from "../ui/label"
import { NativeSelect, NativeSelectOption } from "../ui/native-select"
import { Textarea as UiTextarea } from "../ui/textarea"
/* ---------------------------------------------------------------- Field */
interface FieldContextValue {
id: string
invalid: boolean
describedBy?: string
register: (messageId: string, isError: boolean) => () => void
}
const FieldContext = createContext<FieldContextValue | null>(null)
/**
* Props a control needs to join the surrounding `Field`: `id`, `aria-describedby`
* and `aria-invalid`. Explicit props win. Use it to make your own controls field-aware.
*/
export function useFieldControl<
P extends {
id?: string
"aria-describedby"?: string
"aria-invalid"?: unknown
},
>(props: P): P {
const field = useContext(FieldContext)
if (!field) return props
return {
...props,
id: props.id ?? field.id,
"aria-describedby": props["aria-describedby"] ?? field.describedBy,
"aria-invalid": props["aria-invalid"] ?? (field.invalid || undefined),
}
}
export interface FieldProps extends ComponentProps<"div"> {
/** Marks the control invalid. Rendering a `FieldError` does this too. */
invalid?: boolean
/** `horizontal` puts control and label side by side (checkboxes). */
orientation?: "vertical" | "horizontal"
}
/**
* Groups a label, one control and its messages, and wires ids and ARIA between them.
*
* <Field>
* <FieldLabel>E-Mail</FieldLabel>
* <Input />
* {error && <FieldError>{error}</FieldError>}
* </Field>
*/
export function Field({
invalid,
orientation = "vertical",
className,
...props
}: FieldProps) {
const id = useId()
const [messages, setMessages] = useState<{ id: string; error: boolean }[]>([])
const register = useCallback((messageId: string, error: boolean) => {
setMessages((m) => [...m, { id: messageId, error }])
return () => setMessages((m) => m.filter((x) => x.id !== messageId))
}, [])
const value = useMemo<FieldContextValue>(
() => ({
id,
invalid: invalid ?? messages.some((m) => m.error),
describedBy: messages.map((m) => m.id).join(" ") || undefined,
register,
}),
[id, invalid, messages, register]
)
return (
<FieldContext value={value}>
<div
role="group"
data-slot="field"
data-orientation={orientation}
data-invalid={value.invalid || undefined}
className={cn(
"group/field flex min-w-0 gap-1.5",
orientation === "vertical"
? "flex-col"
: "flex-row items-center gap-2.5",
className
)}
{...props}
/>
</FieldContext>
)
}
/** Row above the control: the label and something aligned right, e.g. "Passwort vergessen?". */
export function FieldHeader({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="field-header"
className={cn(
"flex items-baseline justify-between gap-3 text-sm",
className
)}
{...props}
/>
)
}
export function FieldLabel({
className,
...props
}: ComponentProps<typeof Label>) {
const field = useContext(FieldContext)
return (
<Label
htmlFor={field?.id}
className={cn(
"text-sm font-bold group-data-[orientation=horizontal]/field:cursor-pointer group-data-[orientation=horizontal]/field:text-base group-data-[orientation=horizontal]/field:font-normal group-data-[orientation=horizontal]/field:text-fg-4",
className
)}
{...props}
/>
)
}
/** Small, muted text inside a label, e.g. "(optional)". */
export function FieldNote({ className, ...props }: ComponentProps<"span">) {
return (
<span
data-slot="field-note"
className={cn("font-normal text-fg-subtle", className)}
{...props}
/>
)
}
function useMessageId(id: string | undefined, error: boolean) {
const field = useContext(FieldContext)
const ownId = useId()
const messageId =
id ?? `${field?.id ?? ownId}-${error ? "error" : "description"}`
const register = field?.register
useLayoutEffect(
() => register?.(messageId, error),
[register, messageId, error]
)
return messageId
}
/** Hint under the control; linked to it with `aria-describedby`. */
export function FieldDescription({
id,
className,
...props
}: ComponentProps<"div">) {
return (
<div
id={useMessageId(id, false)}
data-slot="field-description"
className={cn("text-xs text-fg-subtle", className)}
{...props}
/>
)
}
/** Error under the control; marks the field invalid while rendered. */
export function FieldError({
id,
className,
children,
...props
}: ComponentProps<"div">) {
return (
<div
id={useMessageId(id, true)}
data-slot="field-error"
className={cn(
"flex items-center gap-1.5 text-xs text-danger-fg",
className
)}
{...props}
>
<AlertCircle
size={14}
strokeWidth={1.75}
aria-hidden="true"
className="flex-none"
/>
{children}
</div>
)
}
/* ---------------------------------------------------------------- Controls */
export type FieldSize = "md" | "lg"
const heights: Record<FieldSize, string> = { md: "h-[38px]", lg: "h-[42px]" }
export interface InputProps extends Omit<ComponentProps<"input">, "size"> {
/** 38px (filters, dialogs) or 42px (auth forms). */
size?: FieldSize
}
export function Input({ size = "md", className, ...props }: InputProps) {
return (
<UiInput
className={cn(heights[size], className)}
{...useFieldControl(props)}
/>
)
}
/** Wraps an `Input` with addons inside the field: icons on the left, buttons on the right. */
export function InputGroup({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="input-group"
className={cn(
"relative flex items-center has-[>[data-align=end]]:[&>input]:pr-12 has-[>[data-align=start]]:[&>input]:pl-[34px]",
className
)}
{...props}
/>
)
}
export interface InputGroupAddonProps extends ComponentProps<"span"> {
/** `start`: decorative icon on the left. `end`: interactive element on the right. */
align?: "start" | "end"
}
export function InputGroupAddon({
align = "start",
className,
...props
}: InputGroupAddonProps) {
return (
<span
data-slot="input-group-addon"
data-align={align}
className={cn(
"absolute flex",
align === "start"
? "pointer-events-none left-[11px] text-fg-subtle"
: "right-[5px]",
className
)}
{...props}
/>
)
}
/** Small square button for an `InputGroupAddon align="end"`. */
export function InputGroupButton({
className,
type = "button",
...props
}: ComponentProps<"button">) {
return (
<button
type={type}
data-slot="input-group-button"
className={cn(
"flex h-8 w-8 items-center justify-center rounded-[7px] text-fg-subtle hover:bg-hover hover:text-fg focus-visible:shadow-focus focus-visible:outline-none",
className
)}
{...props}
/>
)
}
/** Password input with a show/hide button. `className` goes to the wrapping `InputGroup`. */
export function PasswordInput({
className,
...props
}: Omit<InputProps, "type">) {
const [visible, setVisible] = useState(false)
const label = visible ? "Passwort verbergen" : "Passwort anzeigen"
return (
<InputGroup className={className}>
<Input type={visible ? "text" : "password"} {...props} />
<InputGroupAddon align="end">
<InputGroupButton
onClick={() => setVisible((v) => !v)}
aria-pressed={visible}
aria-label={label}
title={label}
>
{visible ? (
<EyeOff size={18} strokeWidth={1.75} />
) : (
<Eye size={18} strokeWidth={1.75} />
)}
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
)
}
export function Textarea({ rows = 3, ...props }: ComponentProps<"textarea">) {
return <UiTextarea rows={rows} {...useFieldControl(props)} />
}
/** Native select with the design's chevron. Children are `SelectOption`s; `className` sizes the wrapper. */
export function Select(props: ComponentProps<typeof NativeSelect>) {
return <NativeSelect {...useFieldControl(props)} />
}
export const SelectOption = NativeSelectOption
+156
View File
@@ -0,0 +1,156 @@
import type { ComponentProps } from "react"
import { cn } from "../../lib/cn"
/** Page title block: `PageHeading` on the left, `PageActions` on the right. */
export function PageHeader({ className, ...props }: ComponentProps<"header">) {
return (
<header
data-slot="page-header"
className={cn(
"flex flex-wrap items-end justify-between gap-x-6 gap-y-3",
className
)}
{...props}
/>
)
}
/** Eyebrow, title and description, stacked. */
export function PageHeading(props: ComponentProps<"div">) {
return <div data-slot="page-heading" {...props} />
}
/** Small label above the title, e.g. "Einstellungen". */
export function PageEyebrow({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="page-eyebrow"
className={cn("mb-1 text-sm font-bold text-fg-subtle", className)}
{...props}
/>
)
}
/** 28px black page heading. */
export function PageTitle({ className, ...props }: ComponentProps<"h1">) {
return (
<h1
data-slot="page-title"
className={cn(
"m-0 text-display font-black tracking-[-0.01em]",
className
)}
{...props}
/>
)
}
export function PageDescription({ className, ...props }: ComponentProps<"p">) {
return (
<p
data-slot="page-description"
className={cn("mt-1.5 mb-0 text-fg-muted", className)}
{...props}
/>
)
}
export function PageActions({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="page-actions"
className={cn("flex items-center gap-2.5", className)}
{...props}
/>
)
}
/** Centered placeholder for empty lists and searches. */
export function Empty({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="empty"
className={cn(
"flex flex-col items-center gap-2 px-4 py-12 text-center text-fg-subtle",
className
)}
{...props}
/>
)
}
/** Icon above the title. */
export function EmptyMedia({ className, ...props }: ComponentProps<"span">) {
return (
<span
data-slot="empty-media"
className={cn("flex text-fg-faint", className)}
{...props}
/>
)
}
export function EmptyTitle({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="empty-title"
className={cn("font-bold text-fg", className)}
{...props}
/>
)
}
export function EmptyDescription({
className,
...props
}: ComponentProps<"div">) {
return (
<div
data-slot="empty-description"
className={cn("text-sm", className)}
{...props}
/>
)
}
export function EmptyAction({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="empty-action"
className={cn("mt-1.5", className)}
{...props}
/>
)
}
/** Small section label inside lists ("Heute", "Früher"). */
export function SectionLabel({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="section-label"
className={cn(
"px-2.5 pt-2.5 pb-1.5 text-xs font-bold text-fg-subtle",
className
)}
{...props}
/>
)
}
/** "·" between items of a meta line. */
export function MetaSeparator({
className,
children = "·",
...props
}: ComponentProps<"span">) {
return (
<span
data-slot="meta-separator"
aria-hidden="true"
className={cn("text-fg-dim", className)}
{...props}
>
{children}
</span>
)
}
@@ -0,0 +1,59 @@
import type { ComponentProps } from "react"
import { cn } from "../../lib/cn"
import { ToggleGroup, ToggleGroupItem } from "../ui/toggle-group"
export interface SegmentedControlProps extends Omit<
ComponentProps<"div">,
"defaultValue" | "dir"
> {
value?: string
defaultValue?: string
onValueChange?: (value: string) => void
/** 30px for filters, 32px in settings rows and forms. */
size?: "sm" | "md"
disabled?: boolean
}
/**
* Pill group of mutually exclusive segments for filters, views and options; arrow keys
* move between them. Give it an `aria-label`. Stretch segments with `className="*:flex-1"`.
*/
export function SegmentedControl({
size = "sm",
onValueChange,
className,
...props
}: SegmentedControlProps) {
return (
<ToggleGroup
type="single"
size={size}
// Radix lets you deselect the active item; a segmented control always keeps one.
onValueChange={(v: string) => v && onValueChange?.(v)}
className={cn(
"gap-0.5 rounded-[10px] border border-line-subtle bg-inset p-[3px]",
className
)}
{...props}
/>
)
}
export const SegmentedControlItem = ToggleGroupItem
/** Count after a segment label, e.g. "Offen 6". */
export function SegmentedControlCount({
className,
...props
}: ComponentProps<"span">) {
return (
<span
data-slot="segmented-control-count"
className={cn(
"text-xs font-normal text-fg-subtle tabular-nums",
className
)}
{...props}
/>
)
}
+467
View File
@@ -0,0 +1,467 @@
import { createContext, useContext, useId, type ComponentProps } from "react"
import { Check } from "lucide-react"
import { Slot } from "radix-ui"
import { cn } from "../../lib/cn"
import { Card, CardFrame } from "../Card/Card"
import { Label } from "../ui/label"
import { RadioGroup, RadioGroupItem } from "../ui/radio-group"
import { Spinner } from "../Spinner/Spinner"
/* ---------------------------------------------------------------- Nav */
/** Left-hand navigation between settings pages: `SettingsNavLabel`s and `SettingsNavItem`s. */
export function SettingsNav({ className, ...props }: ComponentProps<"nav">) {
return (
<nav
aria-label="Einstellungen"
data-slot="settings-nav"
className={cn(
"flex max-w-[240px] flex-[1_1_200px] flex-col gap-0.5",
className
)}
{...props}
/>
)
}
/** Group title, e.g. "Persönlich". */
export function SettingsNavLabel({
className,
...props
}: ComponentProps<"div">) {
return (
<div
data-slot="settings-nav-label"
className={cn(
"px-3 pb-2 text-xs font-bold text-fg-subtle not-first:pt-[18px]",
className
)}
{...props}
/>
)
}
export interface SettingsNavItemProps extends ComponentProps<"a"> {
active?: boolean
asChild?: boolean
}
/** Icon and label; the active one is framed with an accent icon. */
export function SettingsNavItem({
active,
asChild,
className,
...props
}: SettingsNavItemProps) {
const Comp = asChild ? Slot.Root : "a"
return (
<Comp
aria-current={active ? "page" : undefined}
data-slot="settings-nav-item"
className={cn(
"flex h-[38px] items-center gap-2.5 rounded-lg px-3 font-bold text-fg-muted hover:text-fg [&>svg]:text-fg-subtle",
"aria-[current=page]:bg-side-active aria-[current=page]:text-fg aria-[current=page]:shadow-[inset_0_0_0_1px_var(--cl-side-active-line)] aria-[current=page]:[&>svg]:text-accent-fg",
className
)}
{...props}
/>
)
}
/* ---------------------------------------------------------------- Section */
const SectionContext = createContext<string | undefined>(undefined)
/**
* A settings card: header, then `SettingsRow`s separated by hairlines, then an optional footer.
* Labelled by its `SettingsSectionTitle`. `className` goes to the frame.
*/
export function SettingsSection({
className,
...props
}: ComponentProps<"section">) {
const titleId = useId()
return (
<SectionContext value={titleId}>
<CardFrame className={className}>
<Card asChild padding="none">
<section
aria-labelledby={titleId}
data-slot="settings-section"
{...props}
/>
</Card>
</CardFrame>
</SectionContext>
)
}
export function SettingsSectionHeader({
className,
...props
}: ComponentProps<"div">) {
return (
<div
data-slot="settings-section-header"
className={cn("px-[22px] pt-[18px] pb-4", className)}
{...props}
/>
)
}
export function SettingsSectionTitle({
className,
...props
}: ComponentProps<"h2">) {
return (
<h2
id={useContext(SectionContext)}
data-slot="settings-section-title"
className={cn("m-0 text-md font-bold", className)}
{...props}
/>
)
}
export function SettingsSectionDescription({
className,
...props
}: ComponentProps<"p">) {
return (
<p
data-slot="settings-section-description"
className={cn(
"mt-1 mb-0 text-sm leading-normal text-fg-subtle",
className
)}
{...props}
/>
)
}
/** Right-aligned actions, e.g. Verwerfen / Speichern. */
export function SettingsSectionFooter({
className,
...props
}: ComponentProps<"div">) {
return (
<div
data-slot="settings-section-footer"
className={cn(
"flex flex-wrap items-center justify-end gap-2.5 border-t border-line-subtle px-[22px] py-3.5",
className
)}
{...props}
/>
)
}
export interface SettingsRowProps extends ComponentProps<"div"> {
/** Put the control on its own line under the text. */
stacked?: boolean
}
/** `SettingsRowText` on the left, `SettingsRowControl` on the right; wraps on narrow screens. Also fits free content. */
export function SettingsRow({
stacked,
className,
...props
}: SettingsRowProps) {
return (
<div
data-slot="settings-row"
data-stacked={stacked || undefined}
className={cn(
"group/row border-t border-line-subtle px-[22px] py-4",
!stacked &&
"flex flex-wrap items-center justify-between gap-x-6 gap-y-3",
className
)}
{...props}
/>
)
}
export function SettingsRowText({
className,
...props
}: ComponentProps<"div">) {
return (
<div
data-slot="settings-row-text"
className={cn(
"min-w-0 flex-[1_1_260px] group-data-stacked/row:flex-none",
className
)}
{...props}
/>
)
}
/** A `<label>`; set `htmlFor` to the control's id. */
export function SettingsRowLabel({
className,
...props
}: ComponentProps<typeof Label>) {
return (
<Label
data-slot="settings-row-label"
className={cn("block leading-tight font-bold", className)}
{...props}
/>
)
}
export function SettingsRowDescription({
className,
...props
}: ComponentProps<"div">) {
return (
<div
data-slot="settings-row-description"
className={cn(
"mt-[3px] text-sm leading-normal text-fg-subtle",
className
)}
{...props}
/>
)
}
export function SettingsRowControl({
className,
...props
}: ComponentProps<"div">) {
return (
<div
data-slot="settings-row-control"
className={cn(
"max-w-full flex-none group-data-stacked/row:mt-3.5",
className
)}
{...props}
/>
)
}
/* ---------------------------------------------------------------- Pickers */
/** Selectable card; the checked one gets an accent ring. */
const radioCard =
"group flex flex-col rounded-xl border border-line bg-inset text-fg hover:bg-hover data-[state=checked]:shadow-[0_0_0_2px_var(--cl-accent)] data-[state=checked]:focus-visible:shadow-[0_0_0_2px_var(--cl-accent),0_0_0_5px_var(--cl-accent-ring)]"
export type ThemeChoice = "light" | "dark" | "system"
/** Radio cards for the theme: `ThemeOption`s. Arrow keys move the choice. */
export function ThemePicker({
className,
...props
}: ComponentProps<typeof RadioGroup>) {
return (
<RadioGroup
aria-label="Design"
data-slot="theme-picker"
className={cn(
"grid-cols-[repeat(auto-fit,minmax(140px,1fr))]",
className
)}
{...props}
/>
)
}
/** One card: a `ThemePreview` and a `ThemeOptionLabel`. */
export function ThemeOption({
className,
...props
}: ComponentProps<typeof RadioGroupItem>) {
return (
<RadioGroupItem
data-slot="theme-option"
className={cn(radioCard, "gap-2.5 px-2 pt-2 pb-2.5 text-left", className)}
{...props}
/>
)
}
function MiniWindow({
variant,
className,
}: {
variant: "light" | "dark"
className?: string
}) {
const c =
variant === "light"
? {
bg: "#F4F4F5",
side: "#FFFFFF",
card: "#FFFFFF",
line: "#DEDEE3",
bar: "#E4E4E7",
}
: {
bg: "#050505",
side: "#0E0E0E",
card: "#141414",
line: "#2E2E2E",
bar: "#262626",
}
return (
<span
aria-hidden="true"
className={cn("box-border flex h-[74px] w-full gap-1.5 p-2", className)}
style={{ background: c.bg }}
>
<span className="w-[26%] rounded-[5px]" style={{ background: c.side }} />
<span className="flex flex-auto flex-col gap-[5px]">
<span
className="h-[26px] rounded-[5px]"
style={{ background: c.card, boxShadow: `inset 0 0 0 1px ${c.line}` }}
/>
<span className="h-2 w-[70%] rounded" style={{ background: c.bar }} />
<span className="h-2 w-[45%] rounded" style={{ background: c.bar }} />
</span>
</span>
)
}
/** Miniature app window in the given theme; `system` shows half light, half dark. */
export function ThemePreview({
theme,
className,
}: {
theme: ThemeChoice
className?: string
}) {
if (theme !== "system")
return (
<MiniWindow variant={theme} className={cn("rounded-[9px]", className)} />
)
return (
<span
className={cn(
"flex h-[74px] w-full overflow-hidden rounded-[9px]",
className
)}
>
<span className="flex flex-1 basis-0 overflow-hidden">
<MiniWindow variant="light" className="w-[200%] flex-none" />
</span>
<span className="flex flex-1 basis-0 justify-end overflow-hidden">
<MiniWindow variant="dark" className="w-[200%] flex-none" />
</span>
</span>
)
}
/** Name of the option, with a radio dot on the right. */
export function ThemeOptionLabel({
className,
children,
...props
}: ComponentProps<"span">) {
return (
<span
data-slot="theme-option-label"
className={cn(
"flex items-center justify-between gap-2 px-1 text-sm font-bold",
className
)}
{...props}
>
{children}
<span className="box-border h-4 w-4 flex-none rounded-full border-[1.5px] border-line-control group-data-[state=checked]:border-accent group-data-[state=checked]:bg-accent group-data-[state=checked]:shadow-[inset_0_0_0_3px_var(--cl-inset)]" />
</span>
)
}
/** Accent color swatches ("Farbschema"): `ColorSchemeOption`s. */
export function ColorSchemePicker({
className,
...props
}: ComponentProps<typeof RadioGroup>) {
return (
<RadioGroup
data-slot="color-scheme-picker"
className={cn(
"grid-cols-[repeat(auto-fill,minmax(88px,1fr))] gap-2.5",
className
)}
{...props}
/>
)
}
export interface ColorSchemeOptionProps extends ComponentProps<
typeof RadioGroupItem
> {
color: string
}
/** Round swatch in the color (checked: with a check mark), then `children` as the name. */
export function ColorSchemeOption({
color,
className,
children,
...props
}: ColorSchemeOptionProps) {
return (
<RadioGroupItem
data-slot="color-scheme-option"
className={cn(
radioCard,
"items-center gap-2 px-1.5 pt-3 pb-2.5 text-xs font-bold",
className
)}
{...props}
>
<span
aria-hidden="true"
className="flex h-8 w-8 items-center justify-center rounded-full text-on-accent"
style={{
background: `linear-gradient(180deg, color-mix(in srgb, ${color} 88%, #fff) 0%, color-mix(in srgb, ${color} 90%, #000) 100%)`,
boxShadow:
"inset 0 1px 0 rgba(255,255,255,0.28), 0 1px 2px rgba(0,0,0,0.5)",
}}
>
<Check
size={16}
strokeWidth={3}
className="hidden group-data-[state=checked]:block"
/>
</span>
{children}
</RadioGroupItem>
)
}
/* ---------------------------------------------------------------- Status */
export interface SaveStatusProps extends ComponentProps<"span"> {
state: "idle" | "saving" | "saved"
}
/** Autosave indicator: "Wird gespeichert …" then "Gespeichert". Renders nothing while idle. */
export function SaveStatus({ state, className, ...props }: SaveStatusProps) {
if (state === "idle") return null
return (
<span
role="status"
data-slot="save-status"
className={cn(
"flex items-center gap-1.5 text-xs font-bold",
state === "saving" ? "text-fg-subtle" : "text-success-fg",
className
)}
{...props}
>
{state === "saving" ? (
<Spinner size={14} />
) : (
<Check size={14} strokeWidth={2.5} aria-hidden="true" />
)}
{state === "saving" ? "Wird gespeichert …" : "Gespeichert"}
</span>
)
}
+48
View File
@@ -0,0 +1,48 @@
import type { SVGAttributes } from "react"
import { cn } from "../../lib/cn"
export interface SpinnerProps extends SVGAttributes<SVGSVGElement> {
size?: number
}
/** Indeterminate loading ring. Inherits `currentColor`. */
export function Spinner({ size = 14, className, ...props }: SpinnerProps) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2.5}
strokeLinecap="round"
aria-hidden="true"
className={cn("cl-spinner flex-none animate-spin-fast", className)}
{...props}
>
<circle cx="12" cy="12" r="9" opacity={0.25} />
<path d="M21 12a9 9 0 0 0-9-9" />
</svg>
)
}
/** Checkmark that pops and draws in, shown briefly after an action succeeds. */
export function SuccessCheck({ size = 14, className, ...props }: SpinnerProps) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={3}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
className={cn("flex-none draw-check animate-pop", className)}
{...props}
>
<path d="M20 6 9 17l-5-5" />
</svg>
)
}
@@ -0,0 +1,59 @@
import {
useCallback,
useState,
type ComponentProps,
type CSSProperties,
} from "react"
import { cn } from "../../lib/cn"
import { PortalContainerContext } from "../../lib/portal"
export type Theme = "dark" | "light"
export type Tint = "off" | "subtle" | "strong"
export interface ThemeProviderProps extends ComponentProps<"div"> {
/** Color theme. */
theme?: Theme
/** Accent color for buttons, links and highlights. */
accent?: string
/** Mix a hint of the accent into neutral greys ("Neutraltöne einfärben"). */
tint?: Tint
}
/**
* Sets up a Collabry theme scope. Every component must render inside one;
* scopes can be nested (e.g. a light preview inside a dark page). Dialogs, menus
* and popovers opened inside portal into this element, so they share its theme.
*/
export function ThemeProvider({
theme = "dark",
accent = "#6A5FCB",
tint = "off",
className,
style,
children,
ref,
...props
}: ThemeProviderProps) {
const [el, setEl] = useState<HTMLDivElement | null>(null)
// Stable callback: a new one each render would detach/reattach and set state in a loop.
const setRefs = useCallback(
(node: HTMLDivElement | null) => {
setEl(node)
if (typeof ref === "function") ref(node)
else if (ref) ref.current = node
},
[ref]
)
return (
<div
ref={setRefs}
data-cl-theme={theme}
data-cl-tint={tint === "off" ? undefined : tint}
className={cn("font-sans text-base text-fg", className)}
style={{ "--cl-acc": accent, ...style } as CSSProperties}
{...props}
>
<PortalContainerContext value={el}>{children}</PortalContainerContext>
</div>
)
}
+70
View File
@@ -0,0 +1,70 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/cn"
import { Slot } from "radix-ui"
const buttonVariants = cva(
"relative inline-flex flex-none items-center justify-center font-bold whitespace-nowrap transition-[filter,background-color,border-color,color] duration-100 outline-none select-none focus-visible:shadow-focus [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
variants: {
variant: {
primary:
"border border-accent-deep text-on-accent shadow-primary bg-accent-gradient text-shadow-primary hover:brightness-110",
secondary:
"border border-line-strong text-fg-3 shadow-bevel bg-secondary-gradient hover:border-line-hover hover:text-fg-strong",
ghost:
"border border-transparent bg-transparent text-fg-muted hover:bg-hover hover:text-fg",
danger:
"border border-danger-solid-line bg-danger-solid text-on-accent hover:brightness-110",
"danger-outline":
"border border-line-danger-strong bg-transparent text-danger-fg hover:bg-[rgba(251,113,133,0.1)] hover:text-danger-fg",
},
// Heights from the design: 28 (row actions), 32, 36 (dialogs), 40 (page actions), 44 (auth forms).
size: {
xs: "h-7 gap-1.5 rounded-md px-2.5 text-sm",
sm: "h-8 gap-1.5 rounded-lg px-3 text-sm",
md: "h-9 gap-2 rounded-[10px] px-3.5 text-sm",
lg: "h-10 gap-2 rounded-[10px] px-4 text-base",
xl: "h-11 gap-2 rounded-[10px] px-5 text-base",
},
/** Square button with only an icon; pass `aria-label`. */
iconOnly: { true: "aspect-square px-0", false: "" },
fullWidth: { true: "w-full", false: "" },
},
defaultVariants: {
variant: "secondary",
size: "md",
},
}
)
type ButtonProps = React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}
function Button({
className,
variant,
size,
iconOnly,
fullWidth,
asChild = false,
...props
}: ButtonProps) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(
buttonVariants({ variant, size, iconOnly, fullWidth }),
className
)}
{...props}
/>
)
}
export { Button, buttonVariants, type ButtonProps }
+105
View File
@@ -0,0 +1,105 @@
import * as React from "react"
import { cn } from "@/lib/cn"
import { Slot } from "radix-ui"
/** The raised inner surface of a Collabry card. Use `asChild` for `section`, `article` or `form`. */
function Card({
className,
asChild,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "div"
return (
<Comp
data-slot="card"
className={cn(
"box-border flex min-w-0 flex-auto flex-col rounded-[13px] border border-line bg-surface text-fg",
className
)}
{...props}
/>
)
}
/** `CardTitle` (or a `CardHeading` with title and description), then `CardAction` on the right. Wraps when narrow. */
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"flex min-h-7 flex-wrap items-center justify-between gap-3",
className
)}
{...props}
/>
)
}
/** Card heading (`h2`; use `asChild` for another level). Put a `CountBadge` inside for a count. */
function CardTitle({
className,
asChild,
...props
}: React.ComponentProps<"h2"> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "h2"
return (
<Comp
data-slot="card-title"
className={cn("m-0 flex items-center gap-2 text-md font-bold", className)}
{...props}
/>
)
}
/** Groups `CardTitle` and `CardDescription` on the left of a `CardHeader`. */
function CardHeading({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-heading"
className={cn("min-w-0", className)}
{...props}
/>
)
}
/** Secondary line under the title. */
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("mt-1 text-sm text-fg-subtle", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn("flex items-center gap-3", className)}
{...props}
/>
)
}
/** Footer row that pins its content to the bottom of a card. */
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("mt-auto flex pt-1", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardHeading,
CardFooter,
CardTitle,
CardAction,
CardDescription,
}
+185
View File
@@ -0,0 +1,185 @@
import * as React from "react"
import { cn } from "@/lib/cn"
import { usePortalContainer } from "@/lib/portal"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { buttonVariants } from "@/components/ui/button"
function Dialog(props: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger(
props: React.ComponentProps<typeof DialogPrimitive.Trigger>
) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal(
props: React.ComponentProps<typeof DialogPrimitive.Portal>
) {
return (
<DialogPrimitive.Portal
data-slot="dialog-portal"
container={usePortalContainer()}
{...props}
/>
)
}
function DialogClose(
props: React.ComponentProps<typeof DialogPrimitive.Close>
) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
/** Dimmed, blurred backdrop. */
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 z-[60] bg-scrim backdrop-blur-[6px] data-[state=open]:animate-fade-in",
className
)}
{...props}
/>
)
}
/** Focus the first form field on open (instead of the close button), unless the handler prevented it. */
function focusFirstField(e: Event) {
const field = (e.currentTarget as HTMLElement).querySelector<HTMLElement>(
"[autofocus], input, textarea, select"
)
if (!field) return
e.preventDefault()
field.focus({ preventScroll: true })
}
/** Close button in the design's ghost style. */
const closeButtonClass = cn(
buttonVariants({ variant: "ghost", size: "sm", iconOnly: true }),
"text-fg-subtle"
)
function DialogContent({
className,
children,
showCloseButton = true,
onOpenAutoFocus,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-[10vh] left-1/2 z-[61] box-border w-[560px] max-w-[calc(100vw-32px)] -translate-x-1/2 rounded-2xl border border-line-strong bg-raised text-fg shadow-dialog outline-none data-[state=open]:animate-panel-in",
className
)}
onOpenAutoFocus={(e) => {
onOpenAutoFocus?.(e)
if (!e.defaultPrevented) focusFirstField(e)
}}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
aria-label="Schließen"
className={cn(closeButtonClass, "absolute top-5 right-4")}
>
<XIcon size={16} strokeWidth={1.75} />
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn(
"flex flex-col gap-1 pt-5 pr-[60px] pb-1 pl-[22px]",
className
)}
{...props}
/>
)
}
function DialogBody({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-body"
className={cn("flex flex-col gap-4 px-[22px] pt-4 pb-5", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex justify-end gap-2.5 border-t border-line-divider px-[22px] py-3.5",
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("m-0 text-lg font-bold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("m-0 text-sm text-fg-subtle", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogBody,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
closeButtonClass,
focusFirstField,
}
+19
View File
@@ -0,0 +1,19 @@
import * as React from "react"
import { cn } from "@/lib/cn"
/** Shared look of text inputs, textareas and selects. */
const fieldClass =
"box-border w-full min-w-0 rounded-[10px] border border-line bg-inset text-base text-fg font-[inherit] transition-[border-color,box-shadow] duration-100 outline-none placeholder:text-fg-subtle focus:border-accent-focus focus:shadow-focus disabled:opacity-50 aria-invalid:border-danger-fg"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(fieldClass, "h-[38px] px-3", className)}
{...props}
/>
)
}
export { Input, fieldClass }
+17
View File
@@ -0,0 +1,17 @@
import * as React from "react"
import { cn } from "@/lib/cn"
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
return (
<kbd
data-slot="kbd"
className={cn(
"box-border inline-flex h-[22px] min-w-[22px] items-center justify-center rounded-[5px] border border-line-heavy bg-elevated px-[5px] font-sans text-xs text-fg-muted select-none",
className
)}
{...props}
/>
)
}
export { Kbd }
+21
View File
@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/cn"
import { Label as LabelPrimitive } from "radix-ui"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"select-none peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }
+45
View File
@@ -0,0 +1,45 @@
import * as React from "react"
import { cn } from "@/lib/cn"
import { ChevronDownIcon } from "lucide-react"
import { fieldClass } from "@/components/ui/input"
const heights = { md: "h-[38px]", lg: "h-[42px]", settings: "h-10" }
type NativeSelectProps = Omit<React.ComponentProps<"select">, "size"> & {
/** 38px (filters, dialogs), 42px (auth forms) or 40px (settings rows). */
size?: keyof typeof heights
}
/** Native select with the design's chevron. `className` sizes the wrapper. */
function NativeSelect({ className, size = "md", ...props }: NativeSelectProps) {
return (
<span
data-slot="native-select-wrapper"
className={cn("relative flex", className)}
>
<select
data-slot="native-select"
data-size={size}
className={cn(
fieldClass,
heights[size],
"cursor-pointer appearance-none pr-8 pl-3"
)}
{...props}
/>
<ChevronDownIcon
size={16}
strokeWidth={1.75}
aria-hidden="true"
data-slot="native-select-icon"
className="pointer-events-none absolute top-1/2 right-2.5 -translate-y-1/2 text-fg-subtle"
/>
</span>
)
}
function NativeSelectOption(props: React.ComponentProps<"option">) {
return <option data-slot="native-select-option" {...props} />
}
export { NativeSelect, NativeSelectOption }
+35
View File
@@ -0,0 +1,35 @@
import * as React from "react"
import { cn } from "@/lib/cn"
import { RadioGroup as RadioGroupPrimitive } from "radix-ui"
function RadioGroup({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
return (
<RadioGroupPrimitive.Root
data-slot="radio-group"
className={cn("grid gap-3", className)}
{...props}
/>
)
}
/** A radio with custom content (cards, swatches). Style checked state with `data-[state=checked]:`. */
function RadioGroupItem({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
return (
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
"outline-none focus-visible:shadow-focus disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { RadioGroup, RadioGroupItem }
+19
View File
@@ -0,0 +1,19 @@
import * as React from "react"
import { cn } from "@/lib/cn"
import { fieldClass } from "@/components/ui/input"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
fieldClass,
"resize-y px-3 py-2.5 leading-normal",
className
)}
{...props}
/>
)
}
export { Textarea }
+58
View File
@@ -0,0 +1,58 @@
import * as React from "react"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/cn"
import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"
import { toggleVariants } from "@/components/ui/toggle"
const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants>
>({})
function ToggleGroup({
className,
variant,
size,
children,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<ToggleGroupPrimitive.Root
data-slot="toggle-group"
data-variant={variant}
data-size={size}
className={cn("group/toggle-group flex items-center", className)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
)
}
function ToggleGroupItem({
className,
variant,
size,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
VariantProps<typeof toggleVariants>) {
const context = React.useContext(ToggleGroupContext)
return (
<ToggleGroupPrimitive.Item
data-slot="toggle-group-item"
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
className
)}
{...props}
/>
)
}
export { ToggleGroup, ToggleGroupItem }
+46
View File
@@ -0,0 +1,46 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/cn"
import { Toggle as TogglePrimitive } from "radix-ui"
const toggleVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap outline-none focus-visible:shadow-focus disabled:pointer-events-none",
{
variants: {
variant: {
/** A segment of a segmented control. */
segment:
"box-border gap-1.5 rounded-[7px] border border-transparent bg-transparent text-sm font-bold text-fg-muted transition-colors duration-100 hover:text-fg disabled:opacity-50 data-[state=on]:border-line-heavy data-[state=on]:text-fg data-[state=on]:shadow-seg data-[state=on]:bg-seg-active",
/** Rounded filter pill. */
chip: "h-8 gap-2 rounded-full border border-line-divider bg-transparent px-3 text-sm font-bold text-fg-subtle hover:text-fg disabled:opacity-50 data-[state=on]:border-line-heavy data-[state=on]:bg-elevated data-[state=on]:text-fg",
/** No look of its own; style the children. */
bare: "",
},
size: {
sm: "h-[30px] px-[11px]",
md: "h-8 px-[11px]",
},
},
defaultVariants: {
variant: "segment",
},
}
)
function Toggle({
className,
variant,
size,
...props
}: React.ComponentProps<typeof TogglePrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<TogglePrimitive.Root
data-slot="toggle"
className={cn(toggleVariants({ variant, size }), className)}
{...props}
/>
)
}
export { Toggle, toggleVariants }
+30
View File
@@ -0,0 +1,30 @@
import { clsx, type ClassValue } from "clsx"
import { extendTailwindMerge } from "tailwind-merge"
// Teach tailwind-merge the custom font-size and shadow scales, so `text-sm` vs
// `text-fg-muted` and `shadow-focus` vs `shadow-xs` resolve as intended.
const twMerge = extendTailwindMerge({
extend: {
theme: {
text: ["2xs", "md", "display", "hero"],
shadow: [
"popover",
"menu",
"dropdown",
"dialog",
"toast",
"seg",
"bevel",
"nav-active",
"focus",
"side",
"primary",
"primary-flat",
],
},
},
})
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
+10
View File
@@ -0,0 +1,10 @@
import { createContext, useContext } from "react"
/**
* Element that overlays (dialogs, menus, popovers) portal into. `ThemeProvider`
* sets it to its own element, so portaled content keeps the theme, accent and tint.
*/
export const PortalContainerContext = createContext<HTMLElement | null>(null)
export const usePortalContainer = () =>
useContext(PortalContainerContext) ?? undefined
+277
View File
@@ -0,0 +1,277 @@
@import 'tailwindcss';
@import './tokens.css';
@source '../';
@custom-variant light (&:where([data-cl-theme='light'], [data-cl-theme='light'] *));
@custom-variant dark (&:where([data-cl-theme='dark'], [data-cl-theme='dark'] *));
@theme inline {
--font-sans: Lato, 'Segoe UI', system-ui, sans-serif;
--text-2xs: 11px;
--text-2xs--line-height: 1.3;
--text-xs: 12px;
--text-xs--line-height: 1.3;
--text-sm: 13px;
--text-sm--line-height: 1.45;
--text-base: 14px;
--text-base--line-height: 1.45;
--text-md: 15px;
--text-md--line-height: 1.3;
--text-lg: 17px;
--text-lg--line-height: 1.3;
--text-xl: 20px;
--text-xl--line-height: 1.3;
--text-display: 28px;
--text-display--line-height: 1.2;
--text-hero: 48px;
--text-hero--line-height: 1;
--color-accent: var(--cl-accent);
--color-accent-fg: var(--cl-accent-fg);
--color-accent-fg-hover: var(--cl-accent-fg-hover);
--color-accent-focus: var(--cl-accent-focus);
--color-accent-ring: var(--cl-accent-ring);
--color-accent-soft: var(--cl-accent-soft);
--color-accent-chip: var(--cl-accent-chip);
--color-app: var(--cl-app);
--color-frame: var(--cl-frame);
--color-surface: var(--cl-surface);
--color-inset: var(--cl-inset);
--color-raised: var(--cl-raised);
--color-elevated: var(--cl-elevated);
--color-chip: var(--cl-chip);
--color-track: var(--cl-track);
--color-soft: var(--cl-soft);
--color-section: var(--cl-section);
--color-outside: var(--cl-outside);
--color-weekend: var(--cl-weekend);
--color-brand: var(--cl-brand);
--color-feature: var(--cl-feature);
--color-status-open: var(--cl-status-open);
--color-seg-from: var(--cl-seg-from);
--color-seg-to: var(--cl-seg-to);
--color-option-active: var(--cl-option-active);
--color-grid: var(--cl-grid);
--color-hover-row: var(--cl-hover-row);
--color-hover: var(--cl-hover);
--color-hover-menu: var(--cl-hover-menu);
--color-line-frame: var(--cl-line-frame);
--color-line: var(--cl-line);
--color-line-strong: var(--cl-line-strong);
--color-line-heavy: var(--cl-line-heavy);
--color-line-divider: var(--cl-line-divider);
--color-line-subtle: var(--cl-line-subtle);
--color-line-row: var(--cl-line-row);
--color-line-control: var(--cl-line-control);
--color-line-hover: var(--cl-line-hover);
--color-line-shell: var(--cl-line-shell);
--color-line-danger: var(--cl-line-danger);
--color-line-danger-strong: var(--cl-line-danger-strong);
--color-fg: var(--cl-fg);
--color-fg-strong: var(--cl-fg-strong);
--color-fg-2: var(--cl-fg-2);
--color-fg-3: var(--cl-fg-3);
--color-fg-4: var(--cl-fg-4);
--color-fg-muted: var(--cl-fg-muted);
--color-fg-subtle: var(--cl-fg-subtle);
--color-fg-faint: var(--cl-fg-faint);
--color-fg-dim: var(--cl-fg-dim);
--color-fg-open: var(--cl-fg-open);
--color-on-color: var(--cl-on-color);
--color-on-accent: var(--cl-white);
--color-side: var(--cl-side);
--color-side-line: var(--cl-side-line);
--color-side-active: var(--cl-side-active);
--color-side-active-line: var(--cl-side-active-line);
--color-success: var(--cl-success);
--color-success-fg: var(--cl-success-fg);
--color-warning: var(--cl-warning);
--color-warning-fg: var(--cl-warning-fg);
--color-info: var(--cl-info);
--color-info-fg: var(--cl-info-fg);
--color-danger: var(--cl-danger);
--color-danger-fg: var(--cl-danger-fg);
--color-danger-solid: var(--cl-danger-solid);
--color-danger-solid-line: var(--cl-danger-solid-line);
--color-open-bar: var(--cl-open-bar);
--color-glass: var(--cl-glass);
--color-glass-2: var(--cl-glass-2);
--color-scrim: var(--cl-sh-50);
/* shadcn/ui token names, so components added with `npx shadcn add` pick up the
Collabry palette. `accent` stays the Collabry brand color (shadcn uses it as a
hover fill), so restyle `bg-accent` hovers to `bg-hover-menu` after adding. */
--color-background: var(--cl-surface);
--color-foreground: var(--cl-fg);
--color-card: var(--cl-surface);
--color-card-foreground: var(--cl-fg);
--color-popover: var(--cl-raised);
--color-popover-foreground: var(--cl-fg);
--color-primary: var(--cl-acc);
--color-primary-foreground: var(--cl-white);
--color-secondary: var(--cl-elevated);
--color-secondary-foreground: var(--cl-fg-3);
--color-muted: var(--cl-chip);
--color-muted-foreground: var(--cl-fg-subtle);
--color-accent-foreground: var(--cl-fg-strong);
--color-destructive: var(--cl-danger-solid);
--color-border: var(--cl-line);
--color-input: var(--cl-line);
--color-ring: var(--cl-accent-focus);
--shadow-popover: 0 0 0 1px var(--cl-sh-60), 0 24px 56px -12px var(--cl-sh-85);
--shadow-menu: 0 0 0 1px var(--cl-sh-60), 0 18px 48px -8px var(--cl-sh-85);
--shadow-dropdown: 0 0 0 1px var(--cl-sh-60), 0 16px 40px -8px var(--cl-sh-85);
--shadow-dialog: 0 0 0 1px var(--cl-sh-60), 0 24px 64px -12px var(--cl-sh-85);
--shadow-toast: 0 12px 32px -8px var(--cl-sh-85);
--shadow-seg: inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 1px 2px var(--cl-sh-50);
--shadow-bevel: inset 0 1px 0 rgba(255, 255, 255, 0.06);
--shadow-nav-active: inset 0 0 0 1px var(--cl-side-active-line), inset 0 1px 0 rgba(255, 255, 255, 0.04);
--shadow-focus: 0 0 0 3px var(--cl-accent-ring);
--shadow-side: var(--cl-side-shadow);
--animate-spin-fast: cl-spin 0.7s linear infinite;
--animate-pop: cl-pop 0.28s cubic-bezier(0.2, 1.5, 0.4, 1) both;
--animate-panel-in: cl-panel-in 180ms cubic-bezier(0.2, 0.8, 0.2, 1);
--animate-drawer-in: cl-drawer-in 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
--animate-fade-in: cl-fade-in 150ms ease-out;
}
@keyframes cl-spin {
to {
transform: rotate(360deg);
}
}
@keyframes cl-pop {
from {
transform: scale(0.5);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
@keyframes cl-draw {
to {
stroke-dashoffset: 0;
}
}
@keyframes cl-panel-in {
from {
opacity: 0;
transform: translateY(-8px) scale(0.98);
}
to {
opacity: 1;
transform: none;
}
}
@keyframes cl-drawer-in {
from {
opacity: 0;
transform: translateX(16px);
}
to {
opacity: 1;
transform: none;
}
}
@keyframes cl-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* Primary button fill: accent gradient with a bevel. */
@utility bg-accent-gradient {
background: linear-gradient(
180deg,
color-mix(in srgb, var(--cl-acc) 88%, #fff) 0%,
color-mix(in srgb, var(--cl-acc) 90%, #000) 100%
);
}
@utility border-accent-deep {
border-color: color-mix(in srgb, var(--cl-acc) 62%, #000);
}
@utility shadow-primary {
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.28),
0 1px 2px var(--cl-sh-50),
0 6px 18px -6px color-mix(in srgb, var(--cl-acc) 60%, transparent);
}
@utility shadow-primary-flat {
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.28);
}
@utility text-shadow-primary {
text-shadow: 0 1px 0 var(--cl-sh-18);
}
/* Secondary button fill. */
@utility bg-secondary-gradient {
background: linear-gradient(180deg, var(--cl-elevated), var(--cl-surface));
}
/* Active segment in a segmented control. */
@utility bg-seg-active {
background: linear-gradient(180deg, var(--cl-seg-from), var(--cl-seg-to));
}
/* Checkmark that draws itself in after a successful action. */
@utility draw-check {
& path {
stroke-dasharray: 24;
stroke-dashoffset: 24;
animation: cl-draw 0.32s 0.06s ease-out forwards;
}
}
@layer base {
[data-cl-theme] {
font-family: var(--font-sans);
font-size: var(--text-base);
line-height: 1.45;
color: var(--cl-fg);
}
[data-cl-theme] button {
cursor: pointer;
}
[data-cl-theme] button:disabled {
cursor: default;
}
[data-cl-theme] [aria-busy='true'] {
cursor: progress;
}
[data-cl-theme] a {
color: var(--cl-accent-fg);
text-decoration: none;
}
[data-cl-theme] a:hover {
color: var(--cl-accent-fg-hover);
}
[data-cl-theme] input::placeholder,
[data-cl-theme] textarea::placeholder {
color: var(--cl-fg-subtle);
}
@media (prefers-reduced-motion: reduce) {
[data-cl-theme] *,
[data-cl-theme] *::before,
[data-cl-theme] *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
/* Spinners keep turning, just slower, so loading stays visible. */
[data-cl-theme] .cl-spinner {
animation-duration: 1.8s !important;
animation-iteration-count: infinite !important;
}
}
}
+260
View File
@@ -0,0 +1,260 @@
/*
* Collabry design tokens.
*
* Every theme scope (`:root` or any element with `data-cl-theme`) defines raw
* values (`--cl-raw-*`) per theme and derives the semantic tokens (`--cl-*`)
* from them. Neutral tokens are mixed with the accent by `--cl-tint-bg` /
* `--cl-tint-fg`, which are 0% unless `data-cl-tint` is set, so "Neutraltöne
* einfärben" works by changing one attribute.
*/
:root,
[data-cl-theme] {
color-scheme: dark;
--cl-acc: #6a5fcb;
--cl-tint-bg: 0%;
--cl-tint-fg: 0%;
/* Surfaces */
--cl-raw-app: #050505;
--cl-raw-frame: #0a0a0a;
--cl-raw-surface: #141414;
--cl-raw-inset: #0e0e0e;
--cl-raw-raised: #161616;
--cl-raw-elevated: #1c1c1c;
--cl-raw-chip: #262626;
--cl-raw-track: #222222;
--cl-raw-soft: #1f1f1f;
--cl-raw-section: #101010;
--cl-raw-outside: #0c0c0c;
--cl-raw-weekend: #101010;
--cl-raw-brand: #000000;
--cl-raw-feature: #111111;
--cl-raw-status-open: #171717;
--cl-raw-seg-from: #212121;
--cl-raw-seg-to: #191919;
--cl-raw-option-active: #232323;
--cl-raw-grid: #242424;
--cl-raw-hover-row: #121212;
--cl-raw-hover: #1c1c1c;
--cl-raw-hover-menu: #1f1f1f;
/* Lines */
--cl-raw-line-frame: #1f1f1f;
--cl-raw-line: #2a2a2a;
--cl-raw-line-strong: #2e2e2e;
--cl-raw-line-heavy: #333333;
--cl-raw-line-divider: #262626;
--cl-raw-line-subtle: #242424;
--cl-raw-line-row: #222222;
--cl-raw-line-control: #3a3a3a;
--cl-raw-line-hover: #3a3a3a;
--cl-raw-line-shell: #1c1c1c;
--cl-raw-line-danger: #3a1d24;
--cl-raw-line-danger-strong: #5b2330;
/* Text */
--cl-raw-fg: #ededed;
--cl-raw-fg-strong: #ffffff;
--cl-raw-fg-2: #e5e5e5;
--cl-raw-fg-3: #d4d4d4;
--cl-raw-fg-4: #c7c7c7;
--cl-raw-fg-muted: #a3a3a3;
--cl-raw-fg-subtle: #8a8a8a;
--cl-raw-fg-faint: #6b6b6b;
--cl-raw-fg-dim: #5c5c5c;
--cl-raw-fg-open: #b5b5b5;
/* Sidebar */
--cl-raw-side: #0a0a0a;
--cl-raw-side-line: #1c1c1c;
--cl-raw-side-active: #1a1a1a;
--cl-raw-side-active-line: #2a2a2a;
--cl-side-shadow: none;
/* Status (not tinted) */
--cl-success: #34d399;
--cl-success-fg: #4ade80;
--cl-warning: #fbbf24;
--cl-warning-fg: #fbbf24;
--cl-info: #60a5fa;
--cl-info-fg: #7db4fb;
--cl-danger: #fb7185;
--cl-danger-fg: #fb7185;
--cl-danger-solid: #be123c;
--cl-danger-solid-line: #9f1239;
--cl-open-bar: #383838;
--cl-on-color: #0a0a0a;
--cl-white: #ffffff;
/* Shadow colors */
--cl-sh-18: rgba(0, 0, 0, 0.18);
--cl-sh-50: rgba(0, 0, 0, 0.5);
--cl-sh-60: rgba(0, 0, 0, 0.6);
--cl-sh-80: rgba(0, 0, 0, 0.8);
--cl-sh-85: rgba(0, 0, 0, 0.85);
--cl-glass: rgba(5, 5, 5, 0.92);
--cl-glass-2: rgba(10, 10, 10, 0.94);
/* Accent derived */
--cl-accent-fg: color-mix(in srgb, var(--cl-acc) 55%, #fff);
--cl-accent-fg-hover: color-mix(in srgb, var(--cl-acc) 35%, #fff);
--cl-accent-focus: color-mix(in srgb, var(--cl-acc) 80%, #fff);
/* ---- Semantic tokens (shared by both themes) ---- */
--cl-accent: var(--cl-acc);
--cl-accent-ring: color-mix(in srgb, var(--cl-acc) 30%, transparent);
--cl-accent-soft: color-mix(in srgb, var(--cl-acc) 10%, transparent);
--cl-accent-chip: color-mix(in srgb, var(--cl-acc) 22%, transparent);
--cl-app: color-mix(in srgb, var(--cl-raw-app), var(--cl-acc) var(--cl-tint-bg));
--cl-frame: color-mix(in srgb, var(--cl-raw-frame), var(--cl-acc) var(--cl-tint-bg));
--cl-surface: color-mix(in srgb, var(--cl-raw-surface), var(--cl-acc) var(--cl-tint-bg));
--cl-inset: color-mix(in srgb, var(--cl-raw-inset), var(--cl-acc) var(--cl-tint-bg));
--cl-raised: color-mix(in srgb, var(--cl-raw-raised), var(--cl-acc) var(--cl-tint-bg));
--cl-elevated: color-mix(in srgb, var(--cl-raw-elevated), var(--cl-acc) var(--cl-tint-bg));
--cl-chip: color-mix(in srgb, var(--cl-raw-chip), var(--cl-acc) var(--cl-tint-bg));
--cl-track: color-mix(in srgb, var(--cl-raw-track), var(--cl-acc) var(--cl-tint-bg));
--cl-soft: color-mix(in srgb, var(--cl-raw-soft), var(--cl-acc) var(--cl-tint-bg));
--cl-section: color-mix(in srgb, var(--cl-raw-section), var(--cl-acc) var(--cl-tint-bg));
--cl-outside: color-mix(in srgb, var(--cl-raw-outside), var(--cl-acc) var(--cl-tint-bg));
--cl-weekend: color-mix(in srgb, var(--cl-raw-weekend), var(--cl-acc) var(--cl-tint-bg));
--cl-brand: color-mix(in srgb, var(--cl-raw-brand), var(--cl-acc) var(--cl-tint-bg));
--cl-feature: color-mix(in srgb, var(--cl-raw-feature), var(--cl-acc) var(--cl-tint-bg));
--cl-status-open: color-mix(in srgb, var(--cl-raw-status-open), var(--cl-acc) var(--cl-tint-bg));
--cl-seg-from: color-mix(in srgb, var(--cl-raw-seg-from), var(--cl-acc) var(--cl-tint-bg));
--cl-seg-to: color-mix(in srgb, var(--cl-raw-seg-to), var(--cl-acc) var(--cl-tint-bg));
--cl-option-active: color-mix(in srgb, var(--cl-raw-option-active), var(--cl-acc) var(--cl-tint-bg));
--cl-grid: color-mix(in srgb, var(--cl-raw-grid), var(--cl-acc) var(--cl-tint-bg));
--cl-hover-row: color-mix(in srgb, var(--cl-raw-hover-row), var(--cl-acc) var(--cl-tint-bg));
--cl-hover: color-mix(in srgb, var(--cl-raw-hover), var(--cl-acc) var(--cl-tint-bg));
--cl-hover-menu: color-mix(in srgb, var(--cl-raw-hover-menu), var(--cl-acc) var(--cl-tint-bg));
--cl-line-frame: color-mix(in srgb, var(--cl-raw-line-frame), var(--cl-acc) var(--cl-tint-bg));
--cl-line: color-mix(in srgb, var(--cl-raw-line), var(--cl-acc) var(--cl-tint-bg));
--cl-line-strong: color-mix(in srgb, var(--cl-raw-line-strong), var(--cl-acc) var(--cl-tint-bg));
--cl-line-heavy: color-mix(in srgb, var(--cl-raw-line-heavy), var(--cl-acc) var(--cl-tint-bg));
--cl-line-divider: color-mix(in srgb, var(--cl-raw-line-divider), var(--cl-acc) var(--cl-tint-bg));
--cl-line-subtle: color-mix(in srgb, var(--cl-raw-line-subtle), var(--cl-acc) var(--cl-tint-bg));
--cl-line-row: color-mix(in srgb, var(--cl-raw-line-row), var(--cl-acc) var(--cl-tint-bg));
--cl-line-control: color-mix(in srgb, var(--cl-raw-line-control), var(--cl-acc) var(--cl-tint-bg));
--cl-line-hover: color-mix(in srgb, var(--cl-raw-line-hover), var(--cl-acc) var(--cl-tint-bg));
--cl-line-shell: color-mix(in srgb, var(--cl-raw-line-shell), var(--cl-acc) var(--cl-tint-bg));
--cl-line-danger: var(--cl-raw-line-danger);
--cl-line-danger-strong: var(--cl-raw-line-danger-strong);
--cl-fg: color-mix(in srgb, var(--cl-raw-fg), var(--cl-acc) var(--cl-tint-fg));
--cl-fg-strong: color-mix(in srgb, var(--cl-raw-fg-strong), var(--cl-acc) var(--cl-tint-fg));
--cl-fg-2: color-mix(in srgb, var(--cl-raw-fg-2), var(--cl-acc) var(--cl-tint-fg));
--cl-fg-3: color-mix(in srgb, var(--cl-raw-fg-3), var(--cl-acc) var(--cl-tint-fg));
--cl-fg-4: color-mix(in srgb, var(--cl-raw-fg-4), var(--cl-acc) var(--cl-tint-fg));
--cl-fg-muted: color-mix(in srgb, var(--cl-raw-fg-muted), var(--cl-acc) var(--cl-tint-fg));
--cl-fg-subtle: color-mix(in srgb, var(--cl-raw-fg-subtle), var(--cl-acc) var(--cl-tint-fg));
--cl-fg-faint: color-mix(in srgb, var(--cl-raw-fg-faint), var(--cl-acc) var(--cl-tint-fg));
--cl-fg-dim: color-mix(in srgb, var(--cl-raw-fg-dim), var(--cl-acc) var(--cl-tint-fg));
--cl-fg-open: color-mix(in srgb, var(--cl-raw-fg-open), var(--cl-acc) var(--cl-tint-fg));
--cl-side: color-mix(in srgb, var(--cl-raw-side), var(--cl-acc) var(--cl-tint-bg));
--cl-side-line: color-mix(in srgb, var(--cl-raw-side-line), var(--cl-acc) var(--cl-tint-bg));
--cl-side-active: color-mix(in srgb, var(--cl-raw-side-active), var(--cl-acc) var(--cl-tint-bg));
--cl-side-active-line: color-mix(in srgb, var(--cl-raw-side-active-line), var(--cl-acc) var(--cl-tint-bg));
}
[data-cl-theme='light'] {
color-scheme: light;
--cl-raw-app: #f4f4f5;
--cl-raw-frame: #ededef;
--cl-raw-surface: #ffffff;
--cl-raw-inset: #fafafa;
--cl-raw-raised: #ffffff;
--cl-raw-elevated: #ffffff;
--cl-raw-chip: #e7e7ea;
--cl-raw-track: #e8e8eb;
--cl-raw-soft: #f1f1f3;
--cl-raw-section: #f7f7f8;
--cl-raw-outside: #fafafa;
--cl-raw-weekend: #f7f7f8;
--cl-raw-brand: #ffffff;
--cl-raw-feature: #f4f4f5;
--cl-raw-status-open: #f4f4f5;
--cl-raw-seg-from: #ffffff;
--cl-raw-seg-to: #fafafa;
--cl-raw-option-active: #ffffff;
--cl-raw-grid: #e4e4e7;
--cl-raw-hover-row: #f4f4f5;
--cl-raw-hover: #f1f1f3;
--cl-raw-hover-menu: #f1f1f3;
--cl-raw-line-frame: #e4e4e7;
--cl-raw-line: #dedee3;
--cl-raw-line-strong: #d4d4d8;
--cl-raw-line-heavy: #d4d4d8;
--cl-raw-line-divider: #e4e4e7;
--cl-raw-line-subtle: #ededef;
--cl-raw-line-row: #ededef;
--cl-raw-line-control: #c4c4ca;
--cl-raw-line-hover: #a1a1aa;
--cl-raw-line-shell: #e4e4e7;
--cl-raw-line-danger: #f6cfd7;
--cl-raw-line-danger-strong: #f0a3b2;
--cl-raw-fg: #18181b;
--cl-raw-fg-strong: #18181b;
--cl-raw-fg-2: #27272a;
--cl-raw-fg-3: #3f3f46;
--cl-raw-fg-4: #52525b;
--cl-raw-fg-muted: #5b5b66;
--cl-raw-fg-subtle: #71717a;
--cl-raw-fg-faint: #a1a1aa;
--cl-raw-fg-dim: #a1a1aa;
--cl-raw-fg-open: #52525b;
--cl-raw-side: #ffffff;
--cl-raw-side-line: #d9d9de;
--cl-raw-side-active: #f1f1f3;
--cl-raw-side-active-line: #dcdce1;
--cl-side-shadow: 1px 0 0 rgba(0, 0, 0, 0.02), 4px 0 16px -8px rgba(0, 0, 0, 0.08);
--cl-warning: #f59e0b;
--cl-warning-fg: #b45309;
--cl-success-fg: #15803d;
--cl-info: #3b82f6;
--cl-info-fg: #1d4ed8;
--cl-danger: #f43f5e;
--cl-danger-fg: #e11d48;
--cl-danger-solid: #e11d48;
--cl-open-bar: #d4d4d8;
--cl-sh-18: rgba(0, 0, 0, 0.05);
--cl-sh-50: rgba(0, 0, 0, 0.12);
--cl-sh-60: rgba(0, 0, 0, 0.06);
--cl-sh-80: rgba(0, 0, 0, 0.14);
--cl-sh-85: rgba(0, 0, 0, 0.16);
--cl-glass: rgba(255, 255, 255, 0.9);
--cl-glass-2: rgba(255, 255, 255, 0.94);
--cl-accent-fg: color-mix(in srgb, var(--cl-acc) 85%, #000);
--cl-accent-fg-hover: color-mix(in srgb, var(--cl-acc) 65%, #000);
--cl-accent-focus: var(--cl-acc);
}
[data-cl-tint='subtle'] {
--cl-tint-bg: 5%;
--cl-tint-fg: 6%;
}
[data-cl-tint='strong'] {
--cl-tint-bg: 10%;
--cl-tint-fg: 12%;
}
[data-cl-theme='light'][data-cl-tint='subtle'] {
--cl-tint-bg: 3%;
--cl-tint-fg: 5%;
}
[data-cl-theme='light'][data-cl-tint='strong'] {
--cl-tint-bg: 7%;
--cl-tint-fg: 10%;
}
+2 -1
View File
@@ -13,7 +13,8 @@
"lib": ["ES2022", "DOM", "DOM.Iterable"], "lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["vite/client"], "types": ["vite/client"],
"paths": { "paths": {
"@/*": ["./src/*"] // second entry: imports inside the vendored Collabry files (see its UPSTREAM.md)
"@/*": ["./src/*", "./src/vendor/collabry/*"]
}, },
/* Bundler mode */ /* Bundler mode */
+8 -1
View File
@@ -1,12 +1,19 @@
import { defineConfig } from "vite" import { defineConfig } from "vite"
import { devtools } from "@tanstack/devtools-vite" import { devtools } from "@tanstack/devtools-vite"
import { tanstackStart } from "@tanstack/react-start/plugin/vite" import { tanstackStart } from "@tanstack/react-start/plugin/vite"
import { nitro } from "nitro/vite"
import viteReact from "@vitejs/plugin-react" import viteReact from "@vitejs/plugin-react"
import tailwindcss from "@tailwindcss/vite" import tailwindcss from "@tailwindcss/vite"
try {
process.loadEnvFile() // server-side env (DATABASE_URL, ...) for dev and build
} catch {
// no .env file: use the real environment
}
const config = defineConfig({ const config = defineConfig({
resolve: { tsconfigPaths: true }, resolve: { tsconfigPaths: true },
plugins: [devtools(), tailwindcss(), tanstackStart(), viteReact()], plugins: [devtools(), tailwindcss(), tanstackStart(), nitro(), viteReact()],
}) })
export default config export default config