Skip to content

Production-ready animations, transitions, backgrounds, and scenes for Remotion

feat: decompositionc

dev_wandry673d10ea3403
diff --git a/app/(home)/stars/components/avatar-chips.tsx b/app/(home)/stars/components/avatar-chips.tsx
new file mode 100644
index 00000000..a97452db
--- /dev/null
+++ b/app/(home)/stars/components/avatar-chips.tsx
@@ -0,0 +1,24 @@
+import { motion } from "motion/react";
+import { Skeleton } from "@/components/ui/skeleton";
+import { SPRING_BOUNCE } from "@/config/site";
+
+/** Ghost avatar chips streaming in — the "stargazers flying in" tease. */
+export function AvatarChips({ reduced }: { reduced: boolean }) {
+ return (
+ <div className="flex flex-wrap justify-center gap-2">
+ {Array.from({ length: 9 }).map((_, i) => (
+ <motion.div
+ // biome-ignore lint/suspicious/noArrayIndexKey: fixed-length decorative placeholders
+ key={i}
+ initial={reduced ? false : { opacity: 0, x: -12 }}
+ animate={{ opacity: 1, x: 0 }}
+ transition={
+ reduced ? undefined : { ...SPRING_BOUNCE, delay: i * 0.06 }
+ }
+ >
+ <Skeleton className="size-9 rounded-full" />
+ </motion.div>
+ ))}
+ </div>
+ );
+}
diff --git a/app/(home)/stars/components/customizer-panel.tsx b/app/(home)/stars/components/customizer-panel.tsx
new file mode 100644
index 00000000..6157316e
--- /dev/null
+++ b/app/(home)/stars/components/customizer-panel.tsx
@@ -0,0 +1,25 @@
+import { ComponentCustomizer } from "@/components/docs/component-customizer";
+import { CUSTOM_CONTROLS } from "../lib/constants";
+
+/** Optional customizer panel (scalar inputProps). Hidden unless `show`. */
+export function CustomizerPanel({
+ show,
+ values,
+ onChange,
+}: {
+ show: boolean;
+ values: Record<string, unknown>;
+ onChange: (key: string, value: unknown) => void;
+}) {
+ if (!show) return null;
+
+ return (
+ <div className="mt-4">
+ <ComponentCustomizer
+ controls={CUSTOM_CONTROLS}
+ values={values}
+ onChange={onChange}
+ />
+ </div>
+ );
+}
diff --git a/app/(home)/stars/components/export-controls.tsx b/app/(home)/stars/components/export-controls.tsx
new file mode 100644
index 00000000..4637ff61
--- /dev/null
+++ b/app/(home)/stars/components/export-controls.tsx
@@ -0,0 +1,75 @@
+import { Download, X } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Progress } from "@/components/ui/progress";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+
+/** Download MP4 button with the exporting (progress + cancel) and unsupported
+ * (muted + tooltip) variants. */
+export function ExportControls({
+ supportsExport,
+ exporting,
+ exportProgress,
+ onDownload,
+ onCancelExport,
+}: {
+ supportsExport: boolean;
+ exporting: boolean;
+ exportProgress: number;
+ onDownload: () => void;
+ onCancelExport: () => void;
+}) {
+ if (exporting) {
+ return (
+ <div className="flex w-full items-center gap-3 sm:w-72">
+ <Progress
+ value={Math.round(exportProgress * 100)}
+ className="flex-1"
+ />
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={onCancelExport}
+ aria-label="Cancel export"
+ className="rounded-full"
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ );
+ }
+
+ if (supportsExport) {
+ return (
+ <Button size="lg" onClick={onDownload} className="gap-2 rounded-full">
+ <Download className="size-4" aria-hidden="true" />
+ Download MP4
+ </Button>
+ );
+ }
+
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ // Not the native `disabled` attribute — a disabled button
+ // suppresses hover/click, hiding the tooltip and the info toast.
+ // Style it muted and let onDownload surface the Chrome/Edge hint.
+ <Button
+ size="lg"
+ aria-disabled
+ onClick={onDownload}
+ className="gap-2 rounded-full opacity-50"
+ >
+ <Download className="size-4" aria-hidden="true" />
+ Download MP4
+ </Button>
+ }
+ />
+ <TooltipContent>MP4 export needs Chrome or Edge</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/app/(home)/stars/components/generating-view.tsx b/app/(home)/stars/components/generating-view.tsx
new file mode 100644
index 00000000..52aae3dd
--- /dev/null
+++ b/app/(home)/stars/components/generating-view.tsx
@@ -0,0 +1,39 @@
+import { Button } from "@/components/ui/button";
+import { Progress } from "@/components/ui/progress";
+import { useGenerationTicker } from "../hooks/use-generation-ticker";
+import { AvatarChips } from "./avatar-chips";
+
+export function GeneratingView({
+ reduced,
+ onCancel,
+}: {
+ reduced: boolean;
+ onCancel: () => void;
+}) {
+ const { progress, count } = useGenerationTicker(reduced);
+
+ return (
+ <div className="flex min-h-[70vh] flex-col items-center justify-center">
+ <div className="surface-card mx-auto w-full max-w-xl rounded-3xl p-8">
+ <AvatarChips reduced={reduced} />
+
+ <div className="mt-6">
+ <Progress value={progress} />
+ </div>
+
+ <p className="mt-4 text-center text-sm font-medium text-foreground">
+ Fetching stargazers…{" "}
+ <span className="tabular-nums text-muted-foreground">
+ {count.toLocaleString("en-US")}
+ </span>
+ </p>
+
+ <div className="mt-6 flex justify-center">
+ <Button variant="ghost" onClick={onCancel} className="rounded-full">
+ Cancel
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/app/(home)/stars/components/idle-view.tsx b/app/(home)/stars/components/idle-view.tsx
new file mode 100644
index 00000000..06e47771
--- /dev/null
+++ b/app/(home)/stars/components/idle-view.tsx
@@ -0,0 +1,42 @@
+import { FadeUp } from "../../components/fade-up";
+import { RepoInputForm } from "./repo-input-form";
+
+export function IdleView({
+ inputValue,
+ onInputChange,
+ onSubmit,
+ canGenerate,
+ zeroStars,
+}: {
+ inputValue: string;
+ onInputChange: (v: string) => void;
+ onSubmit: () => void;
+ canGenerate: boolean;
+ zeroStars: boolean;
+}) {
+ return (
+ <div className="flex min-h-[70vh] flex-col items-center justify-center text-center">
+ <FadeUp delay={0.06} className="flex flex-col items-center">
+ <h1 className="max-w-3xl text-balance text-3xl font-semibold leading-[1.1] tracking-tight text-foreground sm:text-4xl md:text-5xl">
+ Turn your repo&rsquo;s stars into a video
+ </h1>
+ </FadeUp>
+
+ <FadeUp delay={0.12}>
+ <p className="mt-4 max-w-2xl text-balance text-base leading-relaxed text-muted-foreground sm:text-lg">
+ Paste a GitHub repo. We fetch every stargazer and animate it into a
+ shareable clip.
+ </p>
+ </FadeUp>
+
+ <FadeUp delay={0.18} className="w-full">
+ <RepoInputForm
+ inputValue={inputValue}
+ onInputChange={onInputChange}
+ onSubmit={onSubmit}
+ canGenerate={canGenerate}
+ />
+ </FadeUp>
+ </div>
+ );
+}
diff --git a/app/(home)/stars/components/orientation-toggle.tsx b/app/(home)/stars/components/orientation-toggle.tsx
new file mode 100644
index 00000000..d56a3f9e
--- /dev/null
+++ b/app/(home)/stars/components/orientation-toggle.tsx
@@ -0,0 +1,31 @@
+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
+import { orientationToParam } from "../lib/dims";
+import type { Orientation } from "../lib/types";
+
+export function OrientationToggle({
+ orientation,
+ onOrientationChange,
+}: {
+ orientation: Orientation;
+ onOrientationChange: (o: Orientation) => void;
+}) {
+ return (
+ <ToggleGroup
+ value={[orientationToParam(orientation)]}
+ onValueChange={(value: string[]) => {
+ const next = value[0];
+ if (next)
+ onOrientationChange(next === "v" ? "vertical" : "horizontal");
+ }}
+ aria-label="Video orientation"
+ className="w-full sm:w-auto"
+ >
+ <ToggleGroupItem value="h" className="flex-1 sm:flex-none">
+ Horizontal
+ </ToggleGroupItem>
+ <ToggleGroupItem value="v" className="flex-1 sm:flex-none">
+ Vertical
+ </ToggleGroupItem>
+ </ToggleGroup>
+ );
+}
diff --git a/app/(home)/stars/components/player-frame.tsx b/app/(home)/stars/components/player-frame.tsx
new file mode 100644
index 00000000..b66e0f3e
--- /dev/null
+++ b/app/(home)/stars/components/player-frame.tsx
@@ -0,0 +1,79 @@
+import { Player } from "@remotion/player";
+import { Pause, Play } from "lucide-react";
+import type { RegistryEntry } from "@/registry/__index__";
+import { usePlayerControls } from "../hooks/use-player-controls";
+import { dims } from "../lib/dims";
+import type { GitHubStarsInputProps, Orientation } from "../lib/types";
+
+export function PlayerFrame({
+ entry,
+ inputProps,
+ orientation,
+ reduced,
+}: {
+ entry: RegistryEntry;
+ inputProps: GitHubStarsInputProps;
+ orientation: Orientation;
+ reduced: boolean;
+}) {
+ const { ref, playing, togglePlay } = usePlayerControls(!reduced);
+ const { width, height } = dims(orientation);
+
+ return (
+ // Player card — a fixed 16:9 frame so toggling orientation never reflows
+ // the page. Vertical renders pillarboxed + centered inside it, while the
+ // Player still gets the true 720×1280 composition so the exported MP4 is
+ // genuinely vertical (only the on-page container width stays constant).
+ <div
+ className="group surface-card relative w-full overflow-hidden rounded-2xl shadow-2xl shadow-black/5 sm:rounded-3xl dark:shadow-black/40"
+ style={{ aspectRatio: "1280 / 720" }}
+ >
+ <div className="absolute inset-0 flex items-center justify-center">
+ <div
+ className="h-full"
+ style={
+ orientation === "vertical"
+ ? {
+ height: "100%",
+ width: "auto",
+ aspectRatio: `${width} / ${height}`,
+ }
+ : { width: "100%", height: "100%" }
+ }
+ >
+ <Player
+ ref={ref}
+ component={entry.Component}
+ inputProps={inputProps}
+ durationInFrames={entry.config.durationInFrames}
+ fps={entry.config.fps}
+ compositionWidth={width}
+ compositionHeight={height}
+ style={{ width: "100%", height: "100%", display: "block" }}
+ autoPlay={!reduced}
+ loop
+ acknowledgeRemotionLicense
+ />
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={togglePlay}
+ aria-label={playing ? "Pause preview" : "Play preview"}
+ className="absolute inset-0 flex items-center justify-center bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
+ >
+ <span
+ aria-hidden
+ data-show={!playing}
+ className="pointer-events-none flex size-14 items-center justify-center rounded-full bg-background/70 text-foreground opacity-0 backdrop-blur-md transition-opacity duration-200 group-hover:opacity-100 motion-reduce:transition-none data-[show=true]:opacity-100"
+ >
+ {playing ? (
+ <Pause className="size-5" />
+ ) : (
+ <Play className="size-5 translate-x-0.5" />
+ )}
+ </span>
+ </button>
+ </div>
+ );
+}
diff --git a/app/(home)/stars/components/ready-footer.tsx b/app/(home)/stars/components/ready-footer.tsx
new file mode 100644
index 00000000..8836c252
--- /dev/null
+++ b/app/(home)/stars/components/ready-footer.tsx
@@ -0,0 +1,59 @@
+import { BookOpen, RotateCcw } from "lucide-react";
+import Link from "next/link";
+import { Button } from "@/components/ui/button";
+import { InstallCommand } from "../../components/install-command";
+import { DOCS_HREF, INSTALL_COMMAND } from "../lib/constants";
+import { ExportControls } from "./export-controls";
+
+/** Footer row: install advert + docs link on the left, reset + export on the right. */
+export function ReadyFooter({
+ onReset,
+ supportsExport,
+ exporting,
+ exportProgress,
+ onDownload,
+ onCancelExport,
+}: {
+ onReset: () => void;
+ supportsExport: boolean;
+ exporting: boolean;
+ exportProgress: number;
+ onDownload: () => void;
+ onCancelExport: () => void;
+}) {
+ return (
+ <div className="mt-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center">
+ <InstallCommand command={INSTALL_COMMAND} />
+ <Button
+ variant="outline"
+ size="lg"
+ className="h-11 gap-2 rounded-full"
+ render={<Link href={DOCS_HREF} />}
+ >
+ <BookOpen className="size-4" aria-hidden="true" />
+ View component docs
+ </Button>
+ </div>
+
+ <div className="flex items-center justify-end gap-2">
+ <Button
+ variant="ghost"
+ size="lg"
+ onClick={onReset}
+ className="gap-2 rounded-full"
+ >
+ <RotateCcw className="size-4" aria-hidden="true" />
+ Change repository
+ </Button>
+ <ExportControls
+ supportsExport={supportsExport}
+ exporting={exporting}
+ exportProgress={exportProgress}
+ onDownload={onDownload}
+ onCancelExport={onCancelExport}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/app/(home)/stars/components/ready-view.tsx b/app/(home)/stars/components/ready-view.tsx
new file mode 100644
index 00000000..0da1b8e4
--- /dev/null
+++ b/app/(home)/stars/components/ready-view.tsx
@@ -0,0 +1,109 @@
+import { Settings2 } from "lucide-react";
+import { motion } from "motion/react";
+import { Button } from "@/components/ui/button";
+import { SPRING_BOUNCE } from "@/config/site";
+import type { RegistryEntry } from "@/registry/__index__";
+import type { GitHubStarsInputProps, Orientation } from "../lib/types";
+import { CustomizerPanel } from "./customizer-panel";
+import { OrientationToggle } from "./orientation-toggle";
+import { PlayerFrame } from "./player-frame";
+import { ReadyFooter } from "./ready-footer";
+import { RepoTitle } from "./repo-title";
+import { TruncatedNotice } from "./truncated-notice";
+
+export function ReadyView({
+ entry,
+ inputProps,
+ repo,
+ totalStars,
+ truncated,
+ reduced,
+ orientation,
+ onOrientationChange,
+ onReset,
+ showCustomizer,
+ onToggleCustomizer,
+ customValues,
+ onCustomChange,
+ supportsExport,
+ exporting,
+ exportProgress,
+ onDownload,
+ onCancelExport,
+}: {
+ entry: RegistryEntry;
+ inputProps: GitHubStarsInputProps;
+ repo: string;
+ totalStars: number;
+ truncated: boolean;
+ reduced: boolean;
+ orientation: Orientation;
+ onOrientationChange: (o: Orientation) => void;
+ onReset: () => void;
+ showCustomizer: boolean;
+ onToggleCustomizer: () => void;
+ customValues: Record<string, unknown>;
+ onCustomChange: (key: string, value: unknown) => void;
+ supportsExport: boolean;
+ exporting: boolean;
+ exportProgress: number;
+ onDownload: () => void;
+ onCancelExport: () => void;
+}) {
+ return (
+ // Constant width regardless of orientation — the preview frame stays
+ // put when toggling horizontal/vertical (refinement #3).
+ <div className="mx-auto max-w-5xl">
+ <TruncatedNotice truncated={truncated} totalStars={totalStars} />
+
+ <motion.div
+ initial={reduced ? false : { y: 40, opacity: 0 }}
+ animate={{ y: 0, opacity: 1 }}
+ transition={{ ...SPRING_BOUNCE, delay: 0.05 }}
+ >
+ <RepoTitle repo={repo} totalStars={totalStars} />
+
+ {/* Controls bar */}
+ <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <OrientationToggle
+ orientation={orientation}
+ onOrientationChange={onOrientationChange}
+ />
+
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onToggleCustomizer}
+ aria-expanded={showCustomizer}
+ className="gap-2 rounded-full"
+ >
+ <Settings2 className="size-4" aria-hidden="true" />
+ Customize
+ </Button>
+ </div>
+
+ <PlayerFrame
+ entry={entry}
+ inputProps={inputProps}
+ orientation={orientation}
+ reduced={reduced}
+ />
+
+ <CustomizerPanel
+ show={showCustomizer}
+ values={customValues}
+ onChange={onCustomChange}
+ />
+
+ <ReadyFooter
+ onReset={onReset}
+ supportsExport={supportsExport}
+ exporting={exporting}
+ exportProgress={exportProgress}
+ onDownload={onDownload}
+ onCancelExport={onCancelExport}
+ />
+ </motion.div>
+ </div>
+ );
+}
diff --git a/app/(home)/stars/components/repo-input-form.tsx b/app/(home)/stars/components/repo-input-form.tsx
new file mode 100644
index 00000000..5540a3e3
--- /dev/null
+++ b/app/(home)/stars/components/repo-input-form.tsx
@@ -0,0 +1,42 @@
+import { ArrowRight } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+
+export function RepoInputForm({
+ inputValue,
+ onInputChange,
+ onSubmit,
+ canGenerate,
+}: {
+ inputValue: string;
+ onInputChange: (v: string) => void;
+ onSubmit: () => void;
+ canGenerate: boolean;
+}) {
+ return (
+ <form
+ className="mt-7 flex flex-col items-center gap-3 sm:flex-row sm:justify-center"
+ onSubmit={(e) => {
+ e.preventDefault();
+ onSubmit();
+ }}
+ >
+ <Input
+ value={inputValue}
+ onChange={(e) => onInputChange(e.target.value)}
+ aria-label="GitHub repository"
+ placeholder="github.com/owner/repo or owner/repo"
+ className="h-11 w-full rounded-full px-5 sm:max-w-sm"
+ />
+ <Button
+ type="submit"
+ size="lg"
+ disabled={!canGenerate}
+ className="h-11 gap-2 rounded-full px-6"
+ >
+ Generate
+ <ArrowRight className="size-4" aria-hidden="true" />
+ </Button>
+ </form>
+ );
+}
diff --git a/app/(home)/stars/components/repo-title.tsx b/app/(home)/stars/components/repo-title.tsx
new file mode 100644
index 00000000..6749840d
--- /dev/null
+++ b/app/(home)/stars/components/repo-title.tsx
@@ -0,0 +1,21 @@
+import { formatStars } from "@/lib/github";
+
+/** Centered repo heading + star count. */
+export function RepoTitle({
+ repo,
+ totalStars,
+}: {
+ repo: string;
+ totalStars: number;
+}) {
+ return (
+ <div className="mb-4 text-center">
+ <h2 className="truncate text-xl font-semibold tracking-tight text-foreground sm:text-2xl">
+ {repo}
+ </h2>
+ <p className="mt-0.5 text-sm text-muted-foreground">
+ {formatStars(totalStars)} stars
+ </p>
+ </div>
+ );
+}
diff --git a/app/(home)/stars/components/stars-tool.tsx b/app/(home)/stars/components/stars-tool.tsx
index 99d37c2a..ca2f82a7 100644
--- a/app/(home)/stars/components/stars-tool.tsx
+++ b/app/(home)/stars/components/stars-tool.tsx
@@ -1,327 +1,14 @@
"use client";
-import { Player, type PlayerRef } from "@remotion/player";
-import {
- ArrowRight,
- BookOpen,
- Download,
- Pause,
- Play,
- RotateCcw,
- Settings2,
- X,
-} from "lucide-react";
-import { motion } from "motion/react";
-import Link from "next/link";
-import { useQueryState } from "nuqs";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { toast } from "sonner";
-import { ComponentCustomizer } from "@/components/docs/component-customizer";
-import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Progress } from "@/components/ui/progress";
-import { Skeleton } from "@/components/ui/skeleton";
import { Toaster } from "@/components/ui/sonner";
-import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip";
-import { SPRING_BOUNCE } from "@/config/site";
-import type { ControlConfig } from "@/lib/customizer-config";
-import { formatStars } from "@/lib/github";
-import { parseRepoInput } from "@/lib/parse-repo";
-import { usePrefersReducedMotion } from "@/lib/use-prefers-reduced-motion";
-import registry, { type RegistryEntry } from "@/registry/__index__";
-import { FadeUp } from "../../components/fade-up";
-import { InstallCommand } from "../../components/install-command";
-
-type Orientation = "horizontal" | "vertical";
-
-/** Exactly the success shape returned by GET /api/stargazers. */
-type StargazersPayload = {
- owner: string;
- repo: string;
- totalStars: number;
- truncated: boolean;
- stargazers: { login: string; avatarUrl: string; starredAt: string }[];
-};
-
-const INSTALL = "npx shadcn@latest add remocn/github-stars";
-
-/** 1280×720 ↔ 720×1280 — the two presets the composition + export render at. */
-function dims(orientation: Orientation) {
- return orientation === "vertical"
- ? { width: 720, height: 1280 }
- : { width: 1280, height: 720 };
-}
-
-/** Scalar controls surfaced in the optional Customize panel (no array control). */
-const CUSTOM_CONTROLS: ControlConfig = {
- accentColor: { type: "color", default: "#ffbb00", label: "Accent" },
- theme: {
- type: "select",
- default: "light",
- options: ["light", "dark"],
- label: "Theme",
- },
- speed: {
- type: "number",
- default: 1,
- min: 1,
- max: 4,
- step: 0.25,
- label: "Speed",
- },
-};
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { useStarsTool } from "../hooks/use-stars-tool";
+import { GeneratingView } from "./generating-view";
+import { IdleView } from "./idle-view";
+import { ReadyView } from "./ready-view";
export function StarsTool() {
- const entry = registry["github-stars"];
- const reduced = usePrefersReducedMotion();
-
- // URL state (project rule: nuqs, not raw useSearchParams). `?repo=` reopens a
- // shared link; `?o=h|v` persists the orientation.
- const [repoParam, setRepoParam] = useQueryState("repo", {
- defaultValue: "",
- });
- const [oParam, setOParam] = useQueryState("o", { defaultValue: "h" });
- const orientation: Orientation = oParam === "v" ? "vertical" : "horizontal";
-
- const [status, setStatus] = useState<"idle" | "generating" | "ready">("idle");
- const [inputValue, setInputValue] = useState(repoParam ?? "");
- const [zeroStars, setZeroStars] = useState(false);
- const [data, setData] = useState<StargazersPayload | null>(null);
-
- // Customizer values (scalar inputProps only).
- const [accentColor, setAccentColor] = useState("#ffbb00");
- const [theme, setTheme] = useState<"light" | "dark">("light");
- const [speed, setSpeed] = useState(1);
- const [showCustomizer, setShowCustomizer] = useState(false);
-
- const genAbortRef = useRef<AbortController | null>(null);
-
- const parsed = parseRepoInput(inputValue);
- const canGenerate = parsed !== null;
-
- // ---- generation --------------------------------------------------------
-
- const handleApiError = useCallback((statusCode: number, code?: string) => {
- if (code === "not_found" || statusCode === 404) {
- toast.error("Repository not found — check owner/name");
- } else if (code === "rate_limited" || statusCode === 429) {
- toast.error("GitHub rate limit hit — try again shortly");
- } else if (code === "invalid_repo" || statusCode === 400) {
- toast.error("Invalid repository. Use owner/name");
- } else {
- toast.error("Couldn't reach GitHub — retry");
- }
- }, []);
-
- const runGeneration = useCallback(
- async (rawRepo: string) => {
- const valid = parseRepoInput(rawRepo);
- if (!valid) {
- toast.error("Enter a repo as owner/name");
- return;
- }
- setZeroStars(false);
- setStatus("generating");
-
- const controller = new AbortController();
- genAbortRef.current = controller;
-
- try {
- const res = await fetch(
- `/api/stargazers?repo=${encodeURIComponent(rawRepo)}`,
- { signal: controller.signal },
- );
-
- if (!res.ok) {
- const body = (await res.json().catch(() => null)) as {
- code?: string;
- } | null;
- handleApiError(res.status, body?.code);
- setStatus("idle");
- return;
- }
-
- const json = (await res.json()) as StargazersPayload;
-
- // Zero-star repos come back 200 with an empty list — a friendly inline
- // state, not a hard error.
- if (json.totalStars === 0 || json.stargazers.length === 0) {
- setZeroStars(true);
- setStatus("idle");
- return;
- }
-
- setData(json);
- setStatus("ready");
- } catch (err) {
- // Cancel (AbortController) returns to idle silently.
- if (err instanceof DOMException && err.name === "AbortError") {
- setStatus("idle");
- return;
- }
- toast.error("Couldn't reach GitHub — retry");
- setStatus("idle");
- } finally {
- genAbortRef.current = null;
- }
- },
- [handleApiError],
- );
-
- // Auto-advance past idle when the page loads with a valid `?repo=` (shared link).
- const didAutoStart = useRef(false);
- useEffect(() => {
- if (didAutoStart.current) return;
- didAutoStart.current = true;
- if (repoParam && parseRepoInput(repoParam)) {
- setInputValue(repoParam);
- void runGeneration(repoParam);
- }
- }, [repoParam, runGeneration]);
-
- const handleSubmit = useCallback(() => {
- const value = inputValue.trim();
- if (!parseRepoInput(value)) {
- toast.error("Enter a repo as owner/name");
- return;
- }
- void setRepoParam(value);
- void runGeneration(value);
- }, [inputValue, runGeneration, setRepoParam]);
-
- const cancelGeneration = useCallback(() => {
- genAbortRef.current?.abort();
- setStatus("idle");
- }, []);
-
- // ---- render-on-web export ---------------------------------------------
-
- const [supportsExport, setSupportsExport] = useState(false);
- const [exporting, setExporting] = useState(false);
- const [exportProgress, setExportProgress] = useState(0);
- const exportAbortRef = useRef<AbortController | null>(null);
-
- useEffect(() => {
- // Feature-detect WebCodecs after mount (avoids hydration mismatch).
- setSupportsExport(
- typeof window !== "undefined" &&
- typeof window.VideoEncoder !== "undefined",
- );
- }, []);
-
- const inputProps = useMemo(
- () =>
- data
- ? {
- repo: `${data.owner}/${data.repo}`,
- totalStars: data.totalStars,
- stargazers: data.stargazers,
- orientation,
- accentColor,
- speed,
- theme,
- }
- : null,
- [data, orientation, accentColor, speed, theme],
- );
-
- const handleDownload = useCallback(async () => {
- if (!supportsExport) {
- toast.info("MP4 export needs Chrome or Edge");
- return;
- }
- if (!entry || !data || !inputProps) return;
-
- const controller = new AbortController();
- exportAbortRef.current = controller;
- setExporting(true);
- setExportProgress(0);
-
- try {
- const { renderMediaOnWeb } = await import("@remotion/web-renderer");
- const base = dims(orientation);
- // Render the export cheaper than the 30fps preview: lower resolution + fps.
- // The composition's motion is purely frame/durationInFrames ratios (no
- // spring, never reads fps), so a 24fps/240-frame render is real-time
- // identical to 30fps/300 — only the encode + per-frame cost drops (≈2-3×
- // faster). Raise EXPORT_SCALE/EXPORT_FPS to trade speed for fidelity.
- const EXPORT_SCALE = 0.7;
- const EXPORT_FPS = 24;
- const even = (n: number) =>
- Math.max(2, Math.round((n * EXPORT_SCALE) / 2) * 2);
- const durationInFrames = Math.max(
- 1,
- Math.round(
- (entry.config.durationInFrames / entry.config.fps) * EXPORT_FPS,
- ),
- );
- const { getBlob } = await renderMediaOnWeb({
- composition: {
- id: "github-stars",
- component: entry.Component,
- durationInFrames,
- fps: EXPORT_FPS,
- width: even(base.width),
- height: even(base.height),
- },
- inputProps,
- container: "mp4",
- signal: controller.signal,
- onProgress: ({ progress }) => setExportProgress(progress),
- });
-
- const blob = await getBlob();
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `${data.owner}-${data.repo}-stars.mp4`;
- document.body.appendChild(a);
- a.click();
- a.remove();
- URL.revokeObjectURL(url);
- } catch (err) {
- if (!(err instanceof DOMException && err.name === "AbortError")) {
- // Surface the real cause (e.g. a Remotion version mismatch) instead of
- // swallowing it — the toast stays friendly, the console is diagnosable.
- console.error("[stars] MP4 export failed:", err);
- const detail = err instanceof Error ? err.message : String(err);
- toast.error("Export failed", { description: detail });
- }
- } finally {
- setExporting(false);
- exportAbortRef.current = null;
- }
- }, [supportsExport, entry, data, inputProps, orientation]);
-
- const cancelExport = useCallback(() => {
- exportAbortRef.current?.abort();
- }, []);
-
- // Clear the current repo and return to the idle input so the user can paste a
- // different one. The `didAutoStart` ref stays set, so wiping `?repo=` here does
- // NOT re-trigger the auto-advance (that only runs on a fresh page load).
- const handleReset = useCallback(() => {
- genAbortRef.current?.abort();
- exportAbortRef.current?.abort();
- setData(null);
- setZeroStars(false);
- setInputValue("");
- void setRepoParam(null);
- setStatus("idle");
- }, [setRepoParam]);
-
- const onCustomChange = useCallback((key: string, value: unknown) => {
- if (key === "accentColor") setAccentColor(value as string);
- else if (key === "theme") setTheme(value as "light" | "dark");
- else if (key === "speed") setSpeed(value as number);
- }, []);
+ const vm = useStarsTool();
return (
<TooltipProvider>
@@ -333,431 +20,13 @@ export function StarsTool() {
</div>
<div className="section">
- {status === "idle" && (
- <IdleView
- inputValue={inputValue}
- setInputValue={(v) => {
- setInputValue(v);
- if (zeroStars) setZeroStars(false);
- }}
- onSubmit={handleSubmit}
- canGenerate={canGenerate}
- zeroStars={zeroStars}
- />
- )}
+ {vm.status === "idle" && <IdleView {...vm.idle} />}
- {status === "generating" && (
- <GeneratingView reduced={reduced} onCancel={cancelGeneration} />
- )}
+ {vm.status === "generating" && <GeneratingView {...vm.generating} />}
- {status === "ready" && entry && data && inputProps && (
- // Constant width regardless of orientation — the preview frame stays
- // put when toggling horizontal/vertical (refinement #3).
- <div className="mx-auto max-w-5xl">
- {data.truncated && (
- <Alert className="mb-4">
- <AlertTitle>Showing a sample</AlertTitle>
- <AlertDescription>
- This repo has {formatStars(data.totalStars)} stars — the
- clip animates an evenly sampled subset for a smooth render.
- </AlertDescription>
- </Alert>
- )}
-
- <ReadyView
- entry={entry}
- inputProps={inputProps}
- repo={`${data.owner}/${data.repo}`}
- totalStars={data.totalStars}
- onReset={handleReset}
- orientation={orientation}
- onOrientationChange={(o) =>
- void setOParam(o === "vertical" ? "v" : "h")
- }
- reduced={reduced}
- showCustomizer={showCustomizer}
- onToggleCustomizer={() => setShowCustomizer((s) => !s)}
- customValues={{ accentColor, theme, speed }}
- onCustomChange={onCustomChange}
- supportsExport={supportsExport}
- exporting={exporting}
- exportProgress={exportProgress}
- onDownload={() => void handleDownload()}
- onCancelExport={cancelExport}
- />
- </div>
- )}
+ {vm.status === "ready" && vm.ready && <ReadyView {...vm.ready} />}
</div>
</section>
</TooltipProvider>
);
}
-
-// ---- idle ----------------------------------------------------------------
-
-function IdleView({
- inputValue,
- setInputValue,
- onSubmit,
- canGenerate,
- zeroStars,
-}: {
- inputValue: string;
- setInputValue: (v: string) => void;
- onSubmit: () => void;
- canGenerate: boolean;
- zeroStars: boolean;
-}) {
- return (
- <div className="flex min-h-[70vh] flex-col items-center justify-center text-center">
- <FadeUp delay={0.06} className="flex flex-col items-center">
- <h1 className="max-w-3xl text-balance text-3xl font-semibold leading-[1.1] tracking-tight text-foreground sm:text-4xl md:text-5xl">
- Turn your repo&rsquo;s stars into a video
- </h1>
- </FadeUp>
-
- <FadeUp delay={0.12}>
- <p className="mt-4 max-w-2xl text-balance text-base leading-relaxed text-muted-foreground sm:text-lg">
- Paste a GitHub repo. We fetch every stargazer and animate it into a
- shareable clip.
- </p>
- </FadeUp>
-
- <FadeUp delay={0.18} className="w-full">
- <form
- className="mt-7 flex flex-col items-center gap-3 sm:flex-row sm:justify-center"
- onSubmit={(e) => {
- e.preventDefault();
- onSubmit();
- }}
- >
- <Input
- value={inputValue}
- onChange={(e) => setInputValue(e.target.value)}
- aria-label="GitHub repository"
- placeholder="github.com/owner/repo or owner/repo"
- className="h-11 w-full rounded-full px-5 sm:max-w-sm"
- />
- <Button
- type="submit"
- size="lg"
- disabled={!canGenerate}
- className="h-11 gap-2 rounded-full px-6"
- >
- Generate
- <ArrowRight className="size-4" aria-hidden="true" />
- </Button>
- </form>
- </FadeUp>
- </div>
- );
-}
-
-// ---- generating ----------------------------------------------------------
-
-function GeneratingView({
- reduced,
- onCancel,
-}: {
- reduced: boolean;
- onCancel: () => void;
-}) {
- const [tick, setTick] = useState(0);
- const [progress, setProgress] = useState(0);
-
- useEffect(() => {
- if (reduced) {
- setProgress(90);
- return;
- }
- const id = setInterval(() => {
- setTick((t) => t + Math.floor(Math.random() * 40) + 10);
- setProgress((v) => Math.min(v + (90 - v) * 0.12, 90));
- }, 160);
- return () => clearInterval(id);
- }, [reduced]);
-
- return (
- <div className="flex min-h-[70vh] flex-col items-center justify-center">
- <div className="surface-card mx-auto w-full max-w-xl rounded-3xl p-8">
- {/* Ghost avatar chips streaming in — the "stargazers flying in" tease. */}
- <div className="flex flex-wrap justify-center gap-2">
- {Array.from({ length: 9 }).map((_, i) => (
- <motion.div
- // biome-ignore lint/suspicious/noArrayIndexKey: fixed-length decorative placeholders
- key={i}
- initial={reduced ? false : { opacity: 0, x: -12 }}
- animate={{ opacity: 1, x: 0 }}
- transition={
- reduced ? undefined : { ...SPRING_BOUNCE, delay: i * 0.06 }
- }
- >
- <Skeleton className="size-9 rounded-full" />
- </motion.div>
- ))}
- </div>
-
- <div className="mt-6">
- <Progress value={progress} />
- </div>
-
- <p className="mt-4 text-center text-sm font-medium text-foreground">
- Fetching stargazers…{" "}
- <span className="tabular-nums text-muted-foreground">
- {tick.toLocaleString("en-US")}
- </span>
- </p>
-
- <div className="mt-6 flex justify-center">
- <Button variant="ghost" onClick={onCancel} className="rounded-full">
- Cancel
- </Button>
- </div>
- </div>
- </div>
- );
-}
-
-// ---- ready ---------------------------------------------------------------
-
-function ReadyView({
- entry,
- inputProps,
- repo,
- totalStars,
- onReset,
- orientation,
- onOrientationChange,
- reduced,
- showCustomizer,
- onToggleCustomizer,
- customValues,
- onCustomChange,
- supportsExport,
- exporting,
- exportProgress,
- onDownload,
- onCancelExport,
-}: {
- entry: RegistryEntry;
- inputProps: Record<string, unknown>;
- repo: string;
- totalStars: number;
- onReset: () => void;
- orientation: Orientation;
- onOrientationChange: (o: Orientation) => void;
- reduced: boolean;
- showCustomizer: boolean;
- onToggleCustomizer: () => void;
- customValues: Record<string, unknown>;
- onCustomChange: (key: string, value: unknown) => void;
- supportsExport: boolean;
- exporting: boolean;
- exportProgress: number;
- onDownload: () => void;
- onCancelExport: () => void;
-}) {
- const playerRef = useRef<PlayerRef>(null);
- const [playing, setPlaying] = useState(!reduced);
-
- const togglePlay = useCallback(() => {
- const p = playerRef.current;
- if (!p) return;
- if (p.isPlaying()) {
- p.pause();
- setPlaying(false);
- } else {
- p.play();
- setPlaying(true);
- }
- }, []);
-
- const { width, height } = dims(orientation);
-
- return (
- <motion.div
- initial={reduced ? false : { y: 40, opacity: 0 }}
- animate={{ y: 0, opacity: 1 }}
- transition={{ ...SPRING_BOUNCE, delay: 0.05 }}
- >
- {/* Repo title — centered heading. */}
- <div className="mb-4 text-center">
- <h2 className="truncate text-xl font-semibold tracking-tight text-foreground sm:text-2xl">
- {repo}
- </h2>
- <p className="mt-0.5 text-sm text-muted-foreground">
- {formatStars(totalStars)} stars
- </p>
- </div>
-
- {/* Controls bar */}
- <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <ToggleGroup
- value={[orientation === "vertical" ? "v" : "h"]}
- onValueChange={(value: string[]) => {
- const next = value[0];
- if (next)
- onOrientationChange(next === "v" ? "vertical" : "horizontal");
- }}
- aria-label="Video orientation"
- className="w-full sm:w-auto"
- >
- <ToggleGroupItem value="h" className="flex-1 sm:flex-none">
- Horizontal
- </ToggleGroupItem>
- <ToggleGroupItem value="v" className="flex-1 sm:flex-none">
- Vertical
- </ToggleGroupItem>
- </ToggleGroup>
-
- <Button
- variant="ghost"
- size="sm"
- onClick={onToggleCustomizer}
- aria-expanded={showCustomizer}
- className="gap-2 rounded-full"
- >
- <Settings2 className="size-4" aria-hidden="true" />
- Customize
- </Button>
- </div>
-
- {/* Player card — a fixed 16:9 frame so toggling orientation never reflows
- the page. Vertical renders pillarboxed + centered inside it, while the
- Player still gets the true 720×1280 composition so the exported MP4 is
- genuinely vertical (only the on-page container width stays constant). */}
- <div
- className="group surface-card relative w-full overflow-hidden rounded-2xl shadow-2xl shadow-black/5 sm:rounded-3xl dark:shadow-black/40"
- style={{ aspectRatio: "1280 / 720" }}
- >
- <div className="absolute inset-0 flex items-center justify-center">
- <div
- className="h-full"
- style={
- orientation === "vertical"
- ? {
- height: "100%",
- width: "auto",
- aspectRatio: `${width} / ${height}`,
- }
- : { width: "100%", height: "100%" }
- }
- >
- <Player
- ref={playerRef}
- component={entry.Component}
- inputProps={inputProps}
- durationInFrames={entry.config.durationInFrames}
- fps={entry.config.fps}
- compositionWidth={width}
- compositionHeight={height}
- style={{ width: "100%", height: "100%", display: "block" }}
- autoPlay={!reduced}
- loop
- acknowledgeRemotionLicense
- />
- </div>
- </div>
- <button
- type="button"
- onClick={togglePlay}
- aria-label={playing ? "Pause preview" : "Play preview"}
- className="absolute inset-0 flex items-center justify-center bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
- >
- <span
- aria-hidden
- data-show={!playing}
- className="pointer-events-none flex size-14 items-center justify-center rounded-full bg-background/70 text-foreground opacity-0 backdrop-blur-md transition-opacity duration-200 group-hover:opacity-100 motion-reduce:transition-none data-[show=true]:opacity-100"
- >
- {playing ? (
- <Pause className="size-5" />
- ) : (
- <Play className="size-5 translate-x-0.5" />
- )}
- </span>
- </button>
- </div>
-
- {/* Optional customizer panel (scalar inputProps). */}
- {showCustomizer && (
- <div className="mt-4">
- <ComponentCustomizer
- controls={CUSTOM_CONTROLS}
- values={customValues}
- onChange={onCustomChange}
- />
- </div>
- )}
-
- {/* Footer row: install advert + export. */}
- <div className="mt-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center">
- <InstallCommand command={INSTALL} />
- <Button
- variant="outline"
- size="lg"
- className="h-11 gap-2 rounded-full"
- render={<Link href="/docs/social/github-stars" />}
- >
- <BookOpen className="size-4" aria-hidden="true" />
- View component docs
- </Button>
- </div>
-
- <div className="flex items-center justify-end gap-2">
- <Button
- variant="ghost"
- size="lg"
- onClick={onReset}
- className="gap-2 rounded-full"
- >
- <RotateCcw className="size-4" aria-hidden="true" />
- Change repository
- </Button>
- {exporting ? (
- <div className="flex w-full items-center gap-3 sm:w-72">
- <Progress
- value={Math.round(exportProgress * 100)}
- className="flex-1"
- />
- <Button
- variant="ghost"
- size="icon"
- onClick={onCancelExport}
- aria-label="Cancel export"
- className="rounded-full"
- >
- <X className="size-4" />
- </Button>
- </div>
- ) : supportsExport ? (
- <Button size="lg" onClick={onDownload} className="gap-2 rounded-full">
- <Download className="size-4" aria-hidden="true" />
- Download MP4
- </Button>
- ) : (
- <Tooltip>
- <TooltipTrigger
- render={
- // Not the native `disabled` attribute — a disabled button
- // suppresses hover/click, hiding the tooltip and the info toast.
- // Style it muted and let onDownload surface the Chrome/Edge hint.
- <Button
- size="lg"
- aria-disabled
- onClick={onDownload}
- className="gap-2 rounded-full opacity-50"
- >
- <Download className="size-4" aria-hidden="true" />
- Download MP4
- </Button>
- }
- />
- <TooltipContent>MP4 export needs Chrome or Edge</TooltipContent>
- </Tooltip>
- )}
- </div>
- </div>
- </motion.div>
- );
-}
diff --git a/app/(home)/stars/components/truncated-notice.tsx b/app/(home)/stars/components/truncated-notice.tsx
new file mode 100644
index 00000000..91553c36
--- /dev/null
+++ b/app/(home)/stars/components/truncated-notice.tsx
@@ -0,0 +1,23 @@
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { formatStars } from "@/lib/github";
+
+/** Inline "we sampled a subset" notice shown for very-high-star repos. */
+export function TruncatedNotice({
+ truncated,
+ totalStars,
+}: {
+ truncated: boolean;
+ totalStars: number;
+}) {
+ if (!truncated) return null;
+
+ return (
+ <Alert className="mb-4">
+ <AlertTitle>Showing a sample</AlertTitle>
+ <AlertDescription>
+ This repo has {formatStars(totalStars)} stars — the clip animates an
+ evenly sampled subset for a smooth render.
+ </AlertDescription>
+ </Alert>
+ );
+}
diff --git a/app/(home)/stars/hooks/use-generation-ticker.ts b/app/(home)/stars/hooks/use-generation-ticker.ts
new file mode 100644
index 00000000..ee1b008b
--- /dev/null
+++ b/app/(home)/stars/hooks/use-generation-ticker.ts
@@ -0,0 +1,27 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+/**
+ * The fake "Fetching… N" progress ticker for the generating view. Eases a
+ * progress bar toward 90% and counts a jittery stargazer tally, or snaps
+ * straight to 90% when reduced motion is requested.
+ */
+export function useGenerationTicker(reduced: boolean) {
+ const [count, setCount] = useState(0);
+ const [progress, setProgress] = useState(0);
+
+ useEffect(() => {
+ if (reduced) {
+ setProgress(90);
+ return;
+ }
+ const id = setInterval(() => {
+ setCount((t) => t + Math.floor(Math.random() * 40) + 10);
+ setProgress((v) => Math.min(v + (90 - v) * 0.12, 90));
+ }, 160);
+ return () => clearInterval(id);
+ }, [reduced]);
+
+ return { progress, count };
+}
diff --git a/app/(home)/stars/hooks/use-mp4-export.ts b/app/(home)/stars/hooks/use-mp4-export.ts
new file mode 100644
index 00000000..3327d094
--- /dev/null
+++ b/app/(home)/stars/hooks/use-mp4-export.ts
@@ -0,0 +1,80 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { toast } from "sonner";
+import type { RegistryEntry } from "@/registry/__index__";
+import { downloadBlob } from "../lib/download";
+import { buildExportComposition } from "../lib/export-settings";
+import type { GitHubStarsInputProps, Orientation } from "../lib/types";
+
+type DownloadArgs = {
+ entry: RegistryEntry;
+ inputProps: GitHubStarsInputProps;
+ orientation: Orientation;
+ filename: string;
+};
+
+/**
+ * Owns the WebCodecs MP4 export: feature-detect, progress, the export
+ * AbortController, and the dynamic web-renderer import + blob download.
+ */
+export function useMp4Export() {
+ const [supportsExport, setSupportsExport] = useState(false);
+ const [exporting, setExporting] = useState(false);
+ const [progress, setProgress] = useState(0);
+ const exportAbortRef = useRef<AbortController | null>(null);
+
+ useEffect(() => {
+ // Feature-detect WebCodecs after mount (avoids hydration mismatch).
+ setSupportsExport(
+ typeof window !== "undefined" &&
+ typeof window.VideoEncoder !== "undefined",
+ );
+ }, []);
+
+ const download = useCallback(
+ async ({ entry, inputProps, orientation, filename }: DownloadArgs) => {
+ if (!supportsExport) {
+ toast.info("MP4 export needs Chrome or Edge");
+ return;
+ }
+
+ const controller = new AbortController();
+ exportAbortRef.current = controller;
+ setExporting(true);
+ setProgress(0);
+
+ try {
+ const { renderMediaOnWeb } = await import("@remotion/web-renderer");
+ const { getBlob } = await renderMediaOnWeb({
+ composition: buildExportComposition(entry, orientation),
+ inputProps,
+ container: "mp4",
+ signal: controller.signal,
+ onProgress: ({ progress }) => setProgress(progress),
+ });
+
+ const blob = await getBlob();
+ downloadBlob(blob, filename);
+ } catch (err) {
+ if (!(err instanceof DOMException && err.name === "AbortError")) {
+ // Surface the real cause (e.g. a Remotion version mismatch) instead of
+ // swallowing it — the toast stays friendly, the console is diagnosable.
+ console.error("[stars] MP4 export failed:", err);
+ const detail = err instanceof Error ? err.message : String(err);
+ toast.error("Export failed", { description: detail });
+ }
+ } finally {
+ setExporting(false);
+ exportAbortRef.current = null;
+ }
+ },
+ [supportsExport],
+ );
+
+ const cancel = useCallback(() => {
+ exportAbortRef.current?.abort();
+ }, []);
+
+ return { supportsExport, exporting, progress, download, cancel };
+}
diff --git a/app/(home)/stars/hooks/use-orientation.ts b/app/(home)/stars/hooks/use-orientation.ts
new file mode 100644
index 00000000..bc62b09e
--- /dev/null
+++ b/app/(home)/stars/hooks/use-orientation.ts
@@ -0,0 +1,27 @@
+"use client";
+
+import { useQueryState } from "nuqs";
+import { useCallback } from "react";
+import {
+ orientationToParam,
+ paramToOrientation,
+} from "../lib/dims";
+import type { Orientation } from "../lib/types";
+
+/**
+ * Wraps the nuqs `?o=h|v` query state (project rule: nuqs, not raw
+ * useSearchParams). `?o=h|v` persists the orientation across reloads.
+ */
+export function useOrientation() {
+ const [oParam, setOParam] = useQueryState("o", { defaultValue: "h" });
+ const orientation = paramToOrientation(oParam);
+
+ const setOrientation = useCallback(
+ (o: Orientation) => {
+ void setOParam(orientationToParam(o));
+ },
+ [setOParam],
+ );
+
+ return { orientation, setOrientation };
+}
diff --git a/app/(home)/stars/hooks/use-player-controls.ts b/app/(home)/stars/hooks/use-player-controls.ts
new file mode 100644
index 00000000..e78f6bc4
--- /dev/null
+++ b/app/(home)/stars/hooks/use-player-controls.ts
@@ -0,0 +1,24 @@
+"use client";
+
+import type { PlayerRef } from "@remotion/player";
+import { useCallback, useRef, useState } from "react";
+
+/** Owns the Remotion PlayerRef play/pause toggle + the mirrored playing flag. */
+export function usePlayerControls(initialPlaying: boolean) {
+ const ref = useRef<PlayerRef>(null);
+ const [playing, setPlaying] = useState(initialPlaying);
+
+ const togglePlay = useCallback(() => {
+ const p = ref.current;
+ if (!p) return;
+ if (p.isPlaying()) {
+ p.pause();
+ setPlaying(false);
+ } else {
+ p.play();
+ setPlaying(true);
+ }
+ }, []);
+
+ return { ref, playing, togglePlay };
+}
diff --git a/app/(home)/stars/hooks/use-stargazers.ts b/app/(home)/stars/hooks/use-stargazers.ts
new file mode 100644
index 00000000..bb030f48
--- /dev/null
+++ b/app/(home)/stars/hooks/use-stargazers.ts
@@ -0,0 +1,88 @@
+"use client";
+
+import { useCallback, useRef, useState } from "react";
+import { toast } from "sonner";
+import { parseRepoInput } from "@/lib/parse-repo";
+import { messageForApiError } from "../lib/api-errors";
+import { fetchStargazers, StargazersApiError } from "../lib/api";
+import type { StarsStatus, StargazersPayload } from "../lib/types";
+
+/**
+ * Owns the generation state machine: status (idle/generating/ready), the
+ * fetched payload, the zero-star inline flag, and the in-flight AbortController.
+ */
+export function useStargazers() {
+ const [status, setStatus] = useState<StarsStatus>("idle");
+ const [data, setData] = useState<StargazersPayload | null>(null);
+ const [zeroStars, setZeroStars] = useState(false);
+ const genAbortRef = useRef<AbortController | null>(null);
+
+ const generate = useCallback(async (rawRepo: string) => {
+ const valid = parseRepoInput(rawRepo);
+ if (!valid) {
+ toast.error("Enter a repo as owner/name");
+ return;
+ }
+ setZeroStars(false);
+ setStatus("generating");
+
+ const controller = new AbortController();
+ genAbortRef.current = controller;
+
+ try {
+ const json = await fetchStargazers(rawRepo, controller.signal);
+
+ // Zero-star repos come back 200 with an empty list — a friendly inline
+ // state, not a hard error.
+ if (json.totalStars === 0 || json.stargazers.length === 0) {
+ setZeroStars(true);
+ setStatus("idle");
+ return;
+ }
+
+ setData(json);
+ setStatus("ready");
+ } catch (err) {
+ // Cancel (AbortController) returns to idle silently.
+ if (err instanceof DOMException && err.name === "AbortError") {
+ setStatus("idle");
+ return;
+ }
+ if (err instanceof StargazersApiError) {
+ toast.error(messageForApiError(err.code, err.status));
+ setStatus("idle");
+ return;
+ }
+ toast.error("Couldn't reach GitHub — retry");
+ setStatus("idle");
+ } finally {
+ genAbortRef.current = null;
+ }
+ }, []);
+
+ const cancel = useCallback(() => {
+ genAbortRef.current?.abort();
+ setStatus("idle");
+ }, []);
+
+ const reset = useCallback(() => {
+ genAbortRef.current?.abort();
+ setData(null);
+ setZeroStars(false);
+ setStatus("idle");
+ }, []);
+
+ const clearZeroStars = useCallback(() => {
+ setZeroStars(false);
+ }, []);
+
+ return {
+ status,
+ data,
+ zeroStars,
+ generate,
+ cancel,
+ reset,
+ clearZeroStars,
+ };
+}
diff --git a/app/(home)/stars/hooks/use-stars-customizer.ts b/app/(home)/stars/hooks/use-stars-customizer.ts
new file mode 100644
index 00000000..2d1a8b9c
--- /dev/null
+++ b/app/(home)/stars/hooks/use-stars-customizer.ts
@@ -0,0 +1,31 @@
+"use client";
+
+import { useCallback, useMemo, useState } from "react";
+
+/**
+ * Owns the optional Customize panel: scalar inputProps (accent/theme/speed)
+ * plus the panel's open/closed visibility.
+ */
+export function useStarsCustomizer() {
+ const [accentColor, setAccentColor] = useState("#ffbb00");
+ const [theme, setTheme] = useState<"light" | "dark">("light");
+ const [speed, setSpeed] = useState(1);
+ const [showCustomizer, setShowCustomizer] = useState(false);
+
+ const onChange = useCallback((key: string, value: unknown) => {
+ if (key === "accentColor") setAccentColor(value as string);
+ else if (key === "theme") setTheme(value as "light" | "dark");
+ else if (key === "speed") setSpeed(value as number);
+ }, []);
+
+ const toggleCustomizer = useCallback(() => {
+ setShowCustomizer((s) => !s);
+ }, []);
+
+ const values = useMemo(
+ () => ({ accentColor, theme, speed }),
+ [accentColor, theme, speed],
+ );
+
+ return { values, onChange, showCustomizer, toggleCustomizer };
+}
diff --git a/app/(home)/stars/hooks/use-stars-tool.ts b/app/(home)/stars/hooks/use-stars-tool.ts
new file mode 100644
index 00000000..cf45bea4
--- /dev/null
+++ b/app/(home)/stars/hooks/use-stars-tool.ts
@@ -0,0 +1,148 @@
+"use client";
+
+import { useQueryState } from "nuqs";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { parseRepoInput } from "@/lib/parse-repo";
+import { usePrefersReducedMotion } from "@/lib/use-prefers-reduced-motion";
+import registry from "@/registry/__index__";
+import type { GitHubStarsInputProps } from "../lib/types";
+import { useMp4Export } from "./use-mp4-export";
+import { useOrientation } from "./use-orientation";
+import { useStargazers } from "./use-stargazers";
+import { useStarsCustomizer } from "./use-stars-customizer";
+
+/**
+ * THE ORCHESTRATOR. Composes orientation + stargazers + customizer + export
+ * into a single view-model the render-only component tree spreads. Owns the
+ * input value, the `?repo=` query state, the auto-advance guard, submit/reset,
+ * and the memoized inputProps.
+ */
+export function useStarsTool() {
+ const entry = registry["github-stars"];
+ const reduced = usePrefersReducedMotion();
+
+ // URL state (project rule: nuqs, not raw useSearchParams). `?repo=` reopens a
+ // shared link; `?o=h|v` persists the orientation.
+ const [repoParam, setRepoParam] = useQueryState("repo", {
+ defaultValue: "",
+ });
+ const { orientation, setOrientation } = useOrientation();
+
+ const [inputValue, setInputValue] = useState(repoParam ?? "");
+
+ const stargazers = useStargazers();
+ const customizer = useStarsCustomizer();
+ const mp4 = useMp4Export();
+
+ const { data, zeroStars, generate, clearZeroStars } = stargazers;
+
+ const canGenerate = parseRepoInput(inputValue) !== null;
+
+ // ---- generation --------------------------------------------------------
+
+ const onInputChange = useCallback(
+ (v: string) => {
+ setInputValue(v);
+ if (zeroStars) clearZeroStars();
+ },
+ [zeroStars, clearZeroStars],
+ );
+
+ // Auto-advance past idle when the page loads with a valid `?repo=` (shared link).
+ const didAutoStart = useRef(false);
+ useEffect(() => {
+ if (didAutoStart.current) return;
+ didAutoStart.current = true;
+ if (repoParam && parseRepoInput(repoParam)) {
+ setInputValue(repoParam);
+ void generate(repoParam);
+ }
+ }, [repoParam, generate]);
+
+ const handleSubmit = useCallback(() => {
+ const value = inputValue.trim();
+ if (!parseRepoInput(value)) {
+ toast.error("Enter a repo as owner/name");
+ return;
+ }
+ void setRepoParam(value);
+ void generate(value);
+ }, [inputValue, generate, setRepoParam]);
+
+ // Clear the current repo and return to the idle input so the user can paste a
+ // different one. The `didAutoStart` ref stays set, so wiping `?repo=` here does
+ // NOT re-trigger the auto-advance (that only runs on a fresh page load).
+ const handleReset = useCallback(() => {
+ stargazers.reset();
+ mp4.cancel();
+ setInputValue("");
+ void setRepoParam(null);
+ }, [stargazers, mp4, setRepoParam]);
+
+ // ---- inputProps + export ----------------------------------------------
+
+ const inputProps = useMemo<GitHubStarsInputProps | null>(
+ () =>
+ data
+ ? {
+ repo: `${data.owner}/${data.repo}`,
+ totalStars: data.totalStars,
+ stargazers: data.stargazers,
+ orientation,
+ accentColor: customizer.values.accentColor,
+ speed: customizer.values.speed,
+ theme: customizer.values.theme,
+ }
+ : null,
+ [data, orientation, customizer.values],
+ );
+
+ const handleDownload = useCallback(() => {
+ if (!entry || !data || !inputProps) return;
+ void mp4.download({
+ entry,
+ inputProps,
+ orientation,
+ filename: `${data.owner}-${data.repo}-stars.mp4`,
+ });
+ }, [entry, data, inputProps, orientation, mp4]);
+
+ return {
+ status: stargazers.status,
+ idle: {
+ inputValue,
+ onInputChange,
+ onSubmit: handleSubmit,
+ canGenerate,
+ zeroStars,
+ },
+ generating: {
+ reduced,
+ onCancel: stargazers.cancel,
+ },
+ ready:
+ entry && data && inputProps
+ ? {
+ entry,
+ inputProps,
+ repo: `${data.owner}/${data.repo}`,
+ totalStars: data.totalStars,
+ truncated: data.truncated,
+ reduced,
+ orientation,
+ onOrientationChange: setOrientation,
+ onReset: handleReset,
+ showCustomizer: customizer.showCustomizer,
+ onToggleCustomizer: customizer.toggleCustomizer,
+ customValues: customizer.values,
+ onCustomChange: customizer.onChange,
+ supportsExport: mp4.supportsExport,
+ exporting: mp4.exporting,
+ exportProgress: mp4.progress,
+ onDownload: handleDownload,
+ onCancelExport: mp4.cancel,
+ }
+ : null,
+ };
+}
diff --git a/app/(home)/stars/lib/api-errors.ts b/app/(home)/stars/lib/api-errors.ts
new file mode 100644
index 00000000..88b2ae2c
--- /dev/null
+++ b/app/(home)/stars/lib/api-errors.ts
@@ -0,0 +1,13 @@
+/** Map an /api/stargazers error (code + HTTP status) to a friendly toast string. */
+export function messageForApiError(code?: string, status?: number): string {
+ if (code === "not_found" || status === 404) {
+ return "Repository not found — check owner/name";
+ }
+ if (code === "rate_limited" || status === 429) {
+ return "GitHub rate limit hit — try again shortly";
+ }
+ if (code === "invalid_repo" || status === 400) {
+ return "Invalid repository. Use owner/name";
+ }
+ return "Couldn't reach GitHub — retry";
+}
diff --git a/app/(home)/stars/lib/api.ts b/app/(home)/stars/lib/api.ts
new file mode 100644
index 00000000..b0f9e590
--- /dev/null
+++ b/app/(home)/stars/lib/api.ts
@@ -0,0 +1,40 @@
+import type { StargazersPayload } from "./types";
+
+/** Carries the GitHub-side `code` + HTTP `status` so callers can map a message. */
+export class StargazersApiError extends Error {
+ code?: string;
+ status: number;
+
+ constructor(status: number, code?: string) {
+ super(`stargazers request failed (${status})`);
+ this.name = "StargazersApiError";
+ this.status = status;
+ this.code = code;
+ }
+}
+
+/**
+ * Fetch the stargazers payload for a raw repo reference.
+ *
+ * Throws {@link StargazersApiError} on a non-OK response. Returns the payload
+ * unmodified on success — including the zero-star 200 case, so the caller can
+ * branch into a friendly inline state rather than a hard error.
+ */
+export async function fetchStargazers(
+ rawRepo: string,
+ signal: AbortSignal,
+): Promise<StargazersPayload> {
+ const res = await fetch(
+ `/api/stargazers?repo=${encodeURIComponent(rawRepo)}`,
+ { signal },
+ );
+
+ if (!res.ok) {
+ const body = (await res.json().catch(() => null)) as {
+ code?: string;
+ } | null;
+ throw new StargazersApiError(res.status, body?.code);
+ }
+
+ return (await res.json()) as StargazersPayload;
+}
diff --git a/app/(home)/stars/lib/constants.ts b/app/(home)/stars/lib/constants.ts
new file mode 100644
index 00000000..2d79562f
--- /dev/null
+++ b/app/(home)/stars/lib/constants.ts
@@ -0,0 +1,24 @@
+import type { ControlConfig } from "@/lib/customizer-config";
+
+export const INSTALL_COMMAND = "npx shadcn@latest add remocn/github-stars";
+
+export const DOCS_HREF = "/docs/social/github-stars";
+
+/** Scalar controls surfaced in the optional Customize panel (no array control). */
+export const CUSTOM_CONTROLS: ControlConfig = {
+ accentColor: { type: "color", default: "#ffbb00", label: "Accent" },
+ theme: {
+ type: "select",
+ default: "light",
+ options: ["light", "dark"],
+ label: "Theme",
+ },
+ speed: {
+ type: "number",
+ default: 1,
+ min: 1,
+ max: 4,
+ step: 0.25,
+ label: "Speed",
+ },
+};
diff --git a/app/(home)/stars/lib/dims.ts b/app/(home)/stars/lib/dims.ts
new file mode 100644
index 00000000..4dc06e26
--- /dev/null
+++ b/app/(home)/stars/lib/dims.ts
@@ -0,0 +1,18 @@
+import type { Orientation } from "./types";
+
+/** 1280×720 ↔ 720×1280 — the two presets the composition + export render at. */
+export function dims(orientation: Orientation) {
+ return orientation === "vertical"
+ ? { width: 720, height: 1280 }
+ : { width: 1280, height: 720 };
+}
+
+/** Orientation → the compact `?o=` query value. */
+export function orientationToParam(o: Orientation): "h" | "v" {
+ return o === "vertical" ? "v" : "h";
+}
+
+/** `?o=` query value → orientation (anything but "v" is horizontal). */
+export function paramToOrientation(p: string): Orientation {
+ return p === "v" ? "vertical" : "horizontal";
+}
diff --git a/app/(home)/stars/lib/download.ts b/app/(home)/stars/lib/download.ts
new file mode 100644
index 00000000..0f0fdf14
--- /dev/null
+++ b/app/(home)/stars/lib/download.ts
@@ -0,0 +1,11 @@
+/** Trigger a browser download for an in-memory blob via a transient anchor. */
+export function downloadBlob(blob: Blob, filename: string) {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+}
diff --git a/app/(home)/stars/lib/export-settings.ts b/app/(home)/stars/lib/export-settings.ts
new file mode 100644
index 00000000..b220365a
--- /dev/null
+++ b/app/(home)/stars/lib/export-settings.ts
@@ -0,0 +1,35 @@
+import type { RegistryEntry } from "@/registry/__index__";
+import { dims } from "./dims";
+import type { Orientation } from "./types";
+
+// Render the export cheaper than the 30fps preview: lower resolution + fps.
+// The composition's motion is purely frame/durationInFrames ratios (no
+// spring, never reads fps), so a 24fps/240-frame render is real-time
+// identical to 30fps/300 — only the encode + per-frame cost drops (≈2-3×
+// faster). Raise EXPORT_SCALE/EXPORT_FPS to trade speed for fidelity.
+export const EXPORT_SCALE = 0.7;
+export const EXPORT_FPS = 24;
+
+const even = (n: number) => Math.max(2, Math.round((n * EXPORT_SCALE) / 2) * 2);
+
+/** Pure composition descriptor for the web-renderer MP4 export. */
+export function buildExportComposition(
+ entry: RegistryEntry,
+ orientation: Orientation,
+) {
+ const base = dims(orientation);
+ const durationInFrames = Math.max(
+ 1,
+ Math.round(
+ (entry.config.durationInFrames / entry.config.fps) * EXPORT_FPS,
+ ),
+ );
+ return {
+ id: "github-stars",
+ component: entry.Component,
+ durationInFrames,
+ fps: EXPORT_FPS,
+ width: even(base.width),
+ height: even(base.height),
+ };
+}
diff --git a/app/(home)/stars/lib/types.ts b/app/(home)/stars/lib/types.ts
new file mode 100644
index 00000000..c1e86635
--- /dev/null
+++ b/app/(home)/stars/lib/types.ts
@@ -0,0 +1,30 @@
+export type Orientation = "horizontal" | "vertical";
+
+export type StarsStatus = "idle" | "generating" | "ready";
+
+/** A single stargazer as surfaced by GET /api/stargazers. */
+export type Stargazer = {
+ login: string;
+ avatarUrl: string;
+ starredAt: string;
+};
+
+/** Exactly the success shape returned by GET /api/stargazers. */
+export type StargazersPayload = {
+ owner: string;
+ repo: string;
+ totalStars: number;
+ truncated: boolean;
+ stargazers: Stargazer[];
+};
+
+/** JSON-serializable props fed to the GitHubStars composition + export. */
+export type GitHubStarsInputProps = {
+ repo: string;
+ totalStars: number;
+ stargazers: Stargazer[];
+ orientation: Orientation;
+ accentColor: string;
+ speed: number;
+ theme: "light" | "dark";
+};