From e44e56fd2db7e571cb20c9c79205c23551775cae Mon Sep 17 00:00:00 2001 From: Philipp Traber Date: Wed, 14 Oct 2026 16:46:36 +0200 Subject: [PATCH] Save imported palettes per user and assign single palette colors - imported coolors.co palettes are stored per user (new palettes table, GET/POST/DELETE /palettes, duplicates ignored, max 50) and listed under "Your palettes" with a remove button - clicking a single color of any palette opens a menu to use it as background, text, buttons or button text; the name row still applies the whole palette - theme picker moved into its own component Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- drizzle/0002_user_palettes.sql | 9 + drizzle/meta/0002_snapshot.json | 653 +++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/server/api.ts | 14 + src/server/db/schema.ts | 14 + src/server/lib/palettes.ts | 50 ++ src/shared/api-types.ts | 6 + src/shared/validation.ts | 6 + src/web/screens/detail/AppearanceTab.tsx | 211 +------- src/web/screens/detail/ThemePicker.tsx | 416 +++++++++++++++ test/api.test.ts | 32 ++ 12 files changed, 1212 insertions(+), 208 deletions(-) create mode 100644 drizzle/0002_user_palettes.sql create mode 100644 drizzle/meta/0002_snapshot.json create mode 100644 src/server/lib/palettes.ts create mode 100644 src/web/screens/detail/ThemePicker.tsx diff --git a/README.md b/README.md index 32b3cb1..9e77a68 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ curl -X POST https://short.example.com/~/api/pages \ -d '{"kind":"redirect","dest":"https://example.com","code":"optional"}' ``` -Main endpoints: `GET/POST /pages`, `GET/PATCH/DELETE /pages/:id`, `GET/DELETE /pages/:id/stats?days=7|30|90`, `POST /pages/:id/blocks`, `PUT /pages/:id/blocks/order`, `PATCH/DELETE /blocks/:id`, `PUT /pages/:id/avatar`, `GET/POST/DELETE /tokens`. +Main endpoints: `GET/POST /pages`, `GET/PATCH/DELETE /pages/:id`, `GET/DELETE /pages/:id/stats?days=7|30|90`, `POST /pages/:id/blocks`, `PUT /pages/:id/blocks/order`, `PATCH/DELETE /blocks/:id`, `PUT /pages/:id/avatar`, `GET/POST/DELETE /palettes`, `GET/POST/DELETE /tokens`. Admin only: `PUT/DELETE /pin`, `GET /users`, `GET /conflicts`. Link buttons can reference an existing short link (`{"kind":"link","label":"…","targetId":12}`) or create one in the page's namespace in the same request (`{"kind":"link","label":"…","newLink":{"dest":"https://…","code":"optional"}}`). diff --git a/drizzle/0002_user_palettes.sql b/drizzle/0002_user_palettes.sql new file mode 100644 index 0000000..2a0c937 --- /dev/null +++ b/drizzle/0002_user_palettes.sql @@ -0,0 +1,9 @@ +CREATE TABLE `palettes` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `user_id` integer NOT NULL, + `colors` text NOT NULL, + `created_at` integer DEFAULT (unixepoch()) NOT NULL, + FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `palettes_user_colors` ON `palettes` (`user_id`,`colors`); \ No newline at end of file diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..94abb9e --- /dev/null +++ b/drizzle/meta/0002_snapshot.json @@ -0,0 +1,653 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "587766a4-dd62-4efe-bce3-dd939b9d72c2", + "prevId": "d686eb3d-38c6-4fa3-bdbd-6a774f85ddb0", + "tables": { + "api_tokens": { + "name": "api_tokens", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "api_tokens_token_hash_unique": { + "name": "api_tokens_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": { + "api_tokens_user_id_users_id_fk": { + "name": "api_tokens_user_id_users_id_fk", + "tableFrom": "api_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "blocks": { + "name": "blocks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "page_id": { + "name": "page_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "markdown": { + "name": "markdown", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "blocks_page": { + "name": "blocks_page", + "columns": [ + "page_id", + "position" + ], + "isUnique": false + }, + "blocks_target": { + "name": "blocks_target", + "columns": [ + "target_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "blocks_page_id_pages_id_fk": { + "name": "blocks_page_id_pages_id_fk", + "tableFrom": "blocks", + "tableTo": "pages", + "columnsFrom": [ + "page_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "blocks_target_id_pages_id_fk": { + "name": "blocks_target_id_pages_id_fk", + "tableFrom": "blocks", + "tableTo": "pages", + "columnsFrom": [ + "target_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "clicks": { + "name": "clicks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "page_id": { + "name": "page_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "day": { + "name": "day", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "visitor": { + "name": "visitor", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "clicks_page_day": { + "name": "clicks_page_day", + "columns": [ + "page_id", + "day", + "visitor" + ], + "isUnique": false + }, + "clicks_at": { + "name": "clicks_at", + "columns": [ + "at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "clicks_page_id_pages_id_fk": { + "name": "clicks_page_id_pages_id_fk", + "tableFrom": "clicks", + "tableTo": "pages", + "columnsFrom": [ + "page_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "daily_stats": { + "name": "daily_stats", + "columns": { + "page_id": { + "name": "page_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "day": { + "name": "day", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "clicks": { + "name": "clicks", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "uniques": { + "name": "uniques", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_at": { + "name": "last_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "daily_stats_page_id_pages_id_fk": { + "name": "daily_stats_page_id_pages_id_fk", + "tableFrom": "daily_stats", + "tableTo": "pages", + "columnsFrom": [ + "page_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "daily_stats_page_id_day_pk": { + "columns": [ + "page_id", + "day" + ], + "name": "daily_stats_page_id_day_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "pages": { + "name": "pages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "namespace": { + "name": "namespace", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dest": { + "name": "dest", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar": { + "name": "avatar", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "theme": { + "name": "theme", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "show_logos": { + "name": "show_logos", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "pages_namespace_code": { + "name": "pages_namespace_code", + "columns": [ + "namespace", + "code" + ], + "isUnique": true + } + }, + "foreignKeys": { + "pages_created_by_users_id_fk": { + "name": "pages_created_by_users_id_fk", + "tableFrom": "pages", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "palettes": { + "name": "palettes", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "colors": { + "name": "colors", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "palettes_user_colors": { + "name": "palettes_user_colors", + "columns": [ + "user_id", + "colors" + ], + "isUnique": true + } + }, + "foreignKeys": { + "palettes_user_id_users_id_fk": { + "name": "palettes_user_id_users_id_fk", + "tableFrom": "palettes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "sub": { + "name": "sub", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_admin": { + "name": "is_admin", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(unixepoch())" + } + }, + "indexes": { + "users_sub_unique": { + "name": "users_sub_unique", + "columns": [ + "sub" + ], + "isUnique": true + }, + "users_username_unique": { + "name": "users_username_unique", + "columns": [ + "username" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 093d048..8e4036a 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1791988240968, "tag": "0001_page_show_logos", "breakpoints": true + }, + { + "idx": 2, + "version": "6", + "when": 1791989055221, + "tag": "0002_user_palettes", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/server/api.ts b/src/server/api.ts index fe2c58d..1c62471 100644 --- a/src/server/api.ts +++ b/src/server/api.ts @@ -5,6 +5,7 @@ import type { z } from "zod"; import type { ApiToken, CreatedToken, Me } from "../shared/api-types.js"; import { createBlockSchema, + createPaletteSchema, createPageSchema, createTokenSchema, pinSchema, @@ -19,6 +20,7 @@ import { createApiToken } from "./auth/sessions.js"; import { apiTokens } from "./db/schema.js"; import { forbidden, HttpError, notFound } from "./lib/errors.js"; import { removeMedia, saveAvatar } from "./lib/media.js"; +import { deletePalette, listPalettes, savePalette } from "./lib/palettes.js"; import * as pages from "./lib/pages.js"; import { getStats, resetStats } from "./lib/stats.js"; @@ -133,6 +135,18 @@ export function apiRoutes(deps: Deps) { return c.body(null, 204); }) + // Saved color palettes (always the caller's own) + .get("/palettes", (c) => c.json(listPalettes(db, c.var.actor.id))) + .post("/palettes", async (c) => { + const { colors } = parse(createPaletteSchema, await jsonBody(c)); + const { palette, created } = savePalette(db, c.var.actor.id, colors); + return c.json(palette, created ? 201 : 200); + }) + .delete("/palettes/:id", (c) => { + deletePalette(db, c.var.actor.id, idParam(c.req.param("id"))); + return c.body(null, 204); + }) + // Personal access tokens (always the caller's own) .get("/tokens", (c) => { const rows = db diff --git a/src/server/db/schema.ts b/src/server/db/schema.ts index d84f324..5a7effc 100644 --- a/src/server/db/schema.ts +++ b/src/server/db/schema.ts @@ -103,6 +103,20 @@ export const apiTokens = sqliteTable("api_tokens", { lastUsedAt: integer("last_used_at", { mode: "timestamp" }), }); +// Color palettes a user imported (e.g. from coolors.co), stored as lowercase "rrggbb-rrggbb-…". +export const palettes = sqliteTable( + "palettes", + { + id: integer("id").primaryKey({ autoIncrement: true }), + userId: integer("user_id") + .notNull() + .references(() => users.id, { onDelete: "cascade" }), + colors: text("colors").notNull(), + createdAt: createdAt(), + }, + (t) => [uniqueIndex("palettes_user_colors").on(t.userId, t.colors)], +); + export const settings = sqliteTable("settings", { key: text("key").primaryKey(), value: text("value").notNull(), diff --git a/src/server/lib/palettes.ts b/src/server/lib/palettes.ts new file mode 100644 index 0000000..40b0360 --- /dev/null +++ b/src/server/lib/palettes.ts @@ -0,0 +1,50 @@ +import { and, desc, eq, sql } from "drizzle-orm"; +import type { SavedPalette } from "../../shared/api-types.js"; +import { MAX_PALETTES } from "../../shared/validation.js"; +import type { Db } from "../db/index.js"; +import { palettes } from "../db/schema.js"; +import { HttpError, notFound } from "./errors.js"; + +type PaletteRow = typeof palettes.$inferSelect; + +function toApi(row: PaletteRow): SavedPalette { + return { + id: row.id, + colors: row.colors.split("-").map((c) => `#${c}`), + createdAt: row.createdAt.toISOString(), + }; +} + +export function listPalettes(db: Db, userId: number): SavedPalette[] { + return db.select().from(palettes).where(eq(palettes.userId, userId)).orderBy(desc(palettes.id)).all().map(toApi); +} + +// Saving the same palette twice returns the existing entry instead of a duplicate. +export function savePalette(db: Db, userId: number, colors: string[]): { palette: SavedPalette; created: boolean } { + const key = colors.map((c) => c.slice(1).toLowerCase()).join("-"); + const existing = db + .select() + .from(palettes) + .where(and(eq(palettes.userId, userId), eq(palettes.colors, key))) + .get(); + if (existing) return { palette: toApi(existing), created: false }; + + const count = db + .select({ n: sql`count(*)` }) + .from(palettes) + .where(eq(palettes.userId, userId)) + .get(); + if ((count?.n ?? 0) >= MAX_PALETTES) { + throw new HttpError(409, `You can save up to ${MAX_PALETTES} palettes. Remove one first.`); + } + const row = db.insert(palettes).values({ userId, colors: key }).returning().get(); + return { palette: toApi(row), created: true }; +} + +export function deletePalette(db: Db, userId: number, id: number): void { + const { changes } = db + .delete(palettes) + .where(and(eq(palettes.id, id), eq(palettes.userId, userId))) + .run(); + if (!changes) throw notFound(); +} diff --git a/src/shared/api-types.ts b/src/shared/api-types.ts index 45a1ca9..eac983b 100644 --- a/src/shared/api-types.ts +++ b/src/shared/api-types.ts @@ -52,6 +52,12 @@ export interface PageStats { series: StatsDay[]; } +export interface SavedPalette { + id: number; + colors: string[]; // "#rrggbb" + createdAt: string; +} + export interface ApiToken { id: number; name: string; diff --git a/src/shared/validation.ts b/src/shared/validation.ts index fa7f1b6..c09dfc7 100644 --- a/src/shared/validation.ts +++ b/src/shared/validation.ts @@ -101,6 +101,12 @@ export const statsRangeSchema = z.object({ days: z.coerce.number().pipe(z.union([z.literal(7), z.literal(30), z.literal(90)])).default(7), }); +export const MAX_PALETTES = 50; + +export const createPaletteSchema = z.object({ + colors: z.array(hexColor).min(2).max(10), +}); + export const pinSchema = z.object({ pageId: z.number().int().positive() }); export const createTokenSchema = z.object({ name: z.string().trim().min(1).max(100) }); diff --git a/src/web/screens/detail/AppearanceTab.tsx b/src/web/screens/detail/AppearanceTab.tsx index da21f4a..9464afb 100644 --- a/src/web/screens/detail/AppearanceTab.tsx +++ b/src/web/screens/detail/AppearanceTab.tsx @@ -1,218 +1,15 @@ -import { useRef, useState, type ReactNode } from "react"; -import { Check, ExternalLink, ImageUp, Trash2 } from "lucide-react"; +import { useRef, useState } from "react"; +import { ImageUp, Trash2 } from "lucide-react"; import type { Me, PageDetail } from "../../../shared/api-types.js"; import type { Theme } from "../../../shared/validation.js"; import { api } from "../../api.js"; import { Button } from "../../components/ui/button.js"; -import { ColorInput, Field, Input, Segmented, Switch } from "../../components/ui/form.js"; +import { Field, Input, Switch } from "../../components/ui/form.js"; import { Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js"; import { useAction } from "../../components/ui/toast.js"; -import { cx } from "../../lib/cx.js"; import { stripMarkdown } from "../../lib/markdown.js"; -import { parseCoolorsInput, themeFromPalette, TRENDING_PALETTES, type Variant } from "../../lib/palette.js"; import { PhoneFrame } from "./PhonePreview.js"; - -const PRESETS: { name: string; theme: Theme }[] = [ - { name: "Midnight", theme: { background: "#111827", text: "#e5e7eb", button: "#475569", buttonText: "#ffffff" } }, - { name: "Paper", theme: { background: "#fafaf9", text: "#1c1917", button: "#1c1917", buttonText: "#fafaf9" } }, -]; - -const COLOR_FIELDS: [keyof Theme, string][] = [ - ["background", "Background"], - ["text", "Text"], - ["button", "Buttons"], - ["buttonText", "Button text"], -]; - -const sameTheme = (a: Theme, b: Theme) => COLOR_FIELDS.every(([k]) => a[k].toLowerCase() === b[k].toLowerCase()); - -function OptionCard({ selected, onClick, swatch, label }: { selected: boolean; onClick: () => void; swatch: ReactNode; label: string }) { - return ( - - ); -} - -function PaletteStrip({ colors }: { colors: string[] }) { - return ( -
- {colors.map((c, i) => ( -
- ))} -
- ); -} - -function SectionLabel({ children, actions }: { children: ReactNode; actions?: ReactNode }) { - return ( -
-

{children}

- {actions} -
- ); -} - -// Theme picker: basic presets, coolors.co palettes (trending or pasted link) and custom colors. -function ThemePicker({ theme, onChange }: { theme: Theme; onChange: (theme: Theme) => void }) { - const [variant, setVariant] = useState("dark"); - // The palette the current theme was generated from, so switching dark/light can re-map it. - const [source, setSource] = useState(null); - const [link, setLink] = useState(""); - const [imported, setImported] = useState(null); - const [linkError, setLinkError] = useState(); - - const applyPalette = (colors: string[], v = variant) => { - setSource(colors); - onChange(themeFromPalette(colors, v)); - }; - const changeVariant = (v: Variant) => { - setVariant(v); - if (source) onChange(themeFromPalette(source, v)); - }; - const importLink = () => { - const colors = parseCoolorsInput(link); - if (!colors) { - setLinkError("That doesn't look like a coolors.co palette link."); - return; - } - setLinkError(undefined); - setImported(colors); - applyPalette(colors); - }; - - const isSelected = (colors: string[]) => source === colors && sameTheme(themeFromPalette(colors, variant), theme); - - return ( -
-
- Basic -
- {PRESETS.map((preset) => ( - { - setSource(null); - onChange(preset.theme); - }} - swatch={ -
-
-
-
- } - /> - ))} -
-
- -
- - } - > - Trending on{" "} - - coolors.co - - -
- {TRENDING_PALETTES.map((p) => ( - applyPalette(p.colors)} - swatch={} - /> - ))} -
-
- -
- Import from coolors.co -
{ - e.preventDefault(); - importLink(); - }} - > - { - setLink(e.target.value); - setLinkError(undefined); - }} - /> - -
- {linkError ? ( -

{linkError}

- ) : ( -

- Create or pick a palette on{" "} - - coolors.co - {" "} - and paste its URL here. -

- )} - {imported && ( -
- applyPalette(imported)} swatch={} /> -
- )} -
- -
- Custom colors -
- {COLOR_FIELDS.map(([key, label]) => ( -
- {label} - { - setSource(null); - onChange({ ...theme, [key]: v }); - }} - /> -
- ))} -
-
-
- ); -} +import { sameTheme, ThemePicker } from "./ThemePicker.js"; // Renders the page with unsaved settings so changes are visible while editing. function MockPreview({ title, avatarUrl, theme, page }: { title: string; avatarUrl: string | null; theme: Theme; page: PageDetail }) { diff --git a/src/web/screens/detail/ThemePicker.tsx b/src/web/screens/detail/ThemePicker.tsx new file mode 100644 index 0000000..7883258 --- /dev/null +++ b/src/web/screens/detail/ThemePicker.tsx @@ -0,0 +1,416 @@ +import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; +import { Check, ExternalLink, X } from "lucide-react"; +import type { SavedPalette } from "../../../shared/api-types.js"; +import type { Theme } from "../../../shared/validation.js"; +import { api, errorMessage, useApi } from "../../api.js"; +import { Button } from "../../components/ui/button.js"; +import { useConfirm } from "../../components/ui/dialog.js"; +import { ColorInput, Input, Segmented } from "../../components/ui/form.js"; +import { useToast } from "../../components/ui/toast.js"; +import { cx } from "../../lib/cx.js"; +import { parseCoolorsInput, themeFromPalette, TRENDING_PALETTES, type Variant } from "../../lib/palette.js"; + +export const COLOR_FIELDS: [keyof Theme, string][] = [ + ["background", "Background"], + ["text", "Text"], + ["button", "Buttons"], + ["buttonText", "Button text"], +]; + +export const sameTheme = (a: Theme, b: Theme) => COLOR_FIELDS.every(([k]) => a[k].toLowerCase() === b[k].toLowerCase()); + +const PRESETS: { name: string; theme: Theme }[] = [ + { name: "Midnight", theme: { background: "#111827", text: "#e5e7eb", button: "#475569", buttonText: "#ffffff" } }, + { name: "Paper", theme: { background: "#fafaf9", text: "#1c1917", button: "#1c1917", buttonText: "#fafaf9" } }, +]; + +const paletteKey = (colors: string[]) => colors.join("-").toLowerCase(); + +const cardClass = (selected: boolean) => + cx( + "relative overflow-hidden rounded-xl border transition", + selected ? "border-accent ring-3 ring-accent/20" : "border-border hover:border-border-strong", + ); + +function SectionLabel({ children, actions, hint }: { children: ReactNode; actions?: ReactNode; hint?: ReactNode }) { + return ( +
+
+

