Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
chore: theme explorer paste copy agent prompt (#2779)
Maximilian Kaskeea4879ab94a0
diff --git a/apps/status-page/src/app/(public)/client.tsx b/apps/status-page/src/app/(public)/client.tsxindex 6e80a01e9..1676aa5f0 100644--- a/apps/status-page/src/app/(public)/client.tsx+++ b/apps/status-page/src/app/(public)/client.tsx@@ -1,5 +1,6 @@"use client";+import { Sidebar as SidebarIcon } from "@openstatus/icons";import { THEMES, THEME_KEYS } from "@openstatus/theme-store";import { StatusBanner } from "@openstatus/ui/components/blocks/status-banner";import {@@ -37,10 +38,18 @@ import {} from "../../components/content/section";import { recomputeStyles } from "../../components/status-page/floating-button";import { StatusComponentStatic } from "../../components/status-page/static/status-component-static";+import { ThemePromptButton } from "../../components/themes/theme-agent-actions";+import { useThemeBuilder } from "../../components/themes/theme-builder-provider";import { ThemePalettePicker } from "../../components/themes/theme-palette-picker";+import { ThemePasteDialog } from "../../components/themes/theme-paste-dialog";import { ThemeSelect } from "../../components/themes/theme-select";import { monitors } from "../../data/monitors";import { defaultLocale } from "../../i18n/config";+import { clearThemeDraft, saveThemeDraft } from "../../lib/theme-draft";+import {+ THEME_SKILL_INSTALL_COMMAND,+ THEME_SKILL_URL,+} from "../../lib/theme-prompt";import { useTRPC } from "../../lib/trpc/client";import { searchParamsParsers } from "./search-params";@@ -60,6 +69,7 @@ export function Client() {const [{ q, t }, setSearchParams] = useQueryStates(searchParamsParsers);const theme = t ? THEMES[t as keyof typeof THEMES] : undefined;const { toggleSidebar } = useSidebar();+ const builder = useThemeBuilder();useEffect(() => {setIsMounted(true);@@ -218,42 +228,63 @@ export function Client() {</SectionHeader><div className="prose dark:prose-invert prose-sm max-w-none"><p>- You can contribute your own theme by creating a new file in the{" "}- <code>@openstatus/theme-store</code> package. You'll only need- to override css variables. If you are familiar with shadcn, you'll- know the trick (it also allows you to override `--radius`). Make- sure your object is satisfying the <code>Theme</code> interface. We- provide a theme builder to help you with the process.- </p>- <Button onClick={toggleSidebar}>Toggle Theme Builder</Button>- <p>- Go to the{" "}- <Link href="https://github.com/openstatusHQ/openstatus/tree/main/packages/theme-store">- GitHub directory- </Link>{" "}- to see the existing themes and create a new one by forking and- creating a pull request.- </p>- <p>- Once you're done, you can test it by adding the following snippet to- your status page:+ A theme is a set of CSS variable overrides for light and dark mode+ in the <code>@openstatus/theme-store</code> package. If you are+ familiar with shadcn, you know the trick (it also lets you override{" "}+ <code>--radius</code>). Three ways to get one:</p>- <pre>- <code>sessionStorage.setItem("community-theme", "true");</code>- </pre>+ <ul>+ <li>+ <strong>Build it</strong> in the theme builder and copy it as a+ TypeScript file, JSON or CSS.+ </li>+ <li>+ <strong>Let your agent design it.</strong> Copy the prompt from+ the builder, or install the{" "}+ <Link href={THEME_SKILL_URL}>openstatus-theme skill</Link> with{" "}+ <code>{THEME_SKILL_INSTALL_COMMAND}</code>. Paste the reply into+ the builder to preview it.+ </li>+ <li>+ <strong>Write it by hand</strong> following the existing themes in+ the{" "}+ <Link href="https://github.com/openstatusHQ/openstatus/tree/main/packages/theme-store">+ GitHub directory+ </Link>+ .+ </li>+ </ul>+ <div className="flex flex-wrap gap-2">+ <ThemePromptButton variant="default" />+ <ThemePasteDialog variant="outline" />+ <Button variant="outline" onClick={toggleSidebar}>+ <SidebarIcon className="size-4" />+ Toggle Sidebar+ </Button>+ </div><p>- Or use the following button to test it on the `status` page slug:+ Preview the theme from the builder on a full status page (the{" "}+ <code>status</code> slug). Unchanged themes open the community theme+ switcher instead:</p><ButtononClick={() => {// NOTE: we use it to display the 'floating-theme' componentsessionStorage.setItem("community-theme", "true");+ if (builder.isModified) saveThemeDraft(builder.theme);+ else clearThemeDraft();window.location.href = `/status/${defaultLocale}`;}}>Test it</Button>- {/* TODO: OR go to the status-page config and click on the View and Configure button */}+ <p>+ Once you are happy, copy the TypeScript file into{" "}+ <code>packages/theme-store/src</code>, register it in{" "}+ <code>index.ts</code> and open a pull request. Or paste the CSS+ variables into your own status page's custom theme in the+ dashboard, no pull request needed.+ </p></div></Section><Separator />diff --git a/apps/status-page/src/app/(public)/layout.tsx b/apps/status-page/src/app/(public)/layout.tsxindex 6949cc483..771ac999b 100644--- a/apps/status-page/src/app/(public)/layout.tsx+++ b/apps/status-page/src/app/(public)/layout.tsx@@ -12,6 +12,7 @@ import { notFound } from "next/navigation";import { Suspense } from "react";import { Link } from "../../components/common/link";+import { ThemeBuilderProvider } from "../../components/themes/theme-builder-provider";import { ThemeProvider } from "../../components/themes/theme-provider";import {SidebarTrigger,@@ -71,18 +72,20 @@ export default async function Layout({} as React.CSSProperties}>- <SidebarInset className="relative">- <SidebarTrigger className="absolute top-2 right-2" />- <main className="mx-auto">{children}</main>- <footer className="text-muted-foreground flex items-center justify-center gap-4 p-4 text-center font-mono text-sm">- <p>- powered by{" "}- <Link href="https://openstatus.dev">openstatus</Link>- </p>- </footer>- </SidebarInset><Suspense>- <ThemeSidebar />+ <ThemeBuilderProvider>+ <SidebarInset className="relative">+ <SidebarTrigger className="absolute top-2 right-2" />+ <main className="mx-auto">{children}</main>+ <footer className="text-muted-foreground flex items-center justify-center gap-4 p-4 text-center font-mono text-sm">+ <p>+ powered by{" "}+ <Link href="https://openstatus.dev">openstatus</Link>+ </p>+ </footer>+ </SidebarInset>+ <ThemeSidebar />+ </ThemeBuilderProvider></Suspense></SidebarProvider><Toaster richColors expand />diff --git a/apps/status-page/src/components/status-page/floating-button.tsx b/apps/status-page/src/components/status-page/floating-button.tsxindex d69ffd339..4361f4b9f 100644--- a/apps/status-page/src/components/status-page/floating-button.tsx+++ b/apps/status-page/src/components/status-page/floating-button.tsx@@ -5,6 +5,7 @@ import {type CustomTheme,THEMES,THEME_KEYS,+ type Theme,type ThemeDefinition,generateThemeStyles,hasCustomTheme,@@ -38,6 +39,7 @@ import { parseAsString, useQueryState } from "nuqs";import type React from "react";import { createContext, useContext, useEffect, useState } from "react";+import { clearThemeDraft } from "../../lib/theme-draft";import { ThemeSelect } from "../themes/theme-select";export const IS_DEV = process.env.NODE_ENV === "development";@@ -68,6 +70,9 @@ interface StatusPageContextType {setNumberOfDays: (numberOfDays: NumberOfDays) => void;communityTheme: CommunityTheme;setCommunityTheme: (communityTheme: CommunityTheme) => void;+ /** Unregistered theme previewed from the explorer's builder. */+ draftTheme: Theme | null;+ setDraftTheme: (draftTheme: Theme | null) => void;}const StatusPageContext = createContext<StatusPageContextType | null>(null);@@ -102,9 +107,17 @@ export function StatusPageProvider({const [showUptime, setShowUptime] = useState<boolean>(defaultShowUptime);const [numberOfDays, setNumberOfDays] =useState<NumberOfDays>(defaultNumberOfDays);- const [communityTheme, setCommunityTheme] = useState<CommunityTheme>(+ const [communityTheme, setCommunityThemeState] = useState<CommunityTheme>(defaultCommunityTheme,);+ const [draftTheme, setDraftTheme] = useState<Theme | null>(null);++ // a draft shadows the community theme, so picking one discards the draft+ function setCommunityTheme(theme: CommunityTheme) {+ clearThemeDraft();+ setDraftTheme(null);+ setCommunityThemeState(theme);+ }const [isMounted, setIsMounted] = useState(false);useEffect(() => {@@ -112,17 +125,22 @@ export function StatusPageProvider({}, []);useEffect(() => {- if (isMounted) {- // keep the page's custom vars applied — without them this rewrite- // clobbers the server-rendered overrides on hydration- recomputeStyles(- communityTheme,- hasCustomTheme(customTheme)- ? sanitizeCustomTheme(customTheme)- : undefined,- );+ if (!isMounted) return;+ if (draftTheme) {+ // an unregistered id falls back to the default theme as base, which is+ // what the draft would render over once registered+ recomputeStyles(draftTheme.id, draftTheme);+ return;}- }, [communityTheme, isMounted, customTheme]);+ // keep the page's custom vars applied — without them this rewrite+ // clobbers the server-rendered overrides on hydration+ recomputeStyles(+ communityTheme,+ hasCustomTheme(customTheme)+ ? sanitizeCustomTheme(customTheme)+ : undefined,+ );+ }, [communityTheme, isMounted, customTheme, draftTheme]);return (<StatusPageContext.Provider@@ -137,6 +155,8 @@ export function StatusPageProvider({setNumberOfDays,communityTheme,setCommunityTheme,+ draftTheme,+ setDraftTheme,}}>{children}@@ -386,8 +406,9 @@ export function FloatingButton({);}+/** Unregistered ids (builder drafts) fall back to the default theme as base. */export function recomputeStyles(- newTheme: CommunityTheme,+ newTheme: string,overrides?: Partial<ThemeDefinition>,) {try {diff --git a/apps/status-page/src/components/status-page/floating-theme.tsx b/apps/status-page/src/components/status-page/floating-theme.tsxindex f7f54df7f..2ccf12cdd 100644--- a/apps/status-page/src/components/status-page/floating-theme.tsx+++ b/apps/status-page/src/components/status-page/floating-theme.tsx@@ -1,6 +1,6 @@"use client";-import { Check, Expand, Theme } from "@openstatus/icons";+import { Check, Close, Expand, Theme } from "@openstatus/icons";import { THEMES, THEME_KEYS } from "@openstatus/theme-store";import { Button } from "@openstatus/ui/components/ui/button";import {@@ -21,6 +21,7 @@ import { cn } from "@openstatus/ui/lib/utils";import { useEffect } from "react";import { useState } from "react";+import { clearThemeDraft, readThemeDraft } from "../../lib/theme-draft";import { ThemeSelect } from "../themes/theme-select";import { useStatusPage } from "./floating-button";@@ -28,7 +29,8 @@ export const COMMUNITY_THEME = THEME_KEYS;export type CommunityTheme = (typeof COMMUNITY_THEME)[number];export function FloatingTheme({ className }: { className?: string }) {- const { communityTheme, setCommunityTheme } = useStatusPage();+ const { communityTheme, setCommunityTheme, draftTheme, setDraftTheme } =+ useStatusPage();const [display, setDisplay] = useState(false);const [open, setOpen] = useState(false);@@ -44,8 +46,14 @@ export function FloatingTheme({ className }: { className?: string }) {) {setDisplay(true);setOpen(true);+ setDraftTheme(readThemeDraft());}- }, []);+ }, [setDraftTheme]);++ function discardDraft() {+ clearThemeDraft();+ setDraftTheme(null);+ }if (!display) return null;@@ -70,61 +78,88 @@ export function FloatingTheme({ className }: { className?: string }) {<Label htmlFor="theme">Theme Mode</Label><ThemeSelect id="theme" className="w-full" /></div>- <div className="space-y-2">- <Label htmlFor="community-theme">Community Theme</Label>- <Popover>- <PopoverTrigger asChild>+ {draftTheme ? (+ <div className="space-y-2">+ <Label>Draft</Label>+ <div className="border-border flex items-center justify-between gap-2 rounded-md border px-3 py-2">+ <div className="min-w-0">+ <div className="truncate text-sm">{draftTheme.name}</div>+ <div className="text-muted-foreground truncate font-mono text-xs">+ {draftTheme.id}+ </div>+ </div><Button- id="community-theme"- variant="outline"- role="combobox"- className="w-full justify-between font-normal"+ variant="ghost"+ size="icon"+ className="size-7 shrink-0"+ onClick={discardDraft}>- <span className="truncate">- {THEMES[communityTheme].name}- </span>- <Expand className="opacity-50" />+ <Close className="size-4" />+ <span className="sr-only">Discard draft</span></Button>- </PopoverTrigger>- <PopoverContent className="p-0">- <Command>- <CommandInput- placeholder="Search themes..."- className="h-9"- />- <CommandList>- <CommandEmpty>No themes found.</CommandEmpty>- <CommandGroup>- {COMMUNITY_THEME.map((theme) => (- <CommandItem- value={theme}- key={theme}- onSelect={(v) =>- setCommunityTheme(v as CommunityTheme)- }- >- <span className="truncate">- {THEMES[theme].name}- </span>- <span className="font-commit-mono text-muted-foreground truncate text-xs">- by {THEMES[theme].author.name}- </span>- <Check- className={cn(- "ml-auto",- theme === communityTheme- ? "opacity-100"- : "opacity-0",- )}- />- </CommandItem>- ))}- </CommandGroup>- </CommandList>- </Command>- </PopoverContent>- </Popover>- </div>+ </div>+ <p className="text-muted-foreground text-xs">+ Previewing the theme from the builder. Discard it to switch+ between community themes.+ </p>+ </div>+ ) : (+ <div className="space-y-2">+ <Label htmlFor="community-theme">Community Theme</Label>+ <Popover>+ <PopoverTrigger asChild>+ <Button+ id="community-theme"+ variant="outline"+ role="combobox"+ className="w-full justify-between font-normal"+ >+ <span className="truncate">+ {THEMES[communityTheme].name}+ </span>+ <Expand className="opacity-50" />+ </Button>+ </PopoverTrigger>+ <PopoverContent className="p-0">+ <Command>+ <CommandInput+ placeholder="Search themes..."+ className="h-9"+ />+ <CommandList>+ <CommandEmpty>No themes found.</CommandEmpty>+ <CommandGroup>+ {COMMUNITY_THEME.map((theme) => (+ <CommandItem+ value={theme}+ key={theme}+ onSelect={(v) =>+ setCommunityTheme(v as CommunityTheme)+ }+ >+ <span className="truncate">+ {THEMES[theme].name}+ </span>+ <span className="font-commit-mono text-muted-foreground truncate text-xs">+ by {THEMES[theme].author.name}+ </span>+ <Check+ className={cn(+ "ml-auto",+ theme === communityTheme+ ? "opacity-100"+ : "opacity-0",+ )}+ />+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ </div>+ )}</div></PopoverContent></Popover>diff --git a/apps/status-page/src/components/themes/theme-agent-actions.tsx b/apps/status-page/src/components/themes/theme-agent-actions.tsxnew file mode 100644index 000000000..196369ed2--- /dev/null+++ b/apps/status-page/src/components/themes/theme-agent-actions.tsx@@ -0,0 +1,32 @@+"use client";++import { Agent } from "@openstatus/icons";+import { Button } from "@openstatus/ui/components/ui/button";+import { useCopyToClipboard } from "@openstatus/ui/hooks/use-copy-to-clipboard";++import { generateThemePrompt } from "../../lib/theme-prompt";+import { useThemeBuilder } from "./theme-builder-provider";++/** Copies a prompt carrying the builder theme for the user's own agent. */+export function ThemePromptButton({+ onClick,+ ...props+}: React.ComponentProps<typeof Button>) {+ const { theme } = useThemeBuilder();+ const { copy } = useCopyToClipboard();+ return (+ <Button+ variant="outline"+ {...props}+ onClick={(e) => {+ copy(generateThemePrompt(theme), {+ withToast: "Prompt copied, paste it into your agent",+ });+ onClick?.(e);+ }}+ >+ <Agent className="size-4" />+ Copy prompt+ </Button>+ );+}diff --git a/apps/status-page/src/components/themes/theme-builder-provider.tsx b/apps/status-page/src/components/themes/theme-builder-provider.tsxnew file mode 100644index 000000000..6cb5f2c95--- /dev/null+++ b/apps/status-page/src/components/themes/theme-builder-provider.tsx@@ -0,0 +1,49 @@+"use client";++import { THEMES, type Theme } from "@openstatus/theme-store";+import { useQueryStates } from "nuqs";+import { createContext, useContext, useEffect, useState } from "react";++import { searchParamsParsers } from "../../app/(public)/search-params";++interface ThemeBuilderContextType {+ /** Theme in the builder: the selected theme plus the user's edits. */+ theme: Theme;+ setTheme: React.Dispatch<React.SetStateAction<Theme>>;+ /** True once the builder theme differs from the selected registered theme. */+ isModified: boolean;+ reset: () => void;+}++const ThemeBuilderContext = createContext<ThemeBuilderContextType | null>(null);++export function useThemeBuilder() {+ const context = useContext(ThemeBuilderContext);+ if (!context) {+ throw new Error("useThemeBuilder must be used within ThemeBuilderProvider");+ }+ return context;+}++export function ThemeBuilderProvider({+ children,+}: {+ children: React.ReactNode;+}) {+ const [{ t }] = useQueryStates(searchParamsParsers);+ const [theme, setTheme] = useState<Theme>(THEMES[t]);++ useEffect(() => {+ setTheme(THEMES[t]);+ }, [t]);++ const isModified = JSON.stringify(theme) !== JSON.stringify(THEMES[t]);++ return (+ <ThemeBuilderContext.Provider+ value={{ theme, setTheme, isModified, reset: () => setTheme(THEMES[t]) }}+ >+ {children}+ </ThemeBuilderContext.Provider>+ );+}diff --git a/apps/status-page/src/components/themes/theme-paste-dialog.tsx b/apps/status-page/src/components/themes/theme-paste-dialog.tsxnew file mode 100644index 000000000..351c70042--- /dev/null+++ b/apps/status-page/src/components/themes/theme-paste-dialog.tsx@@ -0,0 +1,110 @@+"use client";++import { Check, Code } from "@openstatus/icons";+import {+ type ParsedThemeInput,+ type Theme,+ type ThemeMode,+ parseThemeInput,+} from "@openstatus/theme-store";+import { Button } from "@openstatus/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@openstatus/ui/components/ui/dialog";+import { Textarea } from "@openstatus/ui/components/ui/textarea";+import { useTheme } from "next-themes";+import { useState } from "react";+import { toast } from "sonner";++import { useThemeBuilder } from "./theme-builder-provider";++function applyParsedTheme(theme: Theme, parsed: ParsedThemeInput): Theme {+ if (parsed.partial) {+ return {+ ...theme,+ ...parsed.info,+ light: { ...theme.light, ...parsed.definition.light },+ dark: { ...theme.dark, ...parsed.definition.dark },+ };+ }+ return { ...theme, ...parsed.info, ...parsed.definition };+}++/** Applies a pasted theme (JSON, `.ts` file, CSS or bare declarations) to the builder. */+export function ThemePasteDialog(props: React.ComponentProps<typeof Button>) {+ const { setTheme } = useThemeBuilder();+ const { resolvedTheme } = useTheme();+ const [open, setOpen] = useState(false);+ const [text, setText] = useState("");+ const mode: ThemeMode = resolvedTheme === "dark" ? "dark" : "light";++ function apply() {+ const result = parseThemeInput(text, mode);+ if (!result.ok) {+ toast.error(result.error);+ return;+ }+ setTheme((prev) => applyParsedTheme(prev, result));+ if (result.warnings.length > 0) {+ toast.warning(+ `Applied with ${result.warnings.length} skipped ${+ result.warnings.length === 1 ? "entry" : "entries"+ }`,+ { description: result.warnings[0] },+ );+ } else {+ toast.success("Theme applied");+ }+ setOpen(false);+ }++ function onOpenChange(next: boolean) {+ setOpen(next);+ if (!next) setText("");+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogTrigger asChild>+ <Button {...props}>+ <Code className="size-4" />+ Paste+ </Button>+ </DialogTrigger>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Paste a theme</DialogTitle>+ <DialogDescription>+ JSON or the TypeScript theme file, as your agent or the copy button+ produced it. <code>:root</code> / <code>.dark</code> CSS blocks work+ too, and bare <code>--name: value;</code> lines apply to the {mode}{" "}+ mode.+ </DialogDescription>+ </DialogHeader>+ <Textarea+ value={text}+ onChange={(e) => setText(e.target.value)}+ placeholder={`{\n "id": "my-theme",\n "name": "My Theme",\n "light": { "--primary": "oklch(0.6 0.1 250)" },\n "dark": { "--primary": "oklch(0.8 0.1 250)" }\n}`}+ // no ligatures — Geist Mono merges "--" into a single long-dash glyph+ className="field-sizing-fixed h-64 font-mono text-xs [font-variant-ligatures:none]"+ autoFocus+ />+ <DialogFooter>+ <Button variant="outline" onClick={() => setOpen(false)}>+ Cancel+ </Button>+ <Button onClick={apply} disabled={text.trim().length === 0}>+ <Check className="size-4" />+ Apply+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/status-page/src/components/themes/theme-sidebar.tsx b/apps/status-page/src/components/themes/theme-sidebar.tsxindex 1fcd428f5..11befe8df 100644--- a/apps/status-page/src/components/themes/theme-sidebar.tsx+++ b/apps/status-page/src/components/themes/theme-sidebar.tsx@@ -1,17 +1,16 @@"use client";import {- Check,ChevronDown,Copy,Sidebar as SidebarIcon,Reset,} from "@openstatus/icons";import {- THEMES,type Theme,- type ThemeKey,+ type ThemeExportFormat,type ThemeVarName,+ serializeTheme,} from "@openstatus/theme-store";import { Button } from "@openstatus/ui/components/ui/button";import {@@ -24,6 +23,12 @@ import {CollapsibleContent,CollapsibleTrigger,} from "@openstatus/ui/components/ui/collapsible";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@openstatus/ui/components/ui/dropdown-menu";import {InputGroup,InputGroupInput,@@ -60,6 +65,9 @@ import { useEffect, useState } from "react";import { searchParamsParsers } from "../../app/(public)/search-params";import { recomputeStyles } from "../status-page/floating-button";+import { ThemePromptButton } from "./theme-agent-actions";+import { useThemeBuilder } from "./theme-builder-provider";+import { ThemePasteDialog } from "./theme-paste-dialog";type ThemeBuilderColor = {label: string;@@ -74,28 +82,20 @@ type ThemeBuilderCheckbox = {options: { value: string; label: boolean }[];};-const THEME_BUILDER_INFO = {- id: {- label: "ID",- id: "id",- type: "text",- },- name: {- label: "Name",- id: "name",- type: "text",- },- author: {- label: "Author",- id: "author.name",- type: "text",- },- authorUrl: {- label: "Link",- id: "author.url",- type: "text",- },-} as const;+type ThemeInfoField = "id" | "name" | "author.name" | "author.url";++const THEME_BUILDER_INFO: { id: ThemeInfoField; label: string }[] = [+ { id: "id", label: "ID" },+ { id: "name", label: "Name" },+ { id: "author.name", label: "Author" },+ { id: "author.url", label: "Link" },+];++const THEME_EXPORT_FORMATS: { id: ThemeExportFormat; label: string }[] = [+ { id: "ts", label: "TypeScript file" },+ { id: "json", label: "JSON" },+ { id: "css", label: "CSS variables" },+];const THEME_STYLE_BUILDER = {base: {@@ -144,23 +144,37 @@ const THEME_STYLE_BUILDER = {},} satisfies Record<string, ThemeBuilderColor | ThemeBuilderCheckbox>;-// Helper function to get nested property value from an object-// oxlint-disable-next-line typescript/no-explicit-any-function getNestedValue(obj: any, path: string): string | undefined {- const keys = path.split(".");- let value = obj;- for (const key of keys) {- if (value === undefined || value === null) return undefined;- value = value[key];+function getInfo(theme: Theme, field: ThemeInfoField) {+ switch (field) {+ case "id":+ return theme.id;+ case "name":+ return theme.name;+ case "author.name":+ return theme.author.name;+ case "author.url":+ return theme.author.url;+ }+}++function setInfo(theme: Theme, field: ThemeInfoField, value: string): Theme {+ switch (field) {+ case "id":+ return { ...theme, id: value };+ case "name":+ return { ...theme, name: value };+ case "author.name":+ return { ...theme, author: { ...theme.author, name: value } };+ case "author.url":+ return { ...theme, author: { ...theme.author, url: value } };}- return value;}export function ThemeSidebar(props: React.ComponentProps<typeof Sidebar>) {- const [{ t, b }, setSearchParams] = useQueryStates(searchParamsParsers);- const [newTheme, setNewTheme] = useState<Theme>(THEMES[t]);+ const [{ b }, setSearchParams] = useQueryStates(searchParamsParsers);+ const { theme: newTheme, setTheme: setNewTheme, reset } = useThemeBuilder();const { resolvedTheme, setTheme } = useTheme();- const { copy, isCopied } = useCopyToClipboard();+ const { copy } = useCopyToClipboard();const [isMounted, setIsMounted] = useState(false);const debouncedNewTheme = useDebounce(newTheme, 100);const { setOpen } = useSidebar();@@ -169,10 +183,6 @@ export function ThemeSidebar(props: React.ComponentProps<typeof Sidebar>) {setIsMounted(true);}, []);- useEffect(() => {- setNewTheme(THEMES[t]);- }, [t]);-useEffect(() => {if (b) {setOpen(true);@@ -182,9 +192,14 @@ export function ThemeSidebar(props: React.ComponentProps<typeof Sidebar>) {useEffect(() => {if (!resolvedTheme || !isMounted) return;- recomputeStyles(debouncedNewTheme.id as ThemeKey, { ...debouncedNewTheme });+ recomputeStyles(debouncedNewTheme.id, { ...debouncedNewTheme });}, [resolvedTheme, isMounted, debouncedNewTheme]);+ function copyTheme(format: ThemeExportFormat) {+ const label = THEME_EXPORT_FORMATS.find((f) => f.id === format)?.label;+ copy(serializeTheme(newTheme, format), { withToast: `Copied ${label}` });+ }+return (<Sidebar side="right" {...props}><SidebarHeader className="border-border border-b px-3 font-medium">@@ -196,7 +211,7 @@ export function ThemeSidebar(props: React.ComponentProps<typeof Sidebar>) {variant="ghost"size="icon"className="size-7"- onClick={() => setNewTheme(THEMES[t])}+ onClick={reset}><span className="sr-only">Reset</span><Reset />@@ -208,9 +223,29 @@ export function ThemeSidebar(props: React.ComponentProps<typeof Sidebar>) {</Tooltip></div></SidebarHeader>- <SidebarContent>- <Collapsible key="info" defaultOpen className="group/collapsible">+ <SidebarContent className="pb-2">+ <Collapsible key="agent" defaultOpen className="group/collapsible"><SidebarGroup className="pt-2 pb-0">+ <SidebarGroupLabel asChild>+ <CollapsibleTrigger>+ Agent+ <ChevronDown className="ml-auto transition-transform group-data-[state=open]/collapsible:rotate-180" />+ </CollapsibleTrigger>+ </SidebarGroupLabel>+ <CollapsibleContent>+ <SidebarGroupContent className="space-y-2 px-2">+ <p className="text-muted-foreground text-xs">+ Let your agent design the theme. The prompt carries the+ current configuration and the output format you can paste back+ here.+ </p>+ <ThemePromptButton size="sm" className="w-full" />+ </SidebarGroupContent>+ </CollapsibleContent>+ </SidebarGroup>+ </Collapsible>+ <Collapsible key="info" defaultOpen className="group/collapsible">+ <SidebarGroup className="py-0"><SidebarGroupLabel asChild><CollapsibleTrigger>Information@@ -220,8 +255,8 @@ export function ThemeSidebar(props: React.ComponentProps<typeof Sidebar>) {<CollapsibleContent><SidebarGroupContent><SidebarMenu>- {Object.entries(THEME_BUILDER_INFO).map(([key, config]) => (- <SidebarMenuItem key={key}>+ {THEME_BUILDER_INFO.map((config) => (+ <SidebarMenuItem key={config.id}><SidebarMenuButton asChild><div><ButtonGroup className="w-full">@@ -231,10 +266,11 @@ export function ThemeSidebar(props: React.ComponentProps<typeof Sidebar>) {<InputGroup className="h-7"><InputGroupInputid={config.id}- defaultValue={- newTheme- ? getNestedValue(newTheme, config.id)- : ""+ value={getInfo(newTheme, config.id)}+ onChange={(e) =>+ setNewTheme((prev) =>+ setInfo(prev, config.id, e.target.value),+ )}/></InputGroup>@@ -277,15 +313,9 @@ export function ThemeSidebar(props: React.ComponentProps<typeof Sidebar>) {</SidebarMenu></SidebarGroupContent></SidebarGroup>- {Object.entries(THEME_STYLE_BUILDER).map(([key, config], index) => (+ {Object.entries(THEME_STYLE_BUILDER).map(([key, config]) => (<Collapsible key={key} defaultOpen className="group/collapsible">- <SidebarGroup- className={cn(- index !== Object.entries(THEME_STYLE_BUILDER).length - 1- ? "py-0"- : "pt-0",- )}- >+ <SidebarGroup className="py-0"><SidebarGroupLabel asChild><CollapsibleTrigger>{config.label}@@ -321,17 +351,28 @@ export function ThemeSidebar(props: React.ComponentProps<typeof Sidebar>) {))}</SidebarContent><SidebarFooter className="border-border border-t">- <Button- size="sm"- onClick={() => copy(JSON.stringify(newTheme), { withToast: false })}- >- {isCopied ? "Configuration Copied!" : "Copy Configuration"}- {isCopied ? (- <Check className="size-4" />- ) : (- <Copy className="size-4" />- )}- </Button>+ <div className="grid grid-cols-2 gap-2">+ <ThemePasteDialog variant="outline" size="sm" />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button size="sm">+ <Copy className="size-4" />+ Copy+ <ChevronDown className="size-3.5 opacity-70" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {THEME_EXPORT_FORMATS.map((format) => (+ <DropdownMenuItem+ key={format.id}+ onSelect={() => copyTheme(format.id)}+ >+ {format.label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div></SidebarFooter></Sidebar>);diff --git a/apps/status-page/src/lib/theme-draft.ts b/apps/status-page/src/lib/theme-draft.tsnew file mode 100644index 000000000..8630f91c9--- /dev/null+++ b/apps/status-page/src/lib/theme-draft.ts@@ -0,0 +1,26 @@+import { type Theme, parseThemeInput } from "@openstatus/theme-store";++/** Set by the explorer, read by `FloatingTheme` to preview a builder theme on `/status`. */+export const THEME_DRAFT_STORAGE_KEY = "community-theme-draft";++export function saveThemeDraft(theme: Theme) {+ sessionStorage.setItem(THEME_DRAFT_STORAGE_KEY, JSON.stringify(theme));+}++export function clearThemeDraft() {+ sessionStorage.removeItem(THEME_DRAFT_STORAGE_KEY);+}++/** Re-validates on read so a hand-edited storage entry can't inject styles. */+export function readThemeDraft(): Theme | null {+ const raw = sessionStorage.getItem(THEME_DRAFT_STORAGE_KEY);+ if (!raw) return null;+ const result = parseThemeInput(raw);+ if (!result.ok) return null;+ return {+ id: result.info.id ?? "draft",+ name: result.info.name ?? "Draft",+ author: result.info.author ?? { name: "", url: "" },+ ...result.definition,+ };+}diff --git a/apps/status-page/src/lib/theme-prompt.test.ts b/apps/status-page/src/lib/theme-prompt.test.tsnew file mode 100644index 000000000..014a891a9--- /dev/null+++ b/apps/status-page/src/lib/theme-prompt.test.ts@@ -0,0 +1,26 @@+import { THEME_VAR_NAMES, THEMES } from "@openstatus/theme-store";+import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";++import {+ generateThemePrompt,+ THEME_SKILL_INSTALL_COMMAND,+} from "./theme-prompt";++describe("generateThemePrompt", () => {+ const prompt = generateThemePrompt(THEMES.dracula);++ test("lists every supported variable except the rainbow range", () => {+ for (const name of THEME_VAR_NAMES) {+ if (name.startsWith("--rainbow-")) continue;+ expect(prompt).toContain(name);+ }+ expect(prompt).toContain("--rainbow-1 … --rainbow-17");+ });++ test("embeds the current theme and the skill install command", () => {+ expect(prompt).toContain('"id": "dracula"');+ expect(prompt).toContain(THEME_SKILL_INSTALL_COMMAND);+ expect(prompt).toContain("https://themes.openstatus.dev/?b=true");+ });+});diff --git a/apps/status-page/src/lib/theme-prompt.ts b/apps/status-page/src/lib/theme-prompt.tsnew file mode 100644index 000000000..a8762abce--- /dev/null+++ b/apps/status-page/src/lib/theme-prompt.ts@@ -0,0 +1,88 @@+import {+ THEME_VAR_NAMES,+ type Theme,+ serializeTheme,+} from "@openstatus/theme-store";++import { THEME_EXPLORER_URL } from "./theme-explorer-host";++export const THEME_BUILDER_URL = `${THEME_EXPLORER_URL}/?b=true`;+export const THEME_SKILL_URL =+ "https://github.com/openstatusHQ/skills/tree/main/skills/openstatus-theme";+export const THEME_SKILL_INSTALL_COMMAND =+ "npx skills add openstatushq/skills --skill openstatus-theme";++const STATUS_VARS = ["--success", "--warning", "--destructive", "--info"];+const BRAND_VARS = [+ "--primary",+ "--primary-foreground",+ "--secondary",+ "--secondary-foreground",+];+const CHART_VARS = THEME_VAR_NAMES.filter((name) =>+ name.startsWith("--chart-"),+);+const RAINBOW_VARS = THEME_VAR_NAMES.filter((name) =>+ name.startsWith("--rainbow-"),+);+const BASE_VARS = THEME_VAR_NAMES.filter(+ (name) =>+ name !== "--radius" &&+ !STATUS_VARS.includes(name) &&+ !BRAND_VARS.includes(name) &&+ !CHART_VARS.includes(name) &&+ !RAINBOW_VARS.includes(name),+);++/** Prompt a user hands to their own agent; the reply pastes back into the builder. */+export function generateThemePrompt(theme: Theme) {+ return `Design a theme for my openstatus status page.++## Brief++<describe your brand, mood, reference palette or the colors you already use>++## Output++Reply with exactly one \`\`\`json code block containing the theme, nothing else in it. I will paste it into the theme builder at ${THEME_BUILDER_URL} (Paste) to preview it on a status page.++Shape:++{+ "id": "kebab-case-id",+ "name": "Display Name",+ "author": { "name": "@handle", "url": "https://..." },+ "light": { "--background": "oklch(100% 0 0)", "--foreground": "oklch(14.5% 0 0)" },+ "dark": { "--background": "oklch(14.5% 0 0)", "--foreground": "oklch(98.5% 0 0)" }+}++## Supported CSS variables++Anything else is dropped. Only override what the theme needs, unset variables fall back to the default openstatus theme.++- Base: ${BASE_VARS.join(", ")}+- Brand: ${BRAND_VARS.join(", ")}+- Status: ${STATUS_VARS.join(", ")} (operational, degraded, outage/error, maintenance)+- Charts, response time percentiles: ${CHART_VARS.join(", ")}+- Regions on the monitor map, rarely worth overriding: ${RAINBOW_VARS[0]} … ${RAINBOW_VARS[RAINBOW_VARS.length - 1]}+- Shape: --radius (a length, e.g. 0rem or 0.625rem)++## Rules++- Values are CSS colors (oklch() preferred; hex, hsl and named colors work) or var(--other-variable) to reuse one. No ; { } < characters, max 256 characters per value.+- Define both light and dark. Tune dark separately: lift lightness and lower chroma of the status colors so they don't burn on a dark background.+- Keep the canvas (base + brand) calm and low-chroma; give the chroma to the four status colors. They must stay distinguishable from each other, also for color-blind readers.+- Body text contrast ≥ 4.5:1 against --background in both modes.+- One coherent look, no "christmas tree".++## Starting point++This is the theme currently in my builder. Refine it unless the brief asks for something else:++\`\`\`json+${serializeTheme(theme, "json")}+\`\`\`++If you can install agent skills, run \`${THEME_SKILL_INSTALL_COMMAND}\` for the full workflow, including contributing the theme to the openstatus repository.+`;+}diff --git a/apps/web/src/content/pages/docs/guides/how-to-create-status-page-theme.mdx b/apps/web/src/content/pages/docs/guides/how-to-create-status-page-theme.mdxindex 16eb891ef..40742834d 100644--- a/apps/web/src/content/pages/docs/guides/how-to-create-status-page-theme.mdx+++ b/apps/web/src/content/pages/docs/guides/how-to-create-status-page-theme.mdx@@ -18,17 +18,22 @@ Themes are contributed through GitHub. We keep them in version control so everyIf you use AI agents, install the [`openstatus-theme` skill](https://github.com/openstatusHQ/skills/tree/main/skills/openstatus-theme) with `npx skills add openstatushq/skills --skill openstatus-theme` for guided help through palette design, accessibility checks, file scaffolding, and PR submission.</Aside>-## Two ways to build a theme+## Three ways to build a theme-<Grid cols={2}>+<Grid cols={3}><Card title="Visual builder">-Configure a palette at [themes.openstatus.dev](https://themes.openstatus.dev/?b=true) and copy the generated configuration. Fastest way to get a starting point.+Configure a palette at [themes.openstatus.dev](https://themes.openstatus.dev/?b=true) and copy it as a TypeScript file, JSON or CSS. Fastest way to get a starting point.+</Card>+<Card title="Your agent">+Click **Copy prompt** in the builder and hand it to your agent. It receives the current configuration, the supported variables and the JSON shape to reply with. **Paste** the reply back into the builder to preview it.</Card><Card title="Local development">Run the status page app locally and iterate against real, seeded content. Best for fine-tuning and final testing.</Card></Grid>+The builder accepts a theme as JSON, as the TypeScript theme file, or as `:root { }` / `.dark { }` CSS blocks, so anything an agent produces pastes right in. Click **Test it** on the explorer page to preview the builder theme on a full status page before you touch the repository.+Most contributors start in the builder, then test locally before submitting.## 1. Run the project locallydiff --git a/apps/web/src/content/pages/product/status-page.mdx b/apps/web/src/content/pages/product/status-page.mdxindex a6a72be52..91ace0af1 100644--- a/apps/web/src/content/pages/product/status-page.mdx+++ b/apps/web/src/content/pages/product/status-page.mdx@@ -182,7 +182,7 @@ Every action asks for confirmation before anything goes public, and every action<Grid variant="borderless"><div>-Pick a theme from the store or override any CSS variable, separately for light and dark. Point status.yourdomain.com at it; the "Powered by" line goes away on Scale.+Pick a theme from the store or override any CSS variable, separately for light and dark. Point status.yourdomain.com at it, and even white label it to drop the "Powered by" line.- [Theme Store](https://themes.openstatus.dev)- [Custom theme variables](/docs/reference/status-page#custom-theme)diff --git a/packages/theme-store/README.md b/packages/theme-store/README.mdindex fd69ab769..f44215b7b 100644--- a/packages/theme-store/README.md+++ b/packages/theme-store/README.md@@ -28,7 +28,9 @@ Want to contribute a theme?We only support themes via GitHub contributions to keep a certain version control. You can:-- Configure your [themes.openstatus.dev](https://themes.openstatus.dev/?b=true) and copy the configuration+- Configure your theme at [themes.openstatus.dev](https://themes.openstatus.dev/?b=true) and copy it as a TypeScript file, JSON or CSS+- Let your agent design it: **Copy prompt** in the builder hands your agent the current configuration and the JSON shape to reply with; **Paste** applies the reply (JSON, the `.ts` theme file, or `:root { } / .dark { }` CSS) to the preview+- Preview the builder theme on a full status page with **Test it** on the explorer page- Directly test by running it locally### 1. Run the projectdiff --git a/packages/theme-store/src/__tests__/theme-io.test.ts b/packages/theme-store/src/__tests__/theme-io.test.tsnew file mode 100644index 000000000..cc2033f1b--- /dev/null+++ b/packages/theme-store/src/__tests__/theme-io.test.ts@@ -0,0 +1,216 @@+import { readdirSync, readFileSync } from "node:fs";++import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";++import {+ parseThemeInput,+ serializeTheme,+ THEME_KEYS,+ THEMES,+ type Theme,+} from "../index";++function expectOk(result: ReturnType<typeof parseThemeInput>) {+ if (!result.ok) throw new Error(result.error);+ return result;+}++describe("parseThemeInput", () => {+ test("round-trips every registered theme through each export format", () => {+ for (const key of THEME_KEYS) {+ const theme = THEMES[key];+ for (const format of ["ts", "json", "css"] as const) {+ const result = expectOk(parseThemeInput(serializeTheme(theme, format)));+ expect(result.definition).toEqual({+ light: theme.light,+ dark: theme.dark,+ });+ expect(result.warnings).toEqual([]);+ if (format !== "css") {+ expect(result.info).toEqual({+ id: theme.id,+ name: theme.name,+ author: theme.author,+ });+ }+ }+ }+ });++ test("parses the theme source files as they are checked in", () => {+ const dir = new URL("../", import.meta.url);+ const skip = [+ "custom-theme.ts",+ "index.ts",+ "theme-io.ts",+ "types.ts",+ "utils.ts",+ ];+ const parsedIds: string[] = [];+ for (const file of readdirSync(dir)) {+ if (!file.endsWith(".ts") || skip.includes(file)) continue;+ const source = readFileSync(new URL(file, dir), "utf8");+ // one literal per `export const`; spreads (default-rounded) aren't parseable+ for (const chunk of source.split(/^export const /m).slice(1)) {+ if (chunk.includes("...")) continue;+ const result = expectOk(parseThemeInput(chunk));+ const theme = THEMES[result.info.id ?? ""];+ expect(+ theme,+ `${file}: unregistered id ${result.info.id}`,+ ).toBeDefined();+ expect(result.definition).toEqual({+ light: theme.light,+ dark: theme.dark,+ });+ expect(result.warnings).toEqual([]);+ parsedIds.push(theme.id);+ }+ }+ expect(parsedIds).toContain("default");+ expect(parsedIds.length).toBeGreaterThanOrEqual(THEME_KEYS.length - 1);+ });++ test("accepts a bare { light, dark } definition", () => {+ const result = expectOk(+ parseThemeInput(+ '{ "light": { "--primary": "red" }, "dark": { "--primary": "pink" } }',+ ),+ );+ expect(result.info).toEqual({});+ expect(result.partial).toBe(false);+ expect(result.definition).toEqual({+ light: { "--primary": "red" },+ dark: { "--primary": "pink" },+ });+ });++ test("accepts an agent reply wrapped in a markdown code fence", () => {+ const result = expectOk(+ parseThemeInput(+ 'Here you go:\n```json\n{ "id": "nord", "name": "Nord", "light": { "--primary": "#5e81ac" }, "dark": {} }\n```\nLet me know!',+ ),+ );+ expect(result.info.id).toBe("nord");+ expect(result.definition.light).toEqual({ "--primary": "#5e81ac" });+ });++ test("ignores a leading comment that contains a brace", () => {+ const result = expectOk(+ parseThemeInput(+ '/** see {@link Theme} */\n// shape: { light, dark }\nexport const X = { light: { "--primary": "red" }, dark: {} } as const satisfies Theme;',+ ),+ );+ expect(result.definition.light).toEqual({ "--primary": "red" });+ });++ test("keeps comment-like characters inside strings", () => {+ const result = expectOk(+ parseThemeInput(+ '{ "author": { "name": "x", "url": "https://x.dev/*" }, "light": { "--primary": "red" }, "dark": {} }',+ ),+ );+ expect(result.info.author?.url).toBe("https://x.dev/*");+ });++ test("matches CSS selectors exactly, not as prefixes", () => {+ const result = expectOk(+ parseThemeInput(+ ".light-theme { --primary: blue; }\n.light { --primary: red; }\n.dark-mode { --primary: blue; }\n.dark { --primary: pink; }",+ ),+ );+ expect(result.definition).toEqual({+ light: { "--primary": "red" },+ dark: { "--primary": "pink" },+ });+ });++ test("applies bare declarations and flat objects to the fallback mode", () => {+ const declarations = expectOk(+ parseThemeInput("--primary: red;\n--radius: 0.5rem", "dark"),+ );+ expect(declarations.partial).toBe(true);+ expect(declarations.definition).toEqual({+ light: {},+ dark: { "--primary": "red", "--radius": "0.5rem" },+ });++ const flat = expectOk(parseThemeInput('{ "--primary": "red" }', "dark"));+ expect(flat.partial).toBe(true);+ expect(flat.definition).toEqual({+ light: {},+ dark: { "--primary": "red" },+ });+ });++ test("merges a lone mode instead of wiping the other one", () => {+ const css = expectOk(parseThemeInput(":root {\n --primary: red;\n}"));+ expect(css.partial).toBe(true);+ expect(css.definition).toEqual({ light: { "--primary": "red" }, dark: {} });++ const json = expectOk(+ parseThemeInput('{ "dark": { "--primary": "red" } }'),+ );+ expect(json.partial).toBe(true);+ expect(json.definition).toEqual({+ light: {},+ dark: { "--primary": "red" },+ });+ });++ test("reads :root / .dark CSS blocks", () => {+ const result = expectOk(+ parseThemeInput(+ ":root {\n --primary: oklch(0.6 0.1 250);\n}\n.dark {\n --primary: oklch(0.8 0.1 250);\n}",+ ),+ );+ expect(result.partial).toBe(false);+ expect(result.definition).toEqual({+ light: { "--primary": "oklch(0.6 0.1 250)" },+ dark: { "--primary": "oklch(0.8 0.1 250)" },+ });+ });++ test("drops unknown vars and unsafe values with a warning", () => {+ const result = expectOk(+ parseThemeInput(+ '{ "light": { "--primary": "red", "--nope": "blue", "--info": "</style>" } }',+ ),+ );+ expect(result.definition.light).toEqual({ "--primary": "red" });+ expect(result.warnings).toHaveLength(2);+ expect(result.warnings.join()).toContain('Unknown CSS variable "--nope"');+ });++ test("fails when nothing usable was found", () => {+ expect(parseThemeInput("").ok).toBe(false);+ expect(parseThemeInput("hello world").ok).toBe(false);+ expect(parseThemeInput('{ "name": "x" }').ok).toBe(false);+ expect(parseThemeInput("{ light: { --nope: red } }").ok).toBe(false);+ expect(parseThemeInput("{ light: [1, 2] }").ok).toBe(false);+ });+});++describe("serializeTheme", () => {+ const theme = {+ id: "my-theme",+ name: "My Theme",+ author: { name: "@me", url: "https://example.com" },+ light: { "--primary": "red" },+ dark: { "--primary": "pink" },+ } satisfies Theme;++ test("ts names the export after the id", () => {+ const ts = serializeTheme(theme, "ts");+ expect(ts).toContain("export const MY_THEME = {");+ expect(ts).toContain("packages/theme-store/src/my-theme.ts");+ expect(ts).toContain("} as const satisfies Theme;");+ });++ test("css emits :root and .dark blocks", () => {+ expect(serializeTheme(theme, "css")).toBe(+ ":root {\n --primary: red;\n}\n.dark {\n --primary: pink;\n}",+ );+ });+});diff --git a/packages/theme-store/src/custom-theme.ts b/packages/theme-store/src/custom-theme.tsindex edf3e67a1..e9bd30525 100644--- a/packages/theme-store/src/custom-theme.ts+++ b/packages/theme-store/src/custom-theme.ts@@ -29,7 +29,7 @@ export type CustomThemeValidation =type LooseThemeVars = Record<string, string>;type LooseCustomTheme = { light?: LooseThemeVars; dark?: LooseThemeVars };-function validateVarEntry(name: string, value: string): string[] {+export function validateVarEntry(name: string, value: string): string[] {const errors: string[] = [];if (!THEME_VAR_NAME_SET.has(name)) {errors.push(`Unknown CSS variable "${name}".`);diff --git a/packages/theme-store/src/index.ts b/packages/theme-store/src/index.tsindex e4bd03a70..72006ce60 100644--- a/packages/theme-store/src/index.ts+++ b/packages/theme-store/src/index.ts@@ -1,4 +1,5 @@export * from "./custom-theme";+export * from "./theme-io";export * from "./types";import {type CustomTheme,diff --git a/packages/theme-store/src/theme-io.ts b/packages/theme-store/src/theme-io.tsnew file mode 100644index 000000000..8cdca0bf8--- /dev/null+++ b/packages/theme-store/src/theme-io.ts@@ -0,0 +1,333 @@+import { parseThemeVarsText, validateVarEntry } from "./custom-theme";+import type {+ Theme,+ ThemeDefinition,+ ThemeInfo,+ ThemeMode,+ ThemeVarName,+ ThemeVars,+} from "./types";++export type ThemeExportFormat = "ts" | "json" | "css";++export type ParsedThemeInput = {+ info: Partial<ThemeInfo>;+ definition: ThemeDefinition;+ /** Merge into the current theme instead of replacing it (bare declarations, a lone CSS block). */+ partial: boolean;+ /** Dropped vars / values — the rest of the input still applied. */+ warnings: string[];+};++export type ParseThemeInputResult =+ | ({ ok: true } & ParsedThemeInput)+ | { ok: false; error: string };++/**+ * Parses anything a builder, an agent or a theme file hands over: a `Theme`+ * (or `{ light, dark }`) as JSON or as a TS/JS object literal, CSS with+ * `:root { }` / `.dark { }` blocks, or bare `--name: value;` declarations+ * (applied to `fallbackMode`).+ */+export function parseThemeInput(+ text: string,+ fallbackMode: ThemeMode = "light",+): ParseThemeInputResult {+ const source = text.trim();+ if (source.length === 0) return { ok: false, error: "Nothing to paste." };++ const light = cssBlock(source, [":root", ".light"]);+ const dark = cssBlock(source, [".dark"]);+ const parsed =+ light !== undefined || dark !== undefined+ ? parseCssBlocks(light, dark)+ : source.includes("{")+ ? parseObjectLiteral(source, fallbackMode)+ : parseDeclarations(source, fallbackMode);++ if (!parsed.ok) return parsed;++ const hasVars =+ Object.keys(parsed.definition.light).length > 0 ||+ Object.keys(parsed.definition.dark).length > 0;+ if (!hasVars) {+ const detail = parsed.warnings[0] ? ` ${parsed.warnings[0]}` : "";+ return { ok: false, error: `No supported CSS variables found.${detail}` };+ }+ return parsed;+}++function parseDeclarations(+ source: string,+ mode: ThemeMode,+): ParseThemeInputResult {+ const { vars, errors } = parseThemeVarsText(source);+ const definition: ThemeDefinition = { light: {}, dark: {} };+ definition[mode] = vars;+ return { ok: true, info: {}, definition, partial: true, warnings: errors };+}++/** Body of the first `selector { … }`; indexOf instead of a regex (CodeQL js/polynomial-redos). */+function cssBlock(source: string, selectors: string[]) {+ for (const selector of selectors) {+ let from = 0;+ let start = source.indexOf(selector, from);+ while (start !== -1) {+ from = start + selector.length;+ const open = source.indexOf("{", from);+ if (open === -1) break;+ // `.light-theme {` is not `.light {`+ if (source.slice(from, open).trim().length === 0) {+ const close = source.indexOf("}", open);+ return close === -1 ? undefined : source.slice(open + 1, close);+ }+ start = source.indexOf(selector, from);+ }+ }+ return undefined;+}++function parseCssBlocks(+ light: string | undefined,+ dark: string | undefined,+): ParseThemeInputResult {+ const lightResult = parseThemeVarsText(light ?? "");+ const darkResult = parseThemeVarsText(dark ?? "");+ return {+ ok: true,+ info: {},+ definition: { light: lightResult.vars, dark: darkResult.vars },+ // a lone block must not wipe the other mode+ partial: light === undefined || dark === undefined,+ warnings: [...lightResult.errors, ...darkResult.errors],+ };+}++function parseObjectLiteral(+ source: string,+ fallbackMode: ThemeMode,+): ParseThemeInputResult {+ // `import type { Theme }` carries a brace before the literal; everything+ // else ahead of it (comments, fences, prose) is skipped by objectStart+ const stripped = source.replace(/^\s*import\b[^\n]*$/gm, "");+ const from = objectStart(stripped);+ if (from === -1) {+ return { ok: false, error: "Expected an object with light / dark vars." };+ }+ const json = toJson(stripped.slice(from).replace(/\bas const\b/g, ""));+ const start = json.indexOf("{");+ const end = json.lastIndexOf("}");+ if (start === -1 || end <= start) {+ return { ok: false, error: "Expected an object with light / dark vars." };+ }++ let value: unknown;+ try {+ value = JSON.parse(json.slice(start, end + 1));+ } catch {+ return {+ ok: false,+ error:+ "Could not parse the configuration. Paste the JSON or the theme file as is.",+ };+ }+ if (!isRecord(value)) {+ return { ok: false, error: "Expected an object with light / dark vars." };+ }++ const warnings: string[] = [];+ const definition: ThemeDefinition = { light: {}, dark: {} };+ let partial = false;++ if (isRecord(value.light) || isRecord(value.dark)) {+ // `{ light }` alone must not wipe dark (and vice versa)+ partial = value.light === undefined || value.dark === undefined;+ for (const mode of ["light", "dark"] as const) {+ const vars = value[mode];+ if (vars === undefined) continue;+ if (!isRecord(vars)) {+ warnings.push(`"${mode}" must be an object of CSS variables.`);+ continue;+ }+ definition[mode] = pickVars(vars, warnings);+ }+ } else if (Object.keys(value).some((key) => key.startsWith("--"))) {+ definition[fallbackMode] = pickVars(value, warnings);+ partial = true;+ } else {+ return { ok: false, error: "Expected an object with light / dark vars." };+ }++ const info: Partial<ThemeInfo> = {};+ if (typeof value.id === "string" && value.id.trim())+ info.id = value.id.trim();+ if (typeof value.name === "string" && value.name.trim()) {+ info.name = value.name.trim();+ }+ if (+ isRecord(value.author) &&+ typeof value.author.name === "string" &&+ typeof value.author.url === "string"+ ) {+ info.author = { name: value.author.name, url: value.author.url };+ }++ return { ok: true, info, definition, partial, warnings };+}++function pickVars(+ input: Record<string, unknown>,+ warnings: string[],+): ThemeVars {+ const vars: ThemeVars = {};+ for (const [name, raw] of Object.entries(input)) {+ if (typeof raw !== "string") {+ warnings.push(`Value of "${name}" must be a string.`);+ continue;+ }+ const errors = validateVarEntry(name, raw);+ if (errors.length > 0) {+ warnings.push(...errors);+ continue;+ }+ // safe: validateVarEntry checked membership in THEME_VAR_NAMES+ vars[name as ThemeVarName] = raw.trim();+ }+ return vars;+}++/** Index of the first `{` outside a comment; the body itself is left to the string-aware toJson. */+function objectStart(source: string) {+ let i = 0;+ while (i < source.length) {+ if (source.startsWith("//", i)) {+ const end = source.indexOf("\n", i);+ if (end === -1) return -1;+ i = end + 1;+ } else if (source.startsWith("/*", i)) {+ const end = source.indexOf("*/", i + 2);+ if (end === -1) return -1;+ i = end + 2;+ } else if (source.charAt(i) === "{") {+ return i;+ } else {+ i++;+ }+ }+ return -1;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/**+ * Rewrites a TS/JS object literal into strict JSON: strips comments, quotes+ * bare keys, normalizes quotes and drops trailing commas. String-aware, so+ * `//` inside an author url survives.+ */+function toJson(source: string): string {+ let out = "";+ let i = 0;+ while (i < source.length) {+ const ch = source.charAt(i);++ if (ch === '"' || ch === "'" || ch === "`") {+ let j = i + 1;+ let str = "";+ while (j < source.length && source[j] !== ch) {+ if (source[j] === "\\") {+ str += source[j + 1] ?? "";+ j += 2;+ continue;+ }+ str += source.charAt(j);+ j++;+ }+ out += JSON.stringify(str);+ i = j + 1;+ continue;+ }++ if (ch === "/" && source[i + 1] === "/") {+ while (i < source.length && source[i] !== "\n") i++;+ continue;+ }+ if (ch === "/" && source[i + 1] === "*") {+ const end = source.indexOf("*/", i + 2);+ i = end === -1 ? source.length : end + 2;+ continue;+ }++ if (/[A-Za-z_$]/.test(ch)) {+ let j = i;+ while (j < source.length && /[\w$]/.test(source.charAt(j))) j++;+ const word = source.slice(i, j);+ let k = j;+ while (k < source.length && /\s/.test(source.charAt(k))) k++;+ if (source[k] === ":") {+ out += `${JSON.stringify(word)}:`;+ i = k + 1;+ } else {+ out += word;+ i = j;+ }+ continue;+ }++ // comments are already gone from `out`, so a trailing comma is whatever+ // precedes the closing bracket+ if (ch === "}" || ch === "]") out = out.replace(/,\s*$/, "");++ out += ch;+ i++;+ }+ return out;+}++/** Serializes a theme for the clipboard: theme file, JSON or CSS blocks. */+export function serializeTheme(theme: Theme, format: ThemeExportFormat) {+ switch (format) {+ case "json":+ return JSON.stringify(theme, null, 2);+ case "css":+ return `:root {\n${formatBlock(theme.light)}\n}\n.dark {\n${formatBlock(theme.dark)}\n}`;+ case "ts":+ return [+ `// packages/theme-store/src/${theme.id}.ts`,+ `import type { Theme } from "./types";`,+ "",+ `export const ${constName(theme.id)} = {`,+ ` id: ${JSON.stringify(theme.id)},`,+ ` name: ${JSON.stringify(theme.name)},`,+ ` author: { name: ${JSON.stringify(theme.author.name)}, url: ${JSON.stringify(theme.author.url)} },`,+ ` light: {\n${formatObject(theme.light)}\n },`,+ ` dark: {\n${formatObject(theme.dark)}\n },`,+ "} as const satisfies Theme;",+ ].join("\n");+ }+}++function constName(id: string) {+ const base = id+ .toUpperCase()+ .replace(/[^A-Z0-9]+/g, "_")+ .replace(/^_|_$/g, "")+ .replace(/_?THEME$/, "");+ return `${base || "MY"}_THEME`;+}++function formatBlock(vars: ThemeVars) {+ return Object.entries(vars)+ .map(([name, value]) => ` ${name}: ${value};`)+ .join("\n");+}++function formatObject(vars: ThemeVars) {+ return Object.entries(vars)+ .map(+ ([name, value]) =>+ ` ${JSON.stringify(name)}: ${JSON.stringify(value)},`,+ )+ .join("\n");+}