mirror of
https://github.com/traberph/short.git
synced 2026-11-22 22:55:12 +00:00
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 <noreply@anthropic.com>
This commit is contained in:
@@ -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"}}`).
|
||||
|
||||
@@ -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`);
|
||||
@@ -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": {}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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<number>`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();
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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) });
|
||||
|
||||
@@ -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 (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-pressed={selected}
|
||||
className={cx(
|
||||
"relative cursor-pointer overflow-hidden rounded-xl border text-left transition",
|
||||
selected ? "border-accent ring-3 ring-accent/20" : "border-border hover:border-border-strong",
|
||||
)}
|
||||
>
|
||||
{swatch}
|
||||
<div className="flex items-center justify-between gap-2 px-3 py-2 text-sm font-medium">
|
||||
<span className="truncate">{label}</span>
|
||||
{selected && <Check className="size-4 shrink-0 text-accent" />}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function PaletteStrip({ colors }: { colors: string[] }) {
|
||||
return (
|
||||
<div className="flex h-14">
|
||||
{colors.map((c, i) => (
|
||||
<div key={i} className="flex-1" style={{ background: c }} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SectionLabel({ children, actions }: { children: ReactNode; actions?: ReactNode }) {
|
||||
return (
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h3 className="text-sm font-medium">{children}</h3>
|
||||
{actions}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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<Variant>("dark");
|
||||
// The palette the current theme was generated from, so switching dark/light can re-map it.
|
||||
const [source, setSource] = useState<string[] | null>(null);
|
||||
const [link, setLink] = useState("");
|
||||
const [imported, setImported] = useState<string[] | null>(null);
|
||||
const [linkError, setLinkError] = useState<string>();
|
||||
|
||||
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 (
|
||||
<div className="flex flex-col gap-7">
|
||||
<div>
|
||||
<SectionLabel>Basic</SectionLabel>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{PRESETS.map((preset) => (
|
||||
<OptionCard
|
||||
key={preset.name}
|
||||
label={preset.name}
|
||||
selected={sameTheme(preset.theme, theme)}
|
||||
onClick={() => {
|
||||
setSource(null);
|
||||
onChange(preset.theme);
|
||||
}}
|
||||
swatch={
|
||||
<div className="flex h-14 flex-col items-center justify-center gap-1.5 px-6" style={{ background: preset.theme.background }}>
|
||||
<div className="h-2.5 w-full rounded-full" style={{ background: preset.theme.button }} />
|
||||
<div className="h-2.5 w-full rounded-full" style={{ background: preset.theme.button }} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<SectionLabel
|
||||
actions={
|
||||
<Segmented
|
||||
ariaLabel="Background for palettes"
|
||||
value={variant}
|
||||
onChange={changeVariant}
|
||||
options={[
|
||||
{ value: "dark", label: "Dark background" },
|
||||
{ value: "light", label: "Light background" },
|
||||
]}
|
||||
/>
|
||||
}
|
||||
>
|
||||
Trending on{" "}
|
||||
<a href="https://coolors.co/palettes/trending" target="_blank" rel="noreferrer" className="text-accent hover:underline">
|
||||
coolors.co
|
||||
</a>
|
||||
</SectionLabel>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{TRENDING_PALETTES.map((p) => (
|
||||
<OptionCard
|
||||
key={p.name}
|
||||
label={p.name}
|
||||
selected={isSelected(p.colors)}
|
||||
onClick={() => applyPalette(p.colors)}
|
||||
swatch={<PaletteStrip colors={p.colors} />}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<SectionLabel>Import from coolors.co</SectionLabel>
|
||||
<form
|
||||
className="flex gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
importLink();
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
aria-label="coolors.co link"
|
||||
placeholder="https://coolors.co/palette/264653-2a9d8f-e9c46a-f4a261-e76f51"
|
||||
value={link}
|
||||
onChange={(e) => {
|
||||
setLink(e.target.value);
|
||||
setLinkError(undefined);
|
||||
}}
|
||||
/>
|
||||
<Button type="submit" variant="secondary" disabled={!link.trim()}>
|
||||
Apply
|
||||
</Button>
|
||||
</form>
|
||||
{linkError ? (
|
||||
<p className="mt-1.5 text-xs text-danger">{linkError}</p>
|
||||
) : (
|
||||
<p className="mt-1.5 text-xs text-muted">
|
||||
Create or pick a palette on{" "}
|
||||
<a href="https://coolors.co/generate" target="_blank" rel="noreferrer" className="inline-flex items-center gap-0.5 underline">
|
||||
coolors.co <ExternalLink className="size-3" />
|
||||
</a>{" "}
|
||||
and paste its URL here.
|
||||
</p>
|
||||
)}
|
||||
{imported && (
|
||||
<div className="mt-3 grid grid-cols-2 gap-3">
|
||||
<OptionCard label="Imported palette" selected={isSelected(imported)} onClick={() => applyPalette(imported)} swatch={<PaletteStrip colors={imported} />} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<SectionLabel>Custom colors</SectionLabel>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
{COLOR_FIELDS.map(([key, label]) => (
|
||||
<div key={key} className="flex flex-col gap-1.5">
|
||||
<span className="text-xs text-muted">{label}</span>
|
||||
<ColorInput
|
||||
label={label}
|
||||
value={theme[key]}
|
||||
onChange={(v) => {
|
||||
setSource(null);
|
||||
onChange({ ...theme, [key]: v });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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 }) {
|
||||
|
||||
@@ -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 (
|
||||
<div className="mb-3 flex flex-wrap items-end justify-between gap-2">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium">{children}</h3>
|
||||
{hint && <p className="mt-0.5 text-xs text-muted">{hint}</p>}
|
||||
</div>
|
||||
{actions}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PresetCard({ name, theme, selected, onClick }: { name: string; theme: Theme; selected: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button type="button" onClick={onClick} aria-pressed={selected} className={cx(cardClass(selected), "cursor-pointer text-left")}>
|
||||
<div className="flex h-14 flex-col items-center justify-center gap-1.5 px-6" style={{ background: theme.background }}>
|
||||
<div className="h-2.5 w-full rounded-full" style={{ background: theme.button }} />
|
||||
<div className="h-2.5 w-full rounded-full" style={{ background: theme.button }} />
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2 px-3 py-2 text-sm font-medium">
|
||||
<span className="truncate">{name}</span>
|
||||
{selected && <Check className="size-4 shrink-0 text-accent" />}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div className={cardClass(selected)}>
|
||||
<div className="flex h-14">
|
||||
{colors.map((c, i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
aria-haspopup="menu"
|
||||
aria-label={`${c.toUpperCase()}: use for one color`}
|
||||
title={c.toUpperCase()}
|
||||
onClick={(e) => onPickColor(c, e.currentTarget)}
|
||||
className="flex-1 cursor-pointer transition-[flex-grow] duration-150 hover:grow-[1.8] focus-visible:grow-[1.8] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-white"
|
||||
style={{ background: c }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onApply}
|
||||
aria-pressed={selected}
|
||||
className="flex min-w-0 flex-1 cursor-pointer items-center justify-between gap-2 px-3 py-2 text-left text-sm font-medium transition-colors hover:bg-surface-2/60"
|
||||
>
|
||||
<span className="truncate">{label}</span>
|
||||
{selected && <Check className="size-4 shrink-0 text-accent" />}
|
||||
</button>
|
||||
{onRemove && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
aria-label={`Remove ${label}`}
|
||||
title="Remove palette"
|
||||
className="cursor-pointer self-stretch px-2.5 text-muted transition-colors hover:bg-surface-2/60 hover:text-danger"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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<HTMLDivElement>(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<HTMLButtonElement>("[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<HTMLButtonElement>("[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 (
|
||||
<div
|
||||
ref={ref}
|
||||
role="menu"
|
||||
aria-label={`Use ${color.toUpperCase()} for`}
|
||||
onKeyDown={onKeyDown}
|
||||
className="fixed z-50 w-56 animate-pop-in rounded-xl border border-border bg-surface p-1 shadow-xl"
|
||||
style={position ?? { visibility: "hidden", top: 0, left: 0 }}
|
||||
>
|
||||
<div className="flex items-center gap-2 px-2.5 pt-1.5 pb-2 text-xs text-muted">
|
||||
<span className="size-4 rounded border border-border" style={{ background: color }} />
|
||||
<span className="font-mono uppercase">{color}</span>
|
||||
<span>use for…</span>
|
||||
</div>
|
||||
{COLOR_FIELDS.map(([key, label]) => {
|
||||
const current = theme[key].toLowerCase() === color.toLowerCase();
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
onClick={() => onPick(key)}
|
||||
className="flex w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-sm outline-none hover:bg-surface-2 focus-visible:bg-surface-2"
|
||||
>
|
||||
<span className="size-4 rounded border border-border" style={{ background: theme[key] }} title={`Current: ${theme[key]}`} />
|
||||
<span className="flex-1">{label}</span>
|
||||
{current && <Check className="size-4 text-accent" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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<SavedPalette[]>("/palettes");
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const [variant, setVariant] = useState<Variant>("dark");
|
||||
// The palette the current theme was generated from, so switching dark/light can re-map it.
|
||||
const [source, setSource] = useState<string[] | null>(null);
|
||||
const [link, setLink] = useState("");
|
||||
const [linkError, setLinkError] = useState<string>();
|
||||
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<SavedPalette>("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 (
|
||||
<div className="flex flex-col gap-7">
|
||||
<div>
|
||||
<SectionLabel>Basic</SectionLabel>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{PRESETS.map((preset) => (
|
||||
<PresetCard
|
||||
key={preset.name}
|
||||
name={preset.name}
|
||||
theme={preset.theme}
|
||||
selected={sameTheme(preset.theme, theme)}
|
||||
onClick={() => {
|
||||
setSource(null);
|
||||
onChange(preset.theme);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<SectionLabel
|
||||
hint={pickHint}
|
||||
actions={
|
||||
<Segmented
|
||||
ariaLabel="Background for palettes"
|
||||
value={variant}
|
||||
onChange={changeVariant}
|
||||
options={[
|
||||
{ value: "dark", label: "Dark background" },
|
||||
{ value: "light", label: "Light background" },
|
||||
]}
|
||||
/>
|
||||
}
|
||||
>
|
||||
Trending on{" "}
|
||||
<a href="https://coolors.co/palettes/trending" target="_blank" rel="noreferrer" className="text-accent hover:underline">
|
||||
coolors.co
|
||||
</a>
|
||||
</SectionLabel>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{TRENDING_PALETTES.map((p) => (
|
||||
<PaletteCard
|
||||
key={p.name}
|
||||
label={p.name}
|
||||
colors={p.colors}
|
||||
selected={isSelected(p.colors)}
|
||||
onApply={() => applyPalette(p.colors)}
|
||||
onPickColor={toggleMenu}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<SectionLabel hint="Paste a coolors.co palette link to save it to your palettes.">Your palettes</SectionLabel>
|
||||
<form
|
||||
className="flex gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void importLink();
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
aria-label="coolors.co link"
|
||||
placeholder="https://coolors.co/palette/264653-2a9d8f-e9c46a-f4a261-e76f51"
|
||||
value={link}
|
||||
onChange={(e) => {
|
||||
setLink(e.target.value);
|
||||
setLinkError(undefined);
|
||||
}}
|
||||
/>
|
||||
<Button type="submit" variant="secondary" loading={importing} disabled={!link.trim()}>
|
||||
Import
|
||||
</Button>
|
||||
</form>
|
||||
{linkError ? (
|
||||
<p className="mt-1.5 text-xs text-danger">{linkError}</p>
|
||||
) : (
|
||||
<p className="mt-1.5 text-xs text-muted">
|
||||
Create or pick a palette on{" "}
|
||||
<a href="https://coolors.co/generate" target="_blank" rel="noreferrer" className="inline-flex items-center gap-0.5 underline">
|
||||
coolors.co <ExternalLink className="size-3" />
|
||||
</a>{" "}
|
||||
and paste its URL here.
|
||||
</p>
|
||||
)}
|
||||
{!!saved.data?.length && (
|
||||
<div className="mt-3 grid grid-cols-2 gap-3">
|
||||
{saved.data.map((p) => (
|
||||
<PaletteCard
|
||||
key={p.id}
|
||||
label={`Imported ${new Date(p.createdAt).toLocaleDateString(undefined, { month: "short", day: "numeric" })}`}
|
||||
colors={p.colors}
|
||||
selected={isSelected(p.colors)}
|
||||
onApply={() => applyPalette(p.colors)}
|
||||
onPickColor={toggleMenu}
|
||||
onRemove={() => void removePalette(p)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<SectionLabel>Custom colors</SectionLabel>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
{COLOR_FIELDS.map(([key, label]) => (
|
||||
<div key={key} className="flex flex-col gap-1.5">
|
||||
<span className="text-xs text-muted">{label}</span>
|
||||
<ColorInput label={label} value={theme[key]} onChange={(v) => setColor(key, v)} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{menu && (
|
||||
<ColorRoleMenu
|
||||
color={menu.color}
|
||||
anchor={menu.anchor}
|
||||
theme={theme}
|
||||
onClose={() => setMenu(null)}
|
||||
onPick={(role) => {
|
||||
setColor(role, menu.color);
|
||||
setMenu(null);
|
||||
menu.anchor.focus();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user