diff --git a/README.md b/README.md index 88eade8..9ff9f82 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,11 @@ A small self-hosted URL shortener and link-page tool for a handful of people, with login through Authentik (OIDC). - **Short links**: `/` for admins, `//` for everyone else. Codes can be custom or random, and both codes and destinations can be edited later. -- **Link pages**: a "link in bio" page with avatar, link buttons, Markdown text blocks and custom colours. Blocks are reordered by drag and drop. +- **Link pages**: a "link in bio" page with avatar, link buttons, Markdown text blocks and colour themes, including trending or pasted [coolors.co](https://coolors.co) palettes. Blocks are reordered by drag and drop. - **QR codes**: choose the error correction level and colours, then download as PNG or SVG. - **Privacy-friendly stats**: clicks per day, daily unique visitors, last visit. No raw IPs are stored, the visitor hash uses a salt that rotates daily, and individual clicks are deleted after 90 days. - **API with personal access tokens**: for scripts and iOS Shortcuts. -- **Mobile-friendly admin UI**, installable as a PWA. Everything runs as a single container with SQLite. +- **Mobile-friendly admin UI** with light and dark mode, installable as a PWA. Everything runs as a single container with SQLite. See [REQUIREMENTS.md](REQUIREMENTS.md) for the full feature list. diff --git a/src/web/app/Shell.tsx b/src/web/app/Shell.tsx index d1c09bc..f453f20 100644 --- a/src/web/app/Shell.tsx +++ b/src/web/app/Shell.tsx @@ -1,6 +1,7 @@ import type { ReactNode } from "react"; import { KeyRound, LayoutDashboard, Link2, LogOut, PanelsTopLeft, ShieldCheck } from "lucide-react"; import type { Me } from "../../shared/api-types.js"; +import { ThemeCycleButton, ThemeSwitch } from "../components/ThemeToggle.js"; import { Button } from "../components/ui/button.js"; import { Link } from "../components/ui/misc.js"; import { cx } from "../lib/cx.js"; @@ -74,6 +75,9 @@ export function Shell({ me, route, onLogout, children }: { me: Me; route: Route; ))} +
+ +
@@ -90,6 +94,7 @@ export function Shell({ me, route, onLogout, children }: { me: Me; route: Route;
+ + ))} +
+ ); +} + +// Compact button that cycles system → light → dark, for the mobile top bar. +export function ThemeCycleButton() { + const current = useThemePreference(); + const index = OPTIONS.findIndex((o) => o.value === current); + const { icon: Icon, label } = OPTIONS[index]!; + const next = OPTIONS[(index + 1) % OPTIONS.length]!; + return ( + + ); +} diff --git a/src/web/index.html b/src/web/index.html index 8f64915..1dfea63 100644 --- a/src/web/index.html +++ b/src/web/index.html @@ -8,6 +8,7 @@ short +
diff --git a/src/web/lib/markdown.ts b/src/web/lib/markdown.ts index efcdd18..b043527 100644 --- a/src/web/lib/markdown.ts +++ b/src/web/lib/markdown.ts @@ -2,7 +2,8 @@ export function stripMarkdown(markdown: string): string { return markdown .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") - .replace(/[*_`#>~]/g, "") + .replace(/^\s*(#{1,6}|>|[-*+]|\d+\.)\s+/gm, "") + .replace(/[*_`~]/g, "") .replace(/\s+/g, " ") .trim(); } diff --git a/src/web/lib/palette.ts b/src/web/lib/palette.ts new file mode 100644 index 0000000..bf29603 --- /dev/null +++ b/src/web/lib/palette.ts @@ -0,0 +1,94 @@ +import type { Theme } from "../../shared/validation.js"; + +// Turning coolors.co palettes (5–10 colors) into a link page theme (4 roles). + +export interface Palette { + name: string; + colors: string[]; // "#rrggbb" +} + +// Snapshot of the top 4 on https://coolors.co/palettes/trending (October 2026). +export const TRENDING_PALETTES: Palette[] = [ + { name: "Fiery Ocean", colors: hexList("780000-c1121f-fdf0d5-003049-669bbc") }, + { name: "Olive Garden Feast", colors: hexList("606c38-283618-fefae0-dda15e-bc6c25") }, + { name: "Pastel Dreamland", colors: hexList("cdb4db-ffc8dd-ffafcc-bde0fe-a2d2ff") }, + { name: "Ocean Sunset", colors: hexList("001219-005f73-0a9396-94d2bd-e9d8a6-ee9b00-ca6702-bb3e03-ae2012-9b2226") }, +]; + +function hexList(dashed: string): string[] { + return dashed.split("-").map((h) => `#${h.toLowerCase()}`); +} + +// Accepts coolors.co links (generator "coolors.co/264653-2a9d8f-…" or "coolors.co/palette/264653-…") +// as well as a bare "264653-2a9d8f-…" list. The colors are part of the URL, so nothing needs to be fetched. +export function parseCoolorsInput(input: string): string[] | null { + const value = input.trim(); + if (!value) return null; + let candidate = value; + if (/^(https?:\/\/)?([a-z0-9-]+\.)*coolors\.co\//i.test(value)) { + try { + const url = new URL(/^https?:\/\//i.test(value) ? value : `https://${value}`); + candidate = url.pathname.split("/").filter(Boolean).pop() ?? ""; + } catch { + return null; + } + } + if (!/^([0-9a-f]{6}-)+[0-9a-f]{6}$/i.test(candidate)) return null; + const colors = hexList(candidate); + return colors.length >= 2 && colors.length <= 10 ? colors : null; +} + +function channels(hex: string): [number, number, number] { + const n = parseInt(hex.slice(1), 16); + return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; +} + +// WCAG relative luminance and contrast ratio. +function luminance(hex: string): number { + const [r, g, b] = channels(hex).map((c) => { + const s = c / 255; + return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; + }) as [number, number, number]; + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +export function contrast(a: string, b: string): number { + const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x) as [number, number]; + return (hi + 0.05) / (lo + 0.05); +} + +function saturation(hex: string): number { + const [r, g, b] = channels(hex).map((c) => c / 255) as [number, number, number]; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const l = (max + min) / 2; + return max === min ? 0 : (max - min) / (1 - Math.abs(2 * l - 1)); +} + +const maxBy = (items: T[], score: (item: T) => number): T => + items.reduce((best, item) => (score(item) > score(best) ? item : best)); + +export type Variant = "dark" | "light"; + +// Background: darkest (or lightest) color. Text: the color that reads best on it. +// Buttons: the most colorful remaining color that stands out from the background. +// White or black is used whenever no palette color is readable enough. +export function themeFromPalette(colors: string[], variant: Variant): Theme { + const byLuminance = [...colors].sort((a, b) => luminance(a) - luminance(b)); + const background = variant === "dark" ? byLuminance[0]! : byLuminance[byLuminance.length - 1]!; + const rest = colors.filter((c) => c !== background); + + const readable = (on: string, options: string[]) => { + const best = maxBy([...options, "#ffffff", "#000000"], (c) => contrast(c, on)); + const fromPalette = options.filter((c) => contrast(c, on) >= 4.5); + return fromPalette.length ? maxBy(fromPalette, (c) => contrast(c, on)) : best; + }; + + const text = readable(background, rest); + const buttonCandidates = rest.filter((c) => c !== text); + const visible = buttonCandidates.filter((c) => contrast(c, background) >= 1.4); + const button = (visible.length ? maxBy(visible, saturation) : buttonCandidates[0]) ?? text; + const buttonText = readable(button, colors.filter((c) => c !== button)); + + return { background, text, button, buttonText }; +} diff --git a/src/web/lib/theme.ts b/src/web/lib/theme.ts new file mode 100644 index 0000000..7296d85 --- /dev/null +++ b/src/web/lib/theme.ts @@ -0,0 +1,50 @@ +import { useSyncExternalStore } from "react"; + +// Light/dark preference of the admin UI. "system" follows the OS setting. +// theme-init.js applies the same logic before the app loads. + +export type ThemePreference = "system" | "light" | "dark"; + +const STORAGE_KEY = "short-theme"; +const media = matchMedia("(prefers-color-scheme: dark)"); +const listeners = new Set<() => void>(); + +function readPreference(): ThemePreference { + const stored = localStorage.getItem(STORAGE_KEY); + return stored === "light" || stored === "dark" ? stored : "system"; +} + +let preference = readPreference(); + +function resolved(): "light" | "dark" { + return preference === "system" ? (media.matches ? "dark" : "light") : preference; +} + +function apply() { + document.documentElement.dataset.theme = resolved(); + listeners.forEach((l) => l()); +} + +media.addEventListener("change", () => { + if (preference === "system") apply(); +}); + +export function setThemePreference(next: ThemePreference) { + preference = next; + if (next === "system") localStorage.removeItem(STORAGE_KEY); + else localStorage.setItem(STORAGE_KEY, next); + apply(); +} + +const subscribe = (listener: () => void) => { + listeners.add(listener); + return () => listeners.delete(listener); +}; + +export function useThemePreference(): ThemePreference { + return useSyncExternalStore(subscribe, () => preference); +} + +export function useResolvedTheme(): "light" | "dark" { + return useSyncExternalStore(subscribe, resolved); +} diff --git a/src/web/public/theme-init.js b/src/web/public/theme-init.js new file mode 100644 index 0000000..37abeac --- /dev/null +++ b/src/web/public/theme-init.js @@ -0,0 +1,8 @@ +// Applies the saved light/dark preference before the first paint to avoid a flash. +(function () { + try { + var pref = localStorage.getItem("short-theme") || "system"; + var dark = pref === "dark" || (pref === "system" && matchMedia("(prefers-color-scheme: dark)").matches); + document.documentElement.dataset.theme = dark ? "dark" : "light"; + } catch (e) {} +})(); diff --git a/src/web/screens/OverviewScreen.tsx b/src/web/screens/OverviewScreen.tsx index 06f25ab..800e956 100644 --- a/src/web/screens/OverviewScreen.tsx +++ b/src/web/screens/OverviewScreen.tsx @@ -51,7 +51,7 @@ export function OverviewScreen({ me }: { me: Me }) { const links = all.filter((p) => p.kind === "redirect"); const linkPages = all.filter((p) => p.kind === "linkpage"); const clicks = all.reduce((sum, p) => sum + p.totalClicks, 0); - const scope = me.isAdmin ? "across all namespaces" : `in /${me.username}/`; + const scope = me.isAdmin ? "all users" : `in /${me.username}/`; return ( <> diff --git a/src/web/screens/detail/AnalyticsTab.tsx b/src/web/screens/detail/AnalyticsTab.tsx index 5a25f52..08d8ec5 100644 --- a/src/web/screens/detail/AnalyticsTab.tsx +++ b/src/web/screens/detail/AnalyticsTab.tsx @@ -10,26 +10,16 @@ import { Segmented } from "../../components/ui/form.js"; import { Stat } from "../../components/ui/misc.js"; import { Card, CardHeader, Skeleton } from "../../components/ui/surface.js"; import { useAction } from "../../components/ui/toast.js"; +import { useResolvedTheme } from "../../lib/theme.js"; type Range = 7 | 30 | 90; const cssVar = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim(); -// Re-renders when the system switches between light and dark, so the chart picks up the new colors. -function useColorScheme() { - const [dark, setDark] = useState(() => matchMedia("(prefers-color-scheme: dark)").matches); - useEffect(() => { - const mq = matchMedia("(prefers-color-scheme: dark)"); - const update = () => setDark(mq.matches); - mq.addEventListener("change", update); - return () => mq.removeEventListener("change", update); - }, []); - return dark; -} - function Chart({ series }: { series: StatsDay[] }) { const container = useRef(null); - const dark = useColorScheme(); + // Redraw when light/dark mode changes so the chart picks up the new colors. + const mode = useResolvedTheme(); useEffect(() => { const el = container.current; @@ -70,7 +60,7 @@ function Chart({ series }: { series: StatsDay[] }) { resize.disconnect(); plot.destroy(); }; - }, [series, dark]); + }, [series, mode]); return
; } diff --git a/src/web/screens/detail/AppearanceTab.tsx b/src/web/screens/detail/AppearanceTab.tsx index a6d18c7..ddded5c 100644 --- a/src/web/screens/detail/AppearanceTab.tsx +++ b/src/web/screens/detail/AppearanceTab.tsx @@ -1,23 +1,20 @@ -import { useRef, useState } from "react"; -import { Check, ImageUp, Trash2 } from "lucide-react"; +import { useRef, useState, type ReactNode } from "react"; +import { Check, ExternalLink, ImageUp, Trash2 } from "lucide-react"; import type { 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 } from "../../components/ui/form.js"; +import { ColorInput, Field, Input, Segmented } 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" } }, - { name: "Violet", theme: { background: "#2e1065", text: "#ede9fe", button: "#7c3aed", buttonText: "#ffffff" } }, - { name: "Forest", theme: { background: "#052e16", text: "#dcfce7", button: "#15803d", buttonText: "#ffffff" } }, - { name: "Sunset", theme: { background: "#431407", text: "#ffedd5", button: "#ea580c", buttonText: "#ffffff" } }, - { name: "Ocean", theme: { background: "#082f49", text: "#e0f2fe", button: "#0284c7", buttonText: "#ffffff" } }, ]; const COLOR_FIELDS: [keyof Theme, string][] = [ @@ -29,6 +26,194 @@ const COLOR_FIELDS: [keyof Theme, string][] = [ 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 }); + }} + /> +
+ ))} +
+
+
+ ); +} + // 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 }) { return ( @@ -125,41 +310,9 @@ export function AppearanceTab({ page, onChange }: { page: PageDetail; onChange: - - -
- {PRESETS.map((preset) => { - const selected = sameTheme(preset.theme, theme); - return ( - - ); - })} -
-
- {COLOR_FIELDS.map(([key, label]) => ( -
- {label} - setTheme({ ...theme, [key]: v })} /> -
- ))} -
+ + + {dirty && Unsaved changes} diff --git a/src/web/styles.css b/src/web/styles.css index 110aa1c..ff93256 100644 --- a/src/web/styles.css +++ b/src/web/styles.css @@ -1,5 +1,8 @@ @import "tailwindcss"; +/* Dark mode is controlled by data-theme on (see theme-init.js), not only the system setting. */ +@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *)); + /* Semantic color tokens. Components only use these, so light and dark mode stay in sync. */ @theme { --color-canvas: #f6f6f8; @@ -40,28 +43,26 @@ } } -@media (prefers-color-scheme: dark) { - :root { - --color-canvas: #0c0c10; - --color-surface: #141419; - --color-surface-2: #1d1d24; - --color-border: #26262e; - --color-border-strong: #34343e; - --color-fg: #ececf1; - --color-muted: #9898a6; - --color-accent: #8b5cf6; - --color-accent-hover: #7c3aed; - --color-accent-soft: #241a3d; - --color-accent-soft-fg: #c4b5fd; - --color-danger: #ef4444; - --color-danger-soft: #2c1517; - --color-danger-soft-fg: #fca5a5; - --color-warning-soft: #2b2112; - --color-warning-soft-fg: #fcd34d; - --color-chart-1: #a78bfa; - --color-chart-2: #38bdf8; - color-scheme: dark; - } +:root[data-theme="dark"] { + --color-canvas: #0c0c10; + --color-surface: #141419; + --color-surface-2: #1d1d24; + --color-border: #26262e; + --color-border-strong: #34343e; + --color-fg: #ececf1; + --color-muted: #9898a6; + --color-accent: #8b5cf6; + --color-accent-hover: #7c3aed; + --color-accent-soft: #241a3d; + --color-accent-soft-fg: #c4b5fd; + --color-danger: #ef4444; + --color-danger-soft: #2c1517; + --color-danger-soft-fg: #fca5a5; + --color-warning-soft: #2b2112; + --color-warning-soft-fg: #fcd34d; + --color-chart-1: #a78bfa; + --color-chart-2: #38bdf8; + color-scheme: dark; } @layer base { diff --git a/test/palette.test.ts b/test/palette.test.ts new file mode 100644 index 0000000..0c31403 --- /dev/null +++ b/test/palette.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import { contrast, parseCoolorsInput, themeFromPalette, TRENDING_PALETTES } from "../src/web/lib/palette.js"; + +describe("coolors.co palettes", () => { + it("parses palette and generator links as well as bare color lists", () => { + const expected = ["#264653", "#2a9d8f", "#e9c46a", "#f4a261", "#e76f51"]; + expect(parseCoolorsInput("https://coolors.co/palette/264653-2a9d8f-e9c46a-f4a261-e76f51")).toEqual(expected); + expect(parseCoolorsInput("https://coolors.co/264653-2a9d8f-e9c46a-f4a261-e76f51")).toEqual(expected); + expect(parseCoolorsInput("coolors.co/palette/264653-2A9D8F-e9c46a-f4a261-e76f51?ref=x")).toEqual(expected); + expect(parseCoolorsInput(" 264653-2a9d8f-e9c46a-f4a261-e76f51 ")).toEqual(expected); + }); + + it("rejects anything else", () => { + expect(parseCoolorsInput("")).toBeNull(); + expect(parseCoolorsInput("https://example.com/264653-2a9d8f")).toBeNull(); + expect(parseCoolorsInput("https://coolors.co/palettes/trending")).toBeNull(); + expect(parseCoolorsInput("264653")).toBeNull(); + expect(parseCoolorsInput("zzzzzz-2a9d8f")).toBeNull(); + }); + + it("maps every trending palette to a readable theme in both variants", () => { + for (const { colors } of TRENDING_PALETTES) { + for (const variant of ["dark", "light"] as const) { + const theme = themeFromPalette(colors, variant); + expect(contrast(theme.text, theme.background)).toBeGreaterThanOrEqual(4.5); + expect(contrast(theme.buttonText, theme.button)).toBeGreaterThanOrEqual(4.5); + expect(theme.button).not.toBe(theme.background); + } + } + }); + + it("uses the darkest color as dark background and the lightest as light background", () => { + const colors = ["#264653", "#2a9d8f", "#e9c46a", "#f4a261", "#e76f51"]; + expect(themeFromPalette(colors, "dark").background).toBe("#264653"); + expect(themeFromPalette(colors, "light").background).toBe("#e9c46a"); + }); +});