{children}

+ {hint &&

{hint}

} +
+ {actions} +
+ ); +} + +function PresetCard({ name, theme, selected, onClick }: { name: string; theme: Theme; selected: boolean; onClick: () => void }) { + return ( + + ); +} + +// A palette: each color opens the role menu, the name row applies the whole palette. +function PaletteCard({ + colors, + label, + selected, + onApply, + onPickColor, + onRemove, +}: { + colors: string[]; + label: string; + selected: boolean; + onApply: () => void; + onPickColor: (color: string, anchor: HTMLElement) => void; + onRemove?: () => void; +}) { + return ( +
+
+ {colors.map((c, i) => ( +
+
+ + {onRemove && ( + + )} +
+
+ ); +} + +// Small menu next to a clicked color: "use as background / text / buttons / button text". +function ColorRoleMenu({ + color, + anchor, + theme, + onPick, + onClose, +}: { + color: string; + anchor: HTMLElement; + theme: Theme; + onPick: (role: keyof Theme) => void; + onClose: () => void; +}) { + const ref = useRef(null); + const [position, setPosition] = useState<{ top: number; left: number } | null>(null); + + // Place below the color (or above when there's no room), kept inside the viewport. + useLayoutEffect(() => { + const menu = ref.current; + if (!menu) return; + const a = anchor.getBoundingClientRect(); + const { width, height } = menu.getBoundingClientRect(); + const below = a.bottom + 6; + const top = below + height > innerHeight - 8 ? Math.max(8, a.top - height - 6) : below; + const left = Math.min(Math.max(8, a.left + a.width / 2 - width / 2), innerWidth - width - 8); + setPosition({ top, left }); + }, [anchor]); + + // Focus the first item once the menu is visible (hidden elements can't take focus). + useEffect(() => { + if (position) ref.current?.querySelector("[role=menuitem]")?.focus({ preventScroll: true }); + }, [position]); + + useEffect(() => { + const outside = (e: PointerEvent) => { + if (!ref.current?.contains(e.target as Node) && e.target !== anchor) onClose(); + }; + const dismiss = () => onClose(); + const escape = (e: globalThis.KeyboardEvent) => { + if (e.key !== "Escape") return; + onClose(); + anchor.focus(); + }; + document.addEventListener("pointerdown", outside); + document.addEventListener("keydown", escape); + window.addEventListener("resize", dismiss); + window.addEventListener("scroll", dismiss, true); + return () => { + document.removeEventListener("pointerdown", outside); + document.removeEventListener("keydown", escape); + window.removeEventListener("resize", dismiss); + window.removeEventListener("scroll", dismiss, true); + }; + }, [anchor, onClose]); + + const onKeyDown = (e: KeyboardEvent) => { + const items = [...(ref.current?.querySelectorAll("[role=menuitem]") ?? [])]; + const index = items.indexOf(document.activeElement as HTMLButtonElement); + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + const next = (index + (e.key === "ArrowDown" ? 1 : -1) + items.length) % items.length; + items[next]?.focus(); + } + }; + + return ( +
+
+ + {color} + use for… +
+ {COLOR_FIELDS.map(([key, label]) => { + const current = theme[key].toLowerCase() === color.toLowerCase(); + return ( + + ); + })} +
+ ); +} + +// Theme picker: basic presets, trending and saved coolors.co palettes, and custom colors. +export function ThemePicker({ theme, onChange }: { theme: Theme; onChange: (theme: Theme) => void }) { + const saved = useApi("/palettes"); + const toast = useToast(); + const confirm = useConfirm(); + const [variant, setVariant] = useState("dark"); + // The palette the current theme was generated from, so switching dark/light can re-map it. + const [source, setSource] = useState(null); + const [link, setLink] = useState(""); + const [linkError, setLinkError] = useState(); + const [importing, setImporting] = useState(false); + const [menu, setMenu] = useState<{ color: string; anchor: HTMLElement } | null>(null); + + const toggleMenu = (color: string, anchor: HTMLElement) => setMenu((m) => (m?.anchor === anchor ? null : { color, anchor })); + + const applyPalette = (colors: string[], v = variant) => { + setSource(colors); + onChange(themeFromPalette(colors, v)); + }; + const changeVariant = (v: Variant) => { + setVariant(v); + if (source) onChange(themeFromPalette(source, v)); + }; + const setColor = (role: keyof Theme, color: string) => { + setSource(null); + onChange({ ...theme, [role]: color }); + }; + + const isSelected = (colors: string[]) => + !!source && paletteKey(source) === paletteKey(colors) && sameTheme(themeFromPalette(colors, variant), theme); + + const importLink = async () => { + const colors = parseCoolorsInput(link); + if (!colors) { + setLinkError("That doesn't look like a coolors.co palette link."); + return; + } + setImporting(true); + try { + await api("POST", "/palettes", { colors }); + await saved.reload(); + applyPalette(colors); + setLink(""); + setLinkError(undefined); + } catch (err) { + setLinkError(errorMessage(err)); + } finally { + setImporting(false); + } + }; + + const removePalette = async (palette: SavedPalette) => { + const ok = await confirm({ title: "Remove this palette?", description: "Pages that already use its colors keep them.", confirmLabel: "Remove", danger: true }); + if (!ok) return; + try { + await api("DELETE", `/palettes/${palette.id}`); + await saved.reload(); + toast("Palette removed"); + } catch (err) { + toast(errorMessage(err), true); + } + }; + + const pickHint = "Click a name to use the whole palette, or a single color to assign it."; + + return ( +
+
+ Basic +
+ {PRESETS.map((preset) => ( + { + setSource(null); + onChange(preset.theme); + }} + /> + ))} +
+
+ +
+ + } + > + Trending on{" "} + + coolors.co + + +
+ {TRENDING_PALETTES.map((p) => ( + applyPalette(p.colors)} + onPickColor={toggleMenu} + /> + ))} +
+
+ +
+ Your palettes +
{ + e.preventDefault(); + void importLink(); + }} + > + { + setLink(e.target.value); + setLinkError(undefined); + }} + /> + +
+ {linkError ? ( +

{linkError}

+ ) : ( +

+ Create or pick a palette on{" "} + + coolors.co + {" "} + and paste its URL here. +

+ )} + {!!saved.data?.length && ( +
+ {saved.data.map((p) => ( + applyPalette(p.colors)} + onPickColor={toggleMenu} + onRemove={() => void removePalette(p)} + /> + ))} +
+ )} +
+ +
+ Custom colors +
+ {COLOR_FIELDS.map(([key, label]) => ( +
+ {label} + setColor(key, v)} /> +
+ ))} +
+
+ + {menu && ( + setMenu(null)} + onPick={(role) => { + setColor(role, menu.color); + setMenu(null); + menu.anchor.focus(); + }} + /> + )} +
+ ); +} diff --git a/test/api.test.ts b/test/api.test.ts index eab6b4e..4132d3f 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -318,6 +318,38 @@ describe("redirects and stats", () => { }); }); +describe("saved palettes", () => { + it("saves palettes per user without duplicates", async () => { + const { user } = setup(); + const alice = user("alice"); + const bob = user("bob"); + const colors = ["#264653", "#2A9D8F", "#e9c46a"]; + + const created = await alice.api("POST", "/palettes", { colors }); + expect(created.status).toBe(201); + const palette = await created.json(); + expect(palette.colors).toEqual(["#264653", "#2a9d8f", "#e9c46a"]); + + const again = await alice.api("POST", "/palettes", { colors: ["#264653", "#2a9d8f", "#E9C46A"] }); + expect(again.status).toBe(200); + expect((await again.json()).id).toBe(palette.id); + + expect(await (await alice.api("GET", "/palettes")).json()).toHaveLength(1); + expect(await (await bob.api("GET", "/palettes")).json()).toEqual([]); + expect((await bob.api("DELETE", `/palettes/${palette.id}`)).status).toBe(404); + expect((await alice.api("DELETE", `/palettes/${palette.id}`)).status).toBe(204); + expect(await (await alice.api("GET", "/palettes")).json()).toEqual([]); + }); + + it("rejects invalid palettes", async () => { + const { user } = setup(); + const alice = user("alice"); + expect((await alice.api("POST", "/palettes", { colors: ["#264653"] })).status).toBe(400); + expect((await alice.api("POST", "/palettes", { colors: ["#264653", "red"] })).status).toBe(400); + expect((await alice.api("POST", "/palettes", { colors: Array(11).fill("#264653") })).status).toBe(400); + }); +}); + describe("api tokens", () => { it("creates, lists and revokes the caller's tokens only", async () => { const { app, user } = setup();