Skip to content

armgit / pdfcn

Public Imported from GitHub
0

Beautiful pdf components, built on Takumi and Forme. 100% Free, Zero config, one command setup.

refactor: reorganize theme builder components and improve font handling

Aniket-508532b87b307a4
diff --git a/components/pdf-preview.tsx b/components/pdf-preview.tsx
index f2e50ee..08c9c04 100644
--- a/components/pdf-preview.tsx
+++ b/components/pdf-preview.tsx
@@ -4,14 +4,13 @@ import { createElement, useEffect, useRef, useState } from "react";
import takumiWasmUrl from "takumi-pdf/wasm-url";
import { replacePreviewImageSources } from "@/examples/preview-assets";
-import { cn } from "@/lib/utils";
-import type { BaseName } from "@/registry/bases";
-import type { PdfcnTheme } from "@/registry/themes";
-
import {
getPreviewFonts,
getPreviewFontUrls,
-} from "./theme-builder/preview-fonts";
+} from "@/lib/theme-builder/preview-fonts";
+import { cn } from "@/lib/utils";
+import type { BaseName } from "@/registry/bases";
+import type { PdfcnTheme } from "@/registry/themes";
const PREVIEW_LOGO_PATH = "/favicon.png";
diff --git a/components/theme-builder/theme-builder.tsx b/components/theme-builder/theme-builder.tsx
index 2177d3c..9a87b84 100644
--- a/components/theme-builder/theme-builder.tsx
+++ b/components/theme-builder/theme-builder.tsx
@@ -12,7 +12,13 @@ import {
Undo2,
} from "lucide-react";
import Link from "next/link";
-import { useCallback, useDeferredValue, useEffect, useState } from "react";
+import {
+ useCallback,
+ useDeferredValue,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
import { toast } from "sonner";
import { FormeIcon, TakumiIcon } from "@/components/icons";
@@ -24,15 +30,13 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
+import { useMounted } from "@/hooks/use-mounted";
+import { useThemeBuilder } from "@/hooks/use-theme-builder";
import { cn } from "@/lib/utils";
import type { BaseName } from "@/registry/bases";
import { ThemeCodeDialog } from "./theme-code-dialog";
import { ThemeControls } from "./theme-controls";
-import { writeThemeState } from "./theme-storage";
-import { useThemeBuilder } from "./use-theme-builder";
-
-const PERSIST_DELAY_MS = 300;
const BASE_SWITCHER = [
{ icon: TakumiIcon, name: "takumi" as const },
@@ -40,13 +44,15 @@ const BASE_SWITCHER = [
];
export const ThemeBuilder = ({ base }: { base: BaseName }) => {
- const { actions, basePreset, canRedo, canUndo, hydrated, theme } =
+ const { actions, basePreset, canRedo, canUndo, syncToUrl, theme } =
useThemeBuilder();
+ const isMounted = useMounted();
const previewTheme = useDeferredValue(theme);
const [codeOpen, setCodeOpen] = useState(false);
const [customizerOpen, setCustomizerOpen] = useState(false);
const [pdfUrl, setPdfUrl] = useState<string | null>(null);
const [sidebarOpen, setSidebarOpen] = useState(true);
+ const syncTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const safeThemeName =
theme.name
@@ -54,17 +60,22 @@ export const ThemeBuilder = ({ base }: { base: BaseName }) => {
.toLowerCase()
.replaceAll(/[^a-z0-9-]+/g, "-") || "theme";
+ // Debounced sync to URL + localStorage
useEffect(() => {
- if (!hydrated) {
+ if (!isMounted) {
return;
}
- const timeout = window.setTimeout(() => {
- writeThemeState({ basePreset, theme });
- }, PERSIST_DELAY_MS);
+ syncTimeoutRef.current = setTimeout(() => {
+ syncToUrl({ basePreset, theme });
+ }, 300);
- return () => window.clearTimeout(timeout);
- }, [basePreset, hydrated, theme]);
+ return () => {
+ if (syncTimeoutRef.current) {
+ clearTimeout(syncTimeoutRef.current);
+ }
+ };
+ }, [basePreset, isMounted, syncToUrl, theme]);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
@@ -104,7 +115,7 @@ export const ThemeBuilder = ({ base }: { base: BaseName }) => {
}, []);
const shareTheme = async () => {
- writeThemeState({ basePreset, theme });
+ syncToUrl({ basePreset, theme });
try {
await navigator.clipboard.writeText(window.location.href);
toast.success("Share link copied");
@@ -295,7 +306,10 @@ export const ThemeBuilder = ({ base }: { base: BaseName }) => {
: "lg:grid-cols-[minmax(0,1fr)_0px]"
)}
>
- <section aria-label="Live PDF preview">
+ <section
+ className="relative min-h-0 overflow-hidden"
+ aria-label="Live PDF preview"
+ >
<PdfPreview
base={base}
className="h-full rounded-none border-0"
diff --git a/components/theme-builder/theme-code-dialog.tsx b/components/theme-builder/theme-code-dialog.tsx
index 77d989c..fb05f92 100644
--- a/components/theme-builder/theme-code-dialog.tsx
+++ b/components/theme-builder/theme-code-dialog.tsx
@@ -12,12 +12,14 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import {
+ generateDeltaCode,
+ generateThemeCode,
+} from "@/lib/theme-builder/generate-code";
+import { getRemoteFontFamilies } from "@/lib/theme-builder/preview-fonts";
import { cn } from "@/lib/utils";
import type { PdfcnTheme, ThemePresetName } from "@/registry/themes";
-import { getRemoteFontFamilies } from "./preview-fonts";
-import { generateDeltaCode, generateThemeCode } from "./theme-code";
-
type CodeTab = "delta" | "full";
interface ThemeCodeDialogProps {
@@ -111,7 +113,7 @@ export const ThemeCodeDialog = ({
return (
<Dialog onOpenChange={handleOpenChange} open={open}>
- <DialogContent className="gap-0 overflow-hidden p-0 sm:max-w-3xl">
+ <DialogContent className="flex max-h-[85svh] flex-col gap-0 overflow-hidden p-0 sm:max-w-3xl">
<DialogHeader className="border-b p-5 pr-12">
<DialogTitle>Generated theme code</DialogTitle>
<DialogDescription>
@@ -173,14 +175,14 @@ export const ThemeCodeDialog = ({
</p>
</div>
) : null}
- <div className="max-h-[60svh] overflow-auto [&_pre]:m-0">
+ <div className="min-h-0 flex-1 overflow-auto bg-code [&_pre]:m-0">
{highlightedCode ? (
<div
dangerouslySetInnerHTML={{ __html: highlightedCode }}
dir="ltr"
/>
) : (
- <pre className="bg-code p-5 font-mono text-xs leading-relaxed text-code-foreground">
+ <pre className="p-5 font-mono text-xs leading-relaxed text-code-foreground">
<code>{code}</code>
</pre>
)}
diff --git a/components/theme-builder/theme-controls.tsx b/components/theme-builder/theme-controls.tsx
index 902b8aa..901f8ba 100644
--- a/components/theme-builder/theme-controls.tsx
+++ b/components/theme-builder/theme-controls.tsx
@@ -14,18 +14,23 @@ import {
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { cn } from "@/lib/utils";
-import type { PdfcnTheme, ThemePresetName } from "@/registry/themes";
-import { THEMES } from "@/registry/themes";
-
-import { ThemePicker } from "./theme-picker";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
import type {
ColorTokenName,
HeadingLevel,
PageMargin,
SpacingTokenName,
ThemeBuilderActions,
-} from "./use-theme-builder";
+} from "@/hooks/use-theme-builder";
+import { cn } from "@/lib/utils";
+import type { PdfcnTheme, ThemePresetName } from "@/registry/themes";
+import { THEMES } from "@/registry/themes";
+
+import { ThemePicker } from "./theme-picker";
const COLOR_FIELDS = [
{ description: "Primary text", key: "foreground", label: "Foreground" },
@@ -241,26 +246,30 @@ export const ThemeControls = ({
onThemeSelect={(name) => actions.loadPreset(name)}
selectedTheme={basePreset}
/>
- <Button
- aria-label="Pick a random preset"
- onClick={() => {
- const others = THEMES.filter(({ name }) => name !== basePreset);
- const next = others[Math.floor(Math.random() * others.length)];
- if (next) {
- actions.loadPreset(next.name);
- }
- }}
- size="icon-sm"
- title="Pick a random preset"
- variant="outline"
- >
- <Shuffle />
- </Button>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-label="Pick a random preset"
+ onClick={() => {
+ const others = THEMES.filter(({ name }) => name !== basePreset);
+ const next = others[Math.floor(Math.random() * others.length)];
+ if (next) {
+ actions.loadPreset(next.name);
+ }
+ }}
+ size="icon-sm"
+ variant="outline"
+ >
+ <Shuffle />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Random preset</TooltipContent>
+ </Tooltip>
</div>
</div>
<Tabs className="gap-4 px-6" defaultValue="colors">
- <TabsList className="grid w-full grid-cols-3">
+ <TabsList className="grid w-full grid-cols-3 gap-1">
<TabsTrigger value="colors">
<Palette />
Colors
diff --git a/components/theme-builder/theme-picker.tsx b/components/theme-builder/theme-picker.tsx
index de47048..e794ad5 100644
--- a/components/theme-builder/theme-picker.tsx
+++ b/components/theme-builder/theme-picker.tsx
@@ -1,6 +1,6 @@
"use client";
-import { CheckIcon } from "lucide-react";
+import { CheckIcon, ChevronsUpDownIcon } from "lucide-react";
import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
@@ -31,7 +31,7 @@ const THEME_PALETTE_KEYS = [
type ThemeColors = Pick<ColorTokens, (typeof THEME_PALETTE_KEYS)[number]>;
const ThemePalette = ({ colors }: { colors?: ThemeColors }) => (
- <div className="flex shrink-0 gap-0.5">
+ <div className="flex shrink-0 gap-1">
{THEME_PALETTE_KEYS.map((key) => (
<div
key={key}
@@ -42,151 +42,151 @@ const ThemePalette = ({ colors }: { colors?: ThemeColors }) => (
</div>
);
-const SHADCN_THEMES: { name: string; title: string; colors: ThemeColors }[] = [
- {
- colors: {
- accent: "#f5f5f5",
- background: "#ffffff",
- muted: "#f5f5f5",
- primary: "#171717",
- },
- name: "default",
- title: "Default",
- },
- {
- colors: {
- accent: "#dbeafe",
- background: "#ffffff",
- muted: "#f1f5f9",
- primary: "#1d4ed8",
- },
- name: "blue",
- title: "Blue",
- },
- {
- colors: {
- accent: "#dcfce7",
- background: "#ffffff",
- muted: "#f0fdf4",
- primary: "#15803d",
- },
- name: "green",
- title: "Green",
- },
- {
- colors: {
- accent: "#f5f5f5",
- background: "#ffffff",
- muted: "#f5f5f5",
- primary: "#171717",
- },
- name: "neutral",
- title: "Neutral",
- },
- {
- colors: {
- accent: "#f5f5f4",
- background: "#ffffff",
- muted: "#f5f5f4",
- primary: "#1c1917",
- },
- name: "stone",
- title: "Stone",
- },
- {
- colors: {
- accent: "#f4f4f5",
- background: "#ffffff",
- muted: "#f4f4f5",
- primary: "#18181b",
- },
- name: "zinc",
- title: "Zinc",
- },
- {
- colors: {
- accent: "#f1f5f9",
- background: "#ffffff",
- muted: "#f1f5f9",
- primary: "#0f172a",
- },
- name: "slate",
- title: "Slate",
- },
- {
- colors: {
- accent: "#f3f4f6",
- background: "#ffffff",
- muted: "#f3f4f6",
- primary: "#111827",
- },
- name: "gray",
- title: "Gray",
- },
-];
+// const SHADCN_THEMES: { name: string; title: string; colors: ThemeColors }[] = [
+// {
+// colors: {
+// accent: "#f5f5f5",
+// background: "#ffffff",
+// muted: "#f5f5f5",
+// primary: "#171717",
+// },
+// name: "default",
+// title: "Default",
+// },
+// {
+// colors: {
+// accent: "#dbeafe",
+// background: "#ffffff",
+// muted: "#f1f5f9",
+// primary: "#1d4ed8",
+// },
+// name: "blue",
+// title: "Blue",
+// },
+// {
+// colors: {
+// accent: "#dcfce7",
+// background: "#ffffff",
+// muted: "#f0fdf4",
+// primary: "#15803d",
+// },
+// name: "green",
+// title: "Green",
+// },
+// {
+// colors: {
+// accent: "#f5f5f5",
+// background: "#ffffff",
+// muted: "#f5f5f5",
+// primary: "#171717",
+// },
+// name: "neutral",
+// title: "Neutral",
+// },
+// {
+// colors: {
+// accent: "#f5f5f4",
+// background: "#ffffff",
+// muted: "#f5f5f4",
+// primary: "#1c1917",
+// },
+// name: "stone",
+// title: "Stone",
+// },
+// {
+// colors: {
+// accent: "#f4f4f5",
+// background: "#ffffff",
+// muted: "#f4f4f5",
+// primary: "#18181b",
+// },
+// name: "zinc",
+// title: "Zinc",
+// },
+// {
+// colors: {
+// accent: "#f1f5f9",
+// background: "#ffffff",
+// muted: "#f1f5f9",
+// primary: "#0f172a",
+// },
+// name: "slate",
+// title: "Slate",
+// },
+// {
+// colors: {
+// accent: "#f3f4f6",
+// background: "#ffffff",
+// muted: "#f3f4f6",
+// primary: "#111827",
+// },
+// name: "gray",
+// title: "Gray",
+// },
+// ];
-const TWEAKCN_THEMES: { name: string; title: string; colors: ThemeColors }[] = [
- {
- colors: {
- accent: "#caf0f8",
- background: "#ffffff",
- muted: "#f0f8ff",
- primary: "#0077b6",
- },
- name: "ocean",
- title: "Ocean",
- },
- {
- colors: {
- accent: "#d8f3dc",
- background: "#ffffff",
- muted: "#f0fdf4",
- primary: "#2d6a4f",
- },
- name: "forest",
- title: "Forest",
- },
- {
- colors: {
- accent: "#ffedd8",
- background: "#ffffff",
- muted: "#fff7ed",
- primary: "#e85d04",
- },
- name: "sunset",
- title: "Sunset",
- },
- {
- colors: {
- accent: "#ede9fe",
- background: "#ffffff",
- muted: "#f5f3ff",
- primary: "#7c3aed",
- },
- name: "lavender",
- title: "Lavender",
- },
- {
- colors: {
- accent: "#ffe4e6",
- background: "#ffffff",
- muted: "#fff1f2",
- primary: "#e11d48",
- },
- name: "rose",
- title: "Rose",
- },
- {
- colors: {
- accent: "#fef3c7",
- background: "#ffffff",
- muted: "#fffbeb",
- primary: "#d97706",
- },
- name: "amber",
- title: "Amber",
- },
-];
+// const TWEAKCN_THEMES: { name: string; title: string; colors: ThemeColors }[] = [
+// {
+// colors: {
+// accent: "#caf0f8",
+// background: "#ffffff",
+// muted: "#f0f8ff",
+// primary: "#0077b6",
+// },
+// name: "ocean",
+// title: "Ocean",
+// },
+// {
+// colors: {
+// accent: "#d8f3dc",
+// background: "#ffffff",
+// muted: "#f0fdf4",
+// primary: "#2d6a4f",
+// },
+// name: "forest",
+// title: "Forest",
+// },
+// {
+// colors: {
+// accent: "#ffedd8",
+// background: "#ffffff",
+// muted: "#fff7ed",
+// primary: "#e85d04",
+// },
+// name: "sunset",
+// title: "Sunset",
+// },
+// {
+// colors: {
+// accent: "#ede9fe",
+// background: "#ffffff",
+// muted: "#f5f3ff",
+// primary: "#7c3aed",
+// },
+// name: "lavender",
+// title: "Lavender",
+// },
+// {
+// colors: {
+// accent: "#ffe4e6",
+// background: "#ffffff",
+// muted: "#fff1f2",
+// primary: "#e11d48",
+// },
+// name: "rose",
+// title: "Rose",
+// },
+// {
+// colors: {
+// accent: "#fef3c7",
+// background: "#ffffff",
+// muted: "#fffbeb",
+// primary: "#d97706",
+// },
+// name: "amber",
+// title: "Amber",
+// },
+// ];
interface ThemePickerProps {
onThemeSelect: (name: ThemePresetName) => void;
@@ -210,11 +210,12 @@ export const ThemePicker = ({
<Button
variant="outline"
size="sm"
- className="w-full justify-start gap-2 px-2"
+ className="flex-1 justify-start gap-2 px-2"
aria-label="Select theme"
>
<ThemePalette colors={selectedThemeData?.theme.colors} />
<span className="flex-1 text-left">{selectedThemeData?.title}</span>
+ <ChevronsUpDownIcon className="opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[320px] p-0" align="start">
@@ -223,7 +224,7 @@ export const ThemePicker = ({
<CommandList>
<CommandEmpty>No theme found.</CommandEmpty>
- <CommandGroup heading="PDF Themes">
+ <CommandGroup>
{THEMES.map(({ name, theme, title }) => (
<CommandItem
key={name}
@@ -241,7 +242,7 @@ export const ThemePicker = ({
))}
</CommandGroup>
- <CommandGroup heading="shadcn/ui Themes">
+ {/* <CommandGroup heading="shadcn/ui Themes">
{SHADCN_THEMES.map((theme) => (
<CommandItem key={theme.name} disabled>
<ThemePalette colors={theme.colors} />
@@ -257,7 +258,7 @@ export const ThemePicker = ({
<span className="flex-1">{theme.title}</span>
</CommandItem>
))}
- </CommandGroup>
+ </CommandGroup> */}
</CommandList>
</Command>
</PopoverContent>
diff --git a/constants/theme-builder.ts b/constants/theme-builder.ts
new file mode 100644
index 0000000..d25eb9a
--- /dev/null
+++ b/constants/theme-builder.ts
@@ -0,0 +1,3 @@
+export const THEME_BUILDER_HISTORY_LIMIT = 30;
+
+export const THEME_BUILDER_STORAGE_KEY = "pdfcn-theme-builder";
diff --git a/hooks/use-mounted.ts b/hooks/use-mounted.ts
index 8b60d01..c8fc285 100644
--- a/hooks/use-mounted.ts
+++ b/hooks/use-mounted.ts
@@ -1,11 +1,17 @@
-import { useState, useEffect } from "react";
+import { useSyncExternalStore } from "react";
-export const useMounted = () => {
- const [mounted, setMounted] = useState(false);
+const subscribe = () => () => {
+ /* empty */
+};
+const getSnapshot = () => true;
+const getServerSnapshot = () => false;
- useEffect(() => {
- setMounted(true);
- }, []);
+export const useMounted = () => {
+ const isMounted = useSyncExternalStore(
+ subscribe,
+ getSnapshot,
+ getServerSnapshot
+ );
- return mounted;
+ return isMounted;
};
diff --git a/components/theme-builder/use-theme-builder.ts b/hooks/use-theme-builder.ts
similarity index 87%
rename from components/theme-builder/use-theme-builder.ts
rename to hooks/use-theme-builder.ts
index ee29884..1ff886c 100644
--- a/components/theme-builder/use-theme-builder.ts
+++ b/hooks/use-theme-builder.ts
@@ -1,15 +1,19 @@
"use client";
-import { useEffect, useMemo, useReducer } from "react";
+import { useCallback, useEffect, useMemo, useReducer } from "react";
+import {
+ THEME_BUILDER_HISTORY_LIMIT,
+ THEME_BUILDER_STORAGE_KEY,
+} from "@/constants/theme-builder";
+import {
+ readThemeState,
+ writeThemeState,
+} from "@/lib/theme-builder/persist-theme";
+import type { StoredThemeState } from "@/lib/theme-builder/persist-theme";
import type { PdfcnTheme, ThemePresetName } from "@/registry/themes";
import { themePresets } from "@/registry/themes";
-import { readThemeState } from "./theme-storage";
-import type { StoredThemeState } from "./theme-storage";
-
-const HISTORY_LIMIT = 30;
-
export type ColorTokenName = keyof PdfcnTheme["colors"];
export type HeadingLevel =
keyof PdfcnTheme["typography"]["heading"]["fontSize"];
@@ -22,15 +26,14 @@ type ThemeSnapshot = StoredThemeState;
interface ThemeBuilderState {
basePreset: ThemePresetName;
future: ThemeSnapshot[];
- hydrated: boolean;
past: ThemeSnapshot[];
theme: PdfcnTheme;
}
type ThemeBuilderAction =
- | { type: "HYDRATE"; stored: StoredThemeState | null }
| { type: "UPDATE"; update: ThemeUpdate }
| { type: "LOAD_PRESET"; preset: ThemePresetName }
+ | { type: "RESTORE"; stored: StoredThemeState }
| { type: "UNDO" }
| { type: "REDO" };
@@ -63,31 +66,34 @@ const cloneTheme = (theme: PdfcnTheme): PdfcnTheme => ({
const pushHistory = (
history: ThemeSnapshot[],
snapshot: ThemeSnapshot
-): ThemeSnapshot[] => [...history.slice(-(HISTORY_LIMIT - 1)), snapshot];
+): ThemeSnapshot[] => [
+ ...history.slice(-(THEME_BUILDER_HISTORY_LIMIT - 1)),
+ snapshot,
+];
const snapshotState = (state: ThemeBuilderState): ThemeSnapshot => ({
basePreset: state.basePreset,
theme: state.theme,
});
+const getInitialState = (): ThemeBuilderState => ({
+ basePreset: "professional",
+ future: [],
+ past: [],
+ theme: cloneTheme(themePresets.professional),
+});
+
const reducer = (
state: ThemeBuilderState,
action: ThemeBuilderAction
): ThemeBuilderState => {
- if (action.type === "HYDRATE") {
- if (state.hydrated) {
- return state;
- }
-
- return action.stored
- ? {
- basePreset: action.stored.basePreset,
- future: [],
- hydrated: true,
- past: [],
- theme: cloneTheme(action.stored.theme),
- }
- : { ...state, hydrated: true };
+ if (action.type === "RESTORE") {
+ return {
+ basePreset: action.stored.basePreset,
+ future: [],
+ past: [],
+ theme: cloneTheme(action.stored.theme),
+ };
}
if (action.type === "UPDATE") {
@@ -125,7 +131,7 @@ const reducer = (
basePreset: previous.basePreset,
future: [
snapshotState(state),
- ...state.future.slice(0, HISTORY_LIMIT - 1),
+ ...state.future.slice(0, THEME_BUILDER_HISTORY_LIMIT - 1),
],
past: state.past.slice(0, -1),
theme: previous.theme,
@@ -170,21 +176,24 @@ export interface ThemeBuilderActions {
}
export const useThemeBuilder = () => {
- const [state, dispatch] = useReducer(reducer, {
- basePreset: "professional",
- future: [],
- hydrated: false,
- past: [],
- theme: cloneTheme(themePresets.professional),
- });
+ const [state, dispatch] = useReducer(reducer, null, getInitialState);
useEffect(() => {
- dispatch({ stored: readThemeState(), type: "HYDRATE" });
+ const stored = readThemeState(THEME_BUILDER_STORAGE_KEY);
+ if (stored) {
+ dispatch({ stored, type: "RESTORE" });
+ }
+ }, []);
+
+ const syncToUrl = useCallback((snapshot: StoredThemeState) => {
+ writeThemeState(THEME_BUILDER_STORAGE_KEY, snapshot);
}, []);
const actions = useMemo<ThemeBuilderActions>(
() => ({
- loadPreset: (preset) => dispatch({ preset, type: "LOAD_PRESET" }),
+ loadPreset: (preset) => {
+ dispatch({ preset, type: "LOAD_PRESET" });
+ },
redo: () => dispatch({ type: "REDO" }),
setBodyFontFamily: (value) =>
dispatch({
@@ -361,7 +370,7 @@ export const useThemeBuilder = () => {
basePreset: state.basePreset,
canRedo: state.future.length > 0,
canUndo: state.past.length > 0,
- hydrated: state.hydrated,
+ syncToUrl,
theme: state.theme,
};
};
diff --git a/components/theme-builder/theme-code.ts b/lib/theme-builder/generate-code.ts
similarity index 100%
rename from components/theme-builder/theme-code.ts
rename to lib/theme-builder/generate-code.ts
diff --git a/components/theme-builder/theme-storage.ts b/lib/theme-builder/persist-theme.ts
similarity index 66%
rename from components/theme-builder/theme-storage.ts
rename to lib/theme-builder/persist-theme.ts
index 3e3c67c..2e15b81 100644
--- a/components/theme-builder/theme-storage.ts
+++ b/lib/theme-builder/persist-theme.ts
@@ -3,8 +3,6 @@ import { z } from "zod";
import type { PdfcnTheme, ThemePresetName } from "@/registry/themes";
import { themePresets } from "@/registry/themes";
-const STORAGE_KEY = "pdfcn-theme-builder";
-const HASH_KEY = "theme";
const PRESET_NAMES = Object.keys(themePresets) as [
ThemePresetName,
...ThemePresetName[],
@@ -12,6 +10,7 @@ const PRESET_NAMES = Object.keys(themePresets) as [
const finiteNumber = z.number().finite();
const hexColor = z.string().regex(/^#[\da-f]{6}$/i);
+
const ThemeSchema: z.ZodType<PdfcnTheme> = z.object({
colors: z.object({
accent: hexColor,
@@ -114,58 +113,80 @@ const ThemeSchema: z.ZodType<PdfcnTheme> = z.object({
}),
});
-const StoredThemeStateSchema = z.object({
+export const StoredThemeStateSchema = z.object({
basePreset: z.enum(PRESET_NAMES),
theme: ThemeSchema,
});
export type StoredThemeState = z.infer<typeof StoredThemeStateSchema>;
-const parseThemeState = (value: string | null): StoredThemeState | null => {
- if (!value) {
+const readFromLocalStorage = (storageKey: string): StoredThemeState | null => {
+ if (typeof window === "undefined") {
return null;
}
-
try {
- const result = StoredThemeStateSchema.safeParse(JSON.parse(value));
+ const raw = localStorage.getItem(storageKey);
+ if (!raw) {
+ return null;
+ }
+ const result = StoredThemeStateSchema.safeParse(JSON.parse(raw));
return result.success ? result.data : null;
} catch {
return null;
}
};
-export const readThemeState = (): StoredThemeState | null => {
+const writeToLocalStorage = (storageKey: string, state: StoredThemeState) => {
if (typeof window === "undefined") {
- return null;
+ return;
}
-
- const hashValue = new URLSearchParams(window.location.hash.slice(1)).get(
- HASH_KEY
- );
- if (hashValue) {
- return parseThemeState(hashValue);
+ try {
+ localStorage.setItem(storageKey, JSON.stringify(state));
+ } catch {
+ // Storage unavailable — URL is still the source of truth.
}
+};
+const serializeTheme = (state: StoredThemeState): string =>
+ btoa(encodeURIComponent(JSON.stringify(state)));
+
+const deserializeTheme = (encoded: string): StoredThemeState | null => {
try {
- return parseThemeState(localStorage.getItem(STORAGE_KEY));
+ const json = decodeURIComponent(atob(encoded));
+ const result = StoredThemeStateSchema.safeParse(JSON.parse(json));
+ return result.success ? result.data : null;
} catch {
return null;
}
};
-export const writeThemeState = (state: StoredThemeState) => {
+export const readThemeState = (storageKey: string): StoredThemeState | null => {
if (typeof window === "undefined") {
- return;
+ return null;
}
+ const hash = window.location.hash.slice(1);
+ const params = new URLSearchParams(hash);
+ const encoded = params.get("theme");
+ if (encoded) {
+ const fromUrl = deserializeTheme(encoded);
+ if (fromUrl) {
+ writeToLocalStorage(storageKey, fromUrl);
+ return fromUrl;
+ }
+ }
+ return readFromLocalStorage(storageKey);
+};
- const serialized = JSON.stringify(state);
- const url = new URL(window.location.href);
- url.hash = new URLSearchParams({ [HASH_KEY]: serialized }).toString();
- window.history.replaceState(null, "", url);
-
- try {
- localStorage.setItem(STORAGE_KEY, serialized);
- } catch {
- // The shareable URL remains the source of truth when storage is unavailable.
+export const writeThemeState = (
+ storageKey: string,
+ state: StoredThemeState
+) => {
+ if (typeof window === "undefined") {
+ return;
}
+ writeToLocalStorage(storageKey, state);
+ const encoded = serializeTheme(state);
+ const url = new URL(window.location.href);
+ url.hash = `theme=${encoded}`;
+ window.history.replaceState(null, "", url.toString());
};
diff --git a/components/theme-builder/preview-fonts.ts b/lib/theme-builder/preview-fonts.ts
similarity index 100%
rename from components/theme-builder/preview-fonts.ts
rename to lib/theme-builder/preview-fonts.ts