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:
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user