The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Galleries: cards that differ at rest, categories take turns, keyboard-safe Show more
Claude1783c09628c1
diff --git a/src/app/(studio)/settings/page.tsx b/src/app/(studio)/settings/page.tsxindex 9239f9d9..4a17b9f6 100644--- a/src/app/(studio)/settings/page.tsx+++ b/src/app/(studio)/settings/page.tsx@@ -1,6 +1,5 @@import type { Metadata } from "next";-import { PageShell } from "@/components/page-shell";-import { PageHeader } from "@/components/preset-gallery";+import { PageHeader, PageShell } from "@/components/page-shell";import { SettingsForm } from "@/components/settings-form";export const metadata: Metadata = { title: "Settings" };diff --git a/src/app/globals.css b/src/app/globals.cssindex c72135e5..f4cf522a 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -365,10 +365,28 @@scale(calc(1 + var(--pv-base, 0) + (var(--pv-zoom, 0) + var(--pv-dolly, 0) * var(--d)) * var(--pv-t)))rotate(calc(var(--pv-roll, 0) * var(--pv-t) * 1deg));}+/* Each preset's own hue recolors the still (blend: color keeps its light and shade), so+ * neighbouring cards on the same still read as different looks. */.pv-tint {- inset: 0; z-index: 6; mix-blend-mode: soft-light; opacity: 0.55;- background: linear-gradient(135deg, oklch(0.78 0.15 var(--pv-hue, 282)), oklch(0.5 0.2 calc(var(--pv-hue, 282) + 50)));+ inset: 0; z-index: 1; mix-blend-mode: color; opacity: 0.42;+ background: linear-gradient(135deg, oklch(0.72 0.16 var(--pv-hue, 282)), oklch(0.55 0.2 calc(var(--pv-hue, 282) + 50)));}+.pv[data-flip] .pv-shake { scale: -1 1; }++/* A camera move rests partway in (the still already shows the move's framing), and plays on from+ * there; its line diagram (move-glyphs.ts) says which move it is until it plays. */+.pv[data-profile] .pv-cam { --pv-t: 0.5; }+.pv:is([data-profile="crash"], [data-profile="yoyo"], [data-profile="whip"]) .pv-cam { --pv-t: 0; }+.pv[data-profile="crash-rev"] .pv-cam { --pv-t: 1; }+.pv[data-profile="loop"] .pv-cam { --pv-t: 0.06; }+.pv-glyph {+ position: absolute; left: 50%; top: 50%; z-index: 7; width: 42%; translate: -50% -50%;+ fill: none; stroke: #fff; stroke-width: 1.75px; stroke-linecap: round; stroke-linejoin: round;+ filter: drop-shadow(0 1px 1.5px oklch(0 0 0 / 0.55)); opacity: 0.92; transition: opacity 220ms ease;+}+.pv-glyph path { vector-effect: non-scaling-stroke; }+.pv-glyph [data-dashed] { stroke-dasharray: 2.5 3; opacity: 0.75; }+.pv[data-playing] .pv-glyph { opacity: 0; }.pv-fx { z-index: 5; }.pv[data-playing] .pv-layer, .pv[data-playing] .pv-cam { will-change: transform; }@@ -382,6 +400,9 @@.pv[data-playing][data-profile="yoyo"] .pv-cam { animation: pv-t-yoyo var(--pv-dur, 3s) ease-in-out infinite; }.pv[data-playing][data-profile="whip"] .pv-cam { animation: pv-t-whip var(--pv-dur, 2.6s) ease-in-out infinite; }.pv[data-playing]:not([data-profile]) .pv-cam { animation: none; }+/* Play on from the resting frame instead of jumping back to the start. */+.pv[data-playing]:is([data-profile="ease"], [data-profile="ease-rev"], [data-profile="slow"]) .pv-cam { animation-delay: calc(var(--pv-dur, 3s) * -0.5); }+.pv[data-playing][data-profile="loop"] .pv-cam { animation-delay: calc(var(--pv-dur, 3s) * -0.06); }@keyframes pv-t-up { from { --pv-t: 0; } to { --pv-t: 1; } }@keyframes pv-t-down { from { --pv-t: 1; } to { --pv-t: 0; } }@keyframes pv-t-crash {@@ -492,8 +513,10 @@.pv[data-playing][data-fx="lightning"] .pv-flash, .pv[data-playing][data-fx="explode"] .pv-flash { animation: pv-strike 2.2s steps(1) infinite; }@keyframes pv-strike { 0%, 100% { opacity: 0; } 8% { opacity: 1; } 12% { opacity: 0; } 16% { opacity: 0.8; } 22% { opacity: 0; } }+/* At rest the burst shows near its peak, placed by the preset's hue so neighbouring blasts differ. */.pv-burst {- left: 50%; top: 52%; width: 120%; aspect-ratio: 1; translate: -50% -50%; scale: 0.55; border-radius: 50%;+ left: calc(50% + sin(var(--pv-hue, 0) * 1deg) * 22%); top: calc(50% + cos(var(--pv-hue, 0) * 3deg) * 12%);+ width: 120%; aspect-ratio: 1; translate: -50% -50%; scale: 0.72; border-radius: 50%;background: radial-gradient(circle, #fffbe0 0, #ffd166 18%, #ff7b2e 36%, oklch(0.5 0.2 30 / 0.6) 52%, transparent 66%);mix-blend-mode: screen; opacity: 0.85;}@@ -585,6 +608,14 @@.pv[data-playing][data-fx="play"] .pv-cam { animation: pv-push 3.2s ease-in-out infinite alternate; }@keyframes pv-progress { from { --p: 0%; } to { --p: 100%; } }+/* Cracked glass: drawn at rest, the cracks race out from the impact when playing. */+.pv-crack { position: absolute; inset: 0; width: 100%; height: 100%; fill: oklch(1 0 0 / 0.9); stroke: oklch(1 0 0 / 0.88); stroke-width: 1.3px; stroke-linecap: round; stroke-linejoin: round; filter: drop-shadow(0 0 1px oklch(0 0 0 / 0.7)); }+.pv-crack path { fill: none; vector-effect: non-scaling-stroke; stroke-dasharray: 220; stroke-dashoffset: 0; }+.pv[data-playing] .pv-crack path { animation: pv-crack 2.2s cubic-bezier(0.2, 0.8, 0.3, 1) infinite; }+.pv[data-playing][data-fx="crack"] .pv-flash { animation: pv-strike 2.2s steps(1) infinite; }+.pv[data-playing][data-fx="crack"] .pv-shake { animation: pv-impact 2.2s linear infinite; }+@keyframes pv-crack { 0%, 8% { stroke-dashoffset: 220; } 40%, 100% { stroke-dashoffset: 0; } }+.pv[data-playing][data-fx="pop"] .pv-cam { animation: pv-pop 1.6s cubic-bezier(0.3, 1.4, 0.5, 1) infinite; }.pv[data-playing][data-fx="morph"] .pv-cam, .pv[data-playing][data-fx="glow"] .pv-cam { animation: pv-push 3s ease-in-out infinite alternate; }@keyframes pv-pop { 0%, 100% { scale: 1; } 30% { scale: 1.1; } 55% { scale: 1.03; } }diff --git a/src/components/cinema/projects-view.tsx b/src/components/cinema/projects-view.tsxindex cc6d7260..50d5bdbf 100644--- a/src/components/cinema/projects-view.tsx+++ b/src/components/cinema/projects-view.tsx@@ -6,7 +6,7 @@ import { useRouter } from "next/navigation";import { useState } from "react";import { toast } from "sonner";import { PageShell } from "@/components/page-shell";-import { PageHeader } from "@/components/preset-gallery";+import { PageHeader } from "@/components/page-shell";import { Button } from "@/components/ui/button";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Skeleton } from "@/components/ui/skeleton";diff --git a/src/components/models-table.tsx b/src/components/models-table.tsxindex e67bf297..482ee632 100644--- a/src/components/models-table.tsx+++ b/src/components/models-table.tsx@@ -1,7 +1,7 @@"use client";import { Cloud, Cpu, Info, Search } from "lucide-react";-import { memo, useDeferredValue, useMemo, useState } from "react";+import { memo, useDeferredValue, useMemo, useRef, useState } from "react";import { useProgressive } from "@/components/use-progressive";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { useEngine } from "@/lib/api";@@ -105,7 +105,8 @@ export function ModelsTable({ models }: { models: ModelRow[] }) {[index, engine, kind, term],);// 40 rows in the page's HTML, the rest as you scroll.- const { shown, hasMore, more, sentinel, left } = useProgressive(list.length, `${engine}|${kind}|${term}`, 40, 60);+ const { shown, hasMore, moreFrom, sentinel, left } = useProgressive(list.length, `${engine}|${kind}|${term}`, 40, 60);+ const rows = useRef<HTMLTableSectionElement>(null);return (<div className="space-y-4"><div className="flex flex-col gap-2 lg:flex-row lg:items-center">@@ -150,7 +151,7 @@ export function ModelsTable({ models }: { models: ModelRow[] }) {</th></tr></thead>- <tbody className="divide-y">+ <tbody ref={rows} className="divide-y">{list.slice(0, shown).map((m) => (<Row key={m.id} m={m} />))}@@ -161,7 +162,7 @@ export function ModelsTable({ models }: { models: ModelRow[] }) {<buttonref={sentinel}type="button"- onClick={more}+ onClick={(e) => moreFrom(e, rows.current)}className="h-9 rounded-full border bg-background px-4 text-[13px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground">Show more · {left} leftdiff --git a/src/components/preset-gallery.tsx b/src/components/preset-gallery.tsxindex 4b1566f9..33dfe530 100644--- a/src/components/preset-gallery.tsx+++ b/src/components/preset-gallery.tsx@@ -3,17 +3,14 @@import Link from "next/link";import { Cloud, Cpu, Lock, Search, Sparkles, X } from "lucide-react";import { memo, useDeferredValue, useEffect, useMemo, useRef, useState } from "react";-import { PageHeader } from "@/components/page-shell";import { PRESET_ICONS } from "@/components/preset-icons";import { PresetPreview, usePreviewPlayback } from "@/components/preset-preview";import { GALLERY_GRID } from "@/components/skeletons";import { useProgressive } from "@/components/use-progressive";import { useEngineMode } from "@/lib/api";-import { searchText, type PresetCardData } from "@/lib/preset-cards";+import { interleaveByCategory, previewFlip, searchText, type PresetCardData } from "@/lib/preset-cards";import { cn } from "@/lib/utils";-export { PageHeader };-/** A tiny label shown on hover/focus (CSS only: a gallery has hundreds of these). */function EngineChip({ engine }: { engine: "cloud" | "open" }) {const label = engine === "cloud" ? "Runs on cloud models" : "Runs on open-source models";@@ -31,7 +28,18 @@ function EngineChip({ engine }: { engine: "cloud" | "open" }) {);}-export const PresetCard = memo(function PresetCard({ preset, href, compact }: { preset: PresetCardData; href: string; compact?: boolean }) {+export const PresetCard = memo(function PresetCard({+ preset,+ href,+ compact,+ engine,+}: {+ preset: PresetCardData;+ href: string;+ compact?: boolean;+ /** Settings → Engine mode: with one engine locked in, the other's chip would suggest a route the user turned off. */+ engine?: "cloud" | "open";+}) {const Icon = PRESET_ICONS[preset.icon] ?? Sparkles;const { ref, playing, handlers } = usePreviewPlayback<HTMLAnchorElement>(preset.id);return (@@ -42,14 +50,14 @@ export const PresetCard = memo(function PresetCard({ preset, href, compact }: {className="group/card flex min-w-0 flex-col gap-2 rounded-xl p-1.5 transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"><div className="relative aspect-[4/3] overflow-hidden rounded-lg bg-muted">- <PresetPreview preview={preset.preview} hue={preset.hue} playing={playing} />+ <PresetPreview preview={preset.preview} hue={preset.hue} playing={playing} flip={previewFlip(preset)} /><span className="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-gradient-to-t from-black/40 to-transparent" /><span className="pointer-events-none absolute bottom-1.5 left-1.5 grid size-6 place-items-center rounded-md bg-black/30 text-white"><Icon className="size-3.5" /></span><span className="pointer-events-none absolute right-1.5 bottom-1.5 flex gap-1">- {preset.cloud && <EngineChip engine="cloud" />}- {preset.open && <EngineChip engine="open" />}+ {preset.cloud && engine !== "open" && <EngineChip engine="cloud" />}+ {preset.open && engine !== "cloud" && <EngineChip engine="open" />}</span>{preset.top && (<span className="absolute top-1.5 left-1.5 rounded-[4px] bg-highlight px-1 text-[10px] font-semibold text-highlight-foreground">Popular</span>@@ -171,16 +179,21 @@ export function PresetGallery({const query = useDeferredValue(q.trim().toLowerCase());const index = useMemo(() => presets.map((p) => [p, searchText(p)] as const), [presets]);+ // Unfiltered, the categories take turns, so the first screen shows the range of the catalog.+ const mixed = useMemo(() => interleaveByCategory(presets), [presets]);const cats = useMemo(() => ["All", ...new Set(presets.map((p) => p.category))], [presets]);const list = useMemo(() =>- index- .filter(([p, text]) => (cat === "All" || p.category === cat) && (!query || text.includes(query)) && (runsOn === "all" || p[runsOn]))- .map(([p]) => p),- [index, cat, query, runsOn],+ cat === "All" && !query+ ? mixed.filter((p) => runsOn === "all" || p[runsOn])+ : index+ .filter(([p, text]) => (cat === "All" || p.category === cat) && (!query || text.includes(query)) && (runsOn === "all" || p[runsOn]))+ .map(([p]) => p),+ [index, mixed, cat, query, runsOn],);// Cards render a page at a time; a new filter starts from the first page again.- const { shown, hasMore, more, sentinel, left } = useProgressive(list.length, `${cat}|${query}|${runsOn}`, FIRST_PAGE, PAGE);+ const { shown, hasMore, moreFrom, sentinel, left } = useProgressive(list.length, `${cat}|${query}|${runsOn}`, FIRST_PAGE, PAGE);+ const grid = useRef<HTMLDivElement>(null);const strip = useFadeEdges<HTMLDivElement>();const stale = q.trim().toLowerCase() !== query;@@ -244,9 +257,9 @@ export function PresetGallery({</div>{list.length ? (<>- <div className={cn(GRID, "transition-opacity", stale && "opacity-70")}>+ <div ref={grid} className={cn(GRID, "transition-opacity", stale && "opacity-70")}>{list.slice(0, shown).map((p) => (- <PresetCard key={p.id} preset={p} href={href.replace("{id}", p.id)} />+ <PresetCard key={p.id} preset={p} href={href.replace("{id}", p.id)} engine={locked} />))}</div>{hasMore && (@@ -254,7 +267,7 @@ export function PresetGallery({<buttonref={sentinel}type="button"- onClick={more}+ onClick={(e) => moreFrom(e, grid.current)}className="h-9 rounded-full border bg-background px-4 text-[13px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground">Show more · {left} leftdiff --git a/src/components/preset-header.tsx b/src/components/preset-header.tsxindex 236153e4..e4514565 100644--- a/src/components/preset-header.tsx+++ b/src/components/preset-header.tsx@@ -5,7 +5,7 @@ import { useSyncExternalStore } from "react";import { PresetPreview } from "@/components/preset-preview";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import type { Preset } from "@/lib/catalog/types";-import { presetHowTo, presetRouteLines, toPresetCard } from "@/lib/preset-cards";+import { presetHowTo, presetRouteLines, previewFlip, toPresetCard } from "@/lib/preset-cards";import { cn } from "@/lib/utils";const REDUCED = "(prefers-reduced-motion: reduce)";@@ -49,7 +49,7 @@ export function PresetHeader({return (<div className={cn("mx-auto flex w-full max-w-[760px] items-center gap-3 rounded-2xl border bg-background p-2 pr-3 text-left shadow-soft", className)}><div className="relative aspect-[4/3] w-24 shrink-0 overflow-hidden rounded-xl bg-muted sm:w-32">- <PresetPreview preview={card.preview} hue={card.hue} playing={!reduced} />+ <PresetPreview preview={card.preview} hue={card.hue} playing={!reduced} flip={previewFlip(card)} /></div><div className="min-w-0 flex-1"><p className="truncate font-heading text-[19px] leading-snug">{preset.name}</p>diff --git a/src/components/preset-preview.tsx b/src/components/preset-preview.tsxindex 0e563714..a8facb5b 100644--- a/src/components/preset-preview.tsx+++ b/src/components/preset-preview.tsx@@ -14,78 +14,11 @@ import {type PreviewLayer,type PreviewScene,} from "@/lib/preset-cards";+import { glyphFor } from "@/lib/move-glyphs";+import { browserPlaybackEnv, createPlaybackStore } from "@/lib/preview-playback";-/*- * Which preview plays. One at a time everywhere: the hovered or focused card on devices that can- * hover, otherwise the card nearest the middle of the screen while it's mostly in view (phones).- * Nothing plays when the user prefers reduced motion.- */-type Listener = () => void;-const listeners = new Set<Listener>();-let active: string | null = null;-const emit = () => listeners.forEach((l) => l());-const subscribe = (l: Listener) => {- listeners.add(l);- return () => listeners.delete(l);-};--function setActive(id: string | null) {- if (active === id) return;- active = id;- emit();-}--const mq = (q: string) => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(q).matches;-const canHover = () => mq("(hover: hover) and (pointer: fine)");-const reducedMotion = () => mq("(prefers-reduced-motion: reduce)");--/** Touch devices: the most visible card closest to the viewport's middle plays. */-const watched = new Map<Element, string>();-const ratios = new Map<Element, number>();-let observer: IntersectionObserver | null = null;-let raf = 0;--function pickCentered() {- raf = 0;- const mid = window.innerHeight / 2;- let best: string | null = null;- let bestDist = Infinity;- for (const [el, ratio] of ratios) {- if (ratio < 0.6) continue;- const r = el.getBoundingClientRect();- const dist = Math.abs(r.top + r.height / 2 - mid);- if (dist < bestDist) {- bestDist = dist;- best = watched.get(el) ?? null;- }- }- setActive(best);-}--const onScroll = () => {- raf ||= requestAnimationFrame(pickCentered);-};--function watch(el: Element, id: string) {- if (typeof IntersectionObserver === "undefined") return () => {};- observer ??= new IntersectionObserver(- (entries) => {- for (const e of entries) ratios.set(e.target, e.isIntersecting ? e.intersectionRatio : 0);- raf ||= requestAnimationFrame(pickCentered);- },- { threshold: [0, 0.6, 0.85, 1] },- );- if (!watched.size) window.addEventListener("scroll", onScroll, { passive: true, capture: true });- watched.set(el, id);- observer.observe(el);- return () => {- observer?.unobserve(el);- watched.delete(el);- ratios.delete(el);- if (!watched.size) window.removeEventListener("scroll", onScroll, { capture: true });- if (active === id) setActive(null);- };-}+/** One preview plays at a time (rules in lib/preview-playback.ts). */+const store = createPlaybackStore(browserPlaybackEnv);/*** Wire a card element to the playback store. Returns whether its preview should play and the@@ -94,27 +27,18 @@ function watch(el: Element, id: string) {export function usePreviewPlayback<T extends HTMLElement>(id: string) {const ref = useRef<T | null>(null);const playing = useSyncExternalStore(- subscribe,- () => active === id,+ store.subscribe,+ () => store.isActive(id),() => false,);useEffect(() => {const el = ref.current;- if (!el || canHover() || reducedMotion()) return;- return watch(el, id);+ if (!el || store.canHover() || store.reducedMotion()) return;+ return store.watch(el, id);}, [id]);- useEffect(- () => () => {- if (active === id) setActive(null);- },- [id],- );- const on = () => {- if (!reducedMotion()) setActive(id);- };- const off = () => {- if (active === id) setActive(null);- };+ useEffect(() => () => store.stop(id), [id]);+ const on = () => store.play(id);+ const off = () => store.stop(id);return {ref,playing,@@ -302,6 +226,16 @@ function Fx({ fx, scene }: { fx: NonNullable<Preview["fx"]>; scene: PreviewScene<i className="pv-play" /></>);+ case "crack":+ return (+ <>+ <svg className="pv-crack" viewBox="0 0 100 75" preserveAspectRatio="none" aria-hidden>+ <path d="M62 30 L69 22 L77 23 L86 10 L93 7 M62 30 L73 35 L86 33 L100 41 M62 30 L64 43 L58 54 L61 75 M62 30 L51 31 L41 25 L23 27 L0 19 M62 30 L53 41 L45 48 L31 62 L24 75 M62 30 L60 17 L54 7 L56 0 M77 23 L80 31 M51 31 L49 40 M58 54 L50 58" />+ <circle cx="62" cy="30" r="2.2" />+ </svg>+ <i className="pv-flash" />+ </>+ );case "pop":default:return <Sparks n={6} />;@@ -314,7 +248,18 @@ function Fx({ fx, scene }: { fx: NonNullable<Preview["fx"]>; scene: PreviewScene* At rest it shows the poster frame (and the treatment's still frame); `playing` runs it. The depth* layers a camera move needs are only mounted once the card first plays.*/-export const PresetPreview = memo(function PresetPreview({ preview, hue, playing }: { preview: Preview; hue: number; playing: boolean }) {+export const PresetPreview = memo(function PresetPreview({+ preview,+ hue,+ playing,+ flip,+}: {+ preview: Preview;+ hue: number;+ playing: boolean;+ /** Mirror the still (see previewFlip). */+ flip?: boolean;+}) {const video = useRef<HTMLVideoElement>(null);const [armed, setArmed] = useState(false);if (playing && !armed) setArmed(true);@@ -344,6 +289,7 @@ export const PresetPreview = memo(function PresetPreview({ preview, hue, playing);const spec: MoveSpec | undefined = preview.move ? CAMERA_MOVES[preview.move] : undefined;+ const glyph = preview.move ? glyphFor(preview.move) : undefined;const style = { "--pv-hue": hue, ...(spec ? moveVars(spec) : {}) } as React.CSSProperties;return (<div@@ -354,18 +300,27 @@ export const PresetPreview = memo(function PresetPreview({ preview, hue, playingdata-stage={spec?.stage}data-through={spec?.through || undefined}data-fx={preview.fx}+ data-flip={flip || undefined}aria-hidden><div className="pv-cam"><div className="pv-shake">{/* The poster stays underneath, so nothing flashes while the layers load. */}- <Dup src={preview.poster} className="pv-poster" />+ {/* A camera move's poster rests partway into the move (the subject layer's transform). */}+ {spec ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={preview.poster} alt="" draggable={false} decoding="async" className="pv-img pv-poster pv-layer" style={layerVars("subject")} />+ ) : (+ <Dup src={preview.poster} className="pv-poster" />+ )}{spec &&armed &&PREVIEW_LAYERS.map((l) => (// eslint-disable-next-line @next/next/no-img-element<img key={l} src={sceneLayer(preview.scene, l)} alt="" draggable={false} decoding="async" className={`pv-img pv-layer pv-l-${l}`} style={layerVars(l)} />))}+ {/* The preset's hue recolors the still only; the treatment keeps its own colors. */}+ <i className="pv-tint" />{preview.fx && (<div className="pv-fx"><Fx fx={preview.fx} scene={preview.scene} />@@ -373,7 +328,13 @@ export const PresetPreview = memo(function PresetPreview({ preview, hue, playing)}</div></div>- <i className="pv-tint" />+ {glyph && (+ <svg className="pv-glyph" viewBox="0 0 48 36" aria-hidden>+ {glyph.map((part, i) => (+ <path key={i} d={part.d} data-dashed={part.dashed || undefined} />+ ))}+ </svg>+ )}</div>);});diff --git a/src/components/use-progressive.ts b/src/components/use-progressive.tsindex 3ca9ef1d..d1a19fe5 100644--- a/src/components/use-progressive.ts+++ b/src/components/use-progressive.ts@@ -1,20 +1,37 @@"use client";import { useCallback, useEffect, useRef, useState } from "react";+import { pageAfter, progressiveStart, syncProgressive, type ProgressiveState } from "@/lib/progressive";++const FOCUSABLE = 'a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"]), input, select, textarea';/*** Render a long list a page at a time: `first` items up front (and in the server HTML), `page` more* whenever the sentinel element nears the viewport or is clicked. Starts over when `resetKey` changes* (a new search or filter).+ *+ * `moreFrom(event, list)` is the click handler for a "Show more" button: pressed from the keyboard,+ * it also moves focus to the first new item in `list` (the button itself may be gone afterwards).*/export function useProgressive<T extends HTMLElement = HTMLButtonElement>(total: number, resetKey: string, first = 30, page = 40) {- const [shown, setShown] = useState(first);- const [lastKey, setLastKey] = useState(resetKey);- if (lastKey !== resetKey) {- setLastKey(resetKey);- setShown(first);- }- const more = useCallback(() => setShown((n) => n + page), [page]);+ const [state, setState] = useState<ProgressiveState>(() => progressiveStart(resetKey, first));+ const synced = syncProgressive(state, resetKey, first);+ if (synced !== state) setState(synced);+ const shown = synced.shown;+ const more = useCallback(() => setState((s) => ({ ...s, shown: pageAfter(s.shown, page) })), [page]);+ const moreFrom = useCallback(+ (e: React.MouseEvent, list: HTMLElement | null) => {+ const from = shown;+ more();+ // A click from Enter/Space has no pointer position (detail 0).+ if (e.detail !== 0 || !list) return;+ requestAnimationFrame(() => {+ const item = list.children[from] as HTMLElement | undefined;+ (item?.matches(FOCUSABLE) ? item : item?.querySelector<HTMLElement>(FOCUSABLE))?.focus();+ });+ },+ [more, shown],+ );const sentinel = useRef<T>(null);const hasMore = shown < total;useEffect(() => {@@ -24,5 +41,5 @@ export function useProgressive<T extends HTMLElement = HTMLButtonElement>(total:io.observe(el);return () => io.disconnect();}, [hasMore, more, shown]);- return { shown, hasMore, more, sentinel, left: Math.max(0, total - shown) };+ return { shown, hasMore, more, moreFrom, sentinel, left: Math.max(0, total - shown) };}diff --git a/src/lib/move-glyphs.ts b/src/lib/move-glyphs.tsnew file mode 100644index 00000000..ca0b3b14--- /dev/null+++ b/src/lib/move-glyphs.ts@@ -0,0 +1,200 @@+/**+ * A small line diagram of each camera move, drawn over a motion card's resting frame so a gallery+ * of moves reads at a glance (arrows for pans and cranes, an ellipse for orbits, nested frames for+ * a dolly zoom…) before any card plays. Pure data, safe on both sides.+ *+ * Glyphs are drawn in a 48 × 36 box (the card's 4:3), as stroke-only paths; dashed parts are the+ * "behind" half of an orbit or the reference line of a tilted frame.+ */+import type { CameraMove } from "./preset-cards";++export type MoveGlyph =+ | "zoom-in"+ | "zoom-out"+ | "crash-in"+ | "crash-out"+ | "push-in"+ | "pull-out"+ | "vertigo"+ | "yoyo"+ | "through"+ | "pan-left"+ | "pan-right"+ | "tilt-up"+ | "tilt-down"+ | "truck-left"+ | "truck-right"+ | "crane-up"+ | "crane-down"+ | "crane-over"+ | "orbit-left"+ | "orbit-right"+ | "orbit-360"+ | "turntable"+ | "overhead"+ | "roll"+ | "dutch"+ | "shake"+ | "fpv"+ | "rise"+ | "whip"+ | "static"+ | "time"+ | "focus"+ | "jump"+ | "impact"+ | "float";++export interface GlyphPart {+ d: string;+ dashed?: true;+}++/** Which diagram each camera move shows. */+export const MOVE_GLYPH: Record<CameraMove, MoveGlyph> = {+ "zoom-in": "zoom-in",+ "zoom-out": "zoom-out",+ "optical-zoom": "zoom-in",+ "dolly-in": "push-in",+ "dolly-out": "pull-out",+ "super-dolly-in": "push-in",+ "super-dolly-out": "pull-out",+ "crash-in": "crash-in",+ "crash-out": "crash-out",+ "rapid-in": "crash-in",+ "rapid-out": "crash-out",+ "dolly-zoom-in": "vertigo",+ "dolly-zoom-out": "vertigo",+ yoyo: "yoyo",+ "through-in": "through",+ "through-out": "through",+ "earth-out": "zoom-out",+ "orbit-left": "orbit-left",+ "orbit-right": "orbit-right",+ "orbit-360": "orbit-360",+ "lazy-orbit": "orbit-right",+ "bullet-time": "orbit-360",+ turntable: "turntable",+ "crane-up": "crane-up",+ "crane-down": "crane-down",+ "crane-over": "crane-over",+ overhead: "overhead",+ "tilt-up": "tilt-up",+ "tilt-down": "tilt-down",+ "pan-left": "pan-left",+ "pan-right": "pan-right",+ "whip-pan": "whip",+ "truck-left": "truck-left",+ "truck-right": "truck-right",+ tracking: "truck-right",+ "double-dolly": "orbit-right",+ dutch: "dutch",+ roll: "roll",+ incline: "dutch",+ handheld: "shake",+ snorricam: "shake",+ pov: "shake",+ fpv: "fpv",+ "drone-rise": "rise",+ "road-rush": "crash-in",+ "robo-arm": "crane-over",+ static: "static",+ hyperlapse: "time",+ timelapse: "time",+ "slow-mo": "time",+ "rack-focus": "focus",+ "low-shutter": "whip",+ spin: "roll",+ jump: "jump",+ "slide-left": "truck-left",+ "slide-right": "truck-right",+ impact: "impact",+ float: "float",+};++const r = (n: number) => Math.round(n * 100) / 100;++/** An arrowhead whose tip is at (x, y), pointing along `deg` (0 = right, 90 = down). */+function head(x: number, y: number, deg: number, size = 3.4): string {+ const a = (deg * Math.PI) / 180;+ const wing = (s: number) => `${r(x - size * Math.cos(a + s))} ${r(y - size * Math.sin(a + s))}`;+ return `M${wing(0.55)} L${r(x)} ${r(y)} L${wing(-0.55)}`;+}++/** A straight arrow from (x1, y1) to (x2, y2). */+function arrow(x1: number, y1: number, x2: number, y2: number, size?: number): string {+ const deg = (Math.atan2(y2 - y1, x2 - x1) * 180) / Math.PI;+ return `M${x1} ${y1} L${x2} ${y2} ${head(x2, y2, deg, size)}`;+}++const rect = (x: number, y: number, w: number, h: number) => `M${x} ${y} H${x + w} V${y + h} H${x} Z`;+/** The four corner arrows of a zoom, pointing in (to the inner frame) or out (from it). */+const corners = (inward: boolean, from = 6, to = 13.5) => {+ const pts: [number, number, number, number][] = [+ [from, from * 0.75, to, to * 0.75],+ [48 - from, from * 0.75, 48 - to, to * 0.75],+ [from, 36 - from * 0.75, to, 36 - to * 0.75],+ [48 - from, 36 - from * 0.75, 48 - to, 36 - to * 0.75],+ ];+ return pts.map(([a, b, c, d]) => (inward ? arrow(a, b, c, d, 3) : arrow(c, d, a, b, 3))).join(" ");+};+const INNER = rect(16, 12, 16, 12);+const DOT = "M24 18 m-1.2 0 a1.2 1.2 0 1 0 2.4 0 a1.2 1.2 0 1 0 -2.4 0";+const mirror = (d: string) => d.replace(/(-?\d+(?:\.\d+)?) (-?\d+(?:\.\d+)?)/g, (_, x, y) => `${r(48 - Number(x))} ${y}`);+const flipY = (d: string) => d.replace(/(-?\d+(?:\.\d+)?) (-?\d+(?:\.\d+)?)/g, (_, x, y) => `${x} ${r(36 - Number(y))}`);++const PAN_LEFT = `M37 23 Q24 13 11 23 ${head(11, 23, 152)}`;+const TILT_UP = `M20 29 Q31 18 20 7 ${head(20, 7, -118)}`;+// (Only absolute x y pairs here: mirror() flips them.)+const TRUCK_LEFT = `${arrow(37, 15, 11, 15)} M8 24 L40 24 M12 24 L12 27 M20 24 L20 27 M28 24 L28 27 M36 24 L36 27`;+const ORBIT_FRONT = `M8 19 A16 6.5 0 0 0 40 19`;+const ORBIT_BACK = `M40 19 A16 6.5 0 0 0 8 19`;++/** Stroke paths per glyph, in a 48 × 36 box. */+export const GLYPHS: Record<MoveGlyph, GlyphPart[]> = {+ "zoom-in": [{ d: INNER, dashed: true }, { d: corners(true) }],+ "zoom-out": [{ d: INNER }, { d: corners(false) }],+ "crash-in": [{ d: INNER, dashed: true }, { d: corners(true, 4, 14) }, { d: corners(true, 4, 10) }],+ "crash-out": [{ d: INNER }, { d: corners(false, 4, 14) }, { d: corners(false, 8, 14) }],+ "push-in": [{ d: "M9 32 L19 11 M39 32 L29 11" }, { d: arrow(24, 30, 24, 9) }],+ "pull-out": [{ d: "M9 32 L19 11 M39 32 L29 11" }, { d: arrow(24, 10, 24, 31) }],+ vertigo: [{ d: rect(5, 4, 38, 28) }, { d: rect(12.5, 9.5, 23, 17), dashed: true }, { d: rect(19, 14.5, 10, 7) }],+ yoyo: [{ d: INNER, dashed: true }, { d: `${arrow(10, 7.5, 15, 11.25, 2.6)} ${head(6, 4.5, -143, 2.6)} M6 4.5 L10 7.5` }, { d: mirror(`${arrow(10, 7.5, 15, 11.25, 2.6)} ${head(6, 4.5, -143, 2.6)} M6 4.5 L10 7.5`) }],+ through: [{ d: "M26 9 a5 9 0 1 0 0.01 0" }, { d: arrow(6, 18, 43, 18) }],+ "pan-left": [{ d: PAN_LEFT }, { d: "M24 27 v4 M20 31 h8" }],+ "pan-right": [{ d: mirror(PAN_LEFT) }, { d: "M24 27 v4 M20 31 h8" }],+ "tilt-up": [{ d: TILT_UP }, { d: "M14 18 h-4" }],+ "tilt-down": [{ d: flipY(TILT_UP) }, { d: "M14 18 h-4" }],+ "truck-left": [{ d: TRUCK_LEFT }],+ "truck-right": [{ d: mirror(TRUCK_LEFT) }],+ "crane-up": [{ d: arrow(24, 28, 24, 6) }, { d: "M16 31 H32" }],+ "crane-down": [{ d: arrow(24, 6, 24, 27) }, { d: "M16 31 H32" }],+ "crane-over": [{ d: `M9 30 C9 2 39 2 39 26 ${head(39, 26, 90)}` }, { d: DOT }],+ "orbit-left": [{ d: ORBIT_BACK, dashed: true }, { d: `${ORBIT_FRONT} ${head(8, 19, 200)}` }, { d: DOT }],+ "orbit-right": [{ d: ORBIT_BACK, dashed: true }, { d: `${ORBIT_FRONT} ${head(40, 19, -20)}` }, { d: DOT }],+ "orbit-360": [{ d: `${ORBIT_FRONT} ${ORBIT_BACK.replace("M40 19", "")} ${head(40, 19, -20)}` }, { d: DOT }, { d: "M24 8 V13", dashed: true }],+ turntable: [{ d: `M10 27 A14 4.5 0 0 0 38 27 ${head(38, 27, -20, 3)}` }, { d: "M38 27 A14 4.5 0 0 0 10 27", dashed: true }, { d: "M24 6 V27" }],+ overhead: [{ d: "M24 7 a11 11 0 1 0 0.01 0" }, { d: "M24 3 V9 M24 27 V33 M9 18 H15 M33 18 H39" }, { d: DOT }],+ roll: [{ d: `M33.5 13 A11 11 0 1 0 34.5 21 ${head(34.5, 21, 105)}` }, { d: "M17 18 H31", dashed: true }],+ dutch: [{ d: "M8.5 11.3 L37.8 6.1 L39.5 24.7 L10.2 29.9 Z" }, { d: "M6 18 H42", dashed: true }],+ shake: [{ d: "M7 19 L11 13 L15 23 L19 12 L23 24 L27 13 L31 22 L35 14 L39 20 L42 17" }],+ fpv: [{ d: `M7 29 C17 29 15 10 27 10 S38 19 42 13 ${head(42, 13, -52)}` }],+ rise: [{ d: arrow(13, 28, 36, 8) }, { d: "M7 31 H22" }],+ whip: [{ d: arrow(12, 18, 42, 18) }, { d: "M5 12 H24 M8 24 H22", dashed: true }],+ static: [{ d: rect(17, 5, 14, 9) }, { d: "M24 14 V21 M24 21 L15 32 M24 21 L33 32 M24 21 V32" }],+ time: [{ d: "M24 6 a12 12 0 1 0 0.01 0" }, { d: "M24 18 V10 M24 18 L30 21.5" }],+ focus: [{ d: "M18 10 a8 8 0 1 0 0.01 0" }, { d: "M30 10 a8 8 0 1 0 0.01 0", dashed: true }],+ jump: [{ d: `M11 29 Q24 -1 37 29 ${head(37, 29, 66)}` }, { d: "M6 32 H42" }],+ impact: [+ {+ d: Array.from({ length: 8 }, (_, i) => {+ const a = (i * Math.PI) / 4 + Math.PI / 8;+ return `M${r(24 + 6 * Math.cos(a))} ${r(18 + 6 * Math.sin(a))} L${r(24 + 13 * Math.cos(a))} ${r(18 + 13 * Math.sin(a))}`;+ }).join(" "),+ },+ { d: DOT },+ ],+ float: [{ d: `M20 31 C28 26 16 21 24 16 S28 9 24 5 ${head(24, 5, -105)}` }],+};++export const glyphFor = (move: CameraMove): GlyphPart[] => GLYPHS[MOVE_GLYPH[move]];diff --git a/src/lib/preset-cards.ts b/src/lib/preset-cards.tsindex 68e4506f..bb3586ee 100644--- a/src/lib/preset-cards.ts+++ b/src/lib/preset-cards.ts@@ -167,6 +167,7 @@ export const FX = ["frame","pop","play",+ "crack",] as const;export type PreviewFx = (typeof FX)[number];@@ -276,7 +277,10 @@ function keywordFx(n: string): PreviewFx | null {if (has(n, "freez", "frozen", "snow") || word(n, "ice")) return "ice";if (has(n, "air bending", "storm", "tornado", "smoke") || word(n, "wind", "air", "sand", "gas")) return "wind";if (has(n, "thunder", "lightning", "plasma", "atomic")) return "lightning";- if (has(n, "explo", "boom", "crush", "smash", "crack", "disintegrat", "head off", "boiling", "earth")) return "explode";+ if (has(n, "crack", "shatter")) return "crack";+ if (has(n, "disintegrat", "dissolv")) return "wind";+ if (has(n, "head off")) return "glow";+ if (has(n, "explo", "boom", "crush", "smash", "boiling", "earth")) return "explode";if (has(n, "glitch", "datamosh", "pixel", "censor", "x-ray", "visor", "lidar", "point cloud", "wireframe", "polygon")) return "glitch";if (has(n, "flare", "paparazzi", "flash")) return "flare";if (has(n, "bloom", "flower", "petal", "sakura", "garden", "floral") || word(n, "rose")) return "petals";@@ -335,27 +339,44 @@ export function appFx(p: Pick<Preset, "id" | "name" | "category">): PreviewFx {return "pop";}+/** A small stable hash (FNV-1a), for per-preset variety that is the same on the server and the client. */+export function stableHash(s: string): number {+ let h = 0x811c9dc5;+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ return h >>> 0;+}++/** One of `pool`, picked by the preset id: presets without telling words still differ from their neighbours. */+function pick<T>(id: string | undefined, pool: readonly T[]): T {+ return pool[id ? stableHash(id) % pool.length : 0];+}+/** Which bundled still a preset's preview runs on. */-export function previewScene(p: Pick<Preset, "type" | "name" | "category">): PreviewScene {+export function previewScene(p: Pick<Preset, "type" | "name" | "category"> & { id?: string }): PreviewScene {const n = p.name.toLowerCase();const c = p.category.toLowerCase();if (p.type === "motion") {if (has(n, "eyes", "mouth", "eating", "kiss", "snorricam", "head tracking", "rap flex", "selfie", "fisheye", "glam", "lazy susan", "intimate")) return "portrait";if (c.includes("drone") || has(n, "road", "car", "buckle", "robo", "hyperlapse")) return "city";- return "landscape";+ if (has(n, "crane", "jib", "pedestal", "tilt", "aerial", "earth", "epic", "downhill")) return "landscape";+ return pick(p.id, ["landscape", "city", "portrait", "product"] as const);}if (p.type === "app") {if (c === "product" || has(n, "product", "packshot", "ad ", "billboard", "unboxing")) return "product";if (has(n, "urban", "clipcut", "truck", "roller")) return "city";if (["identity", "fashion", "fun", "video"].includes(c) || has(n, "face", "portrait", "headshot", "hair", "makeup", "selfie")) return "portrait";- return "landscape";+ return pick(p.id, ["landscape", "city", "portrait"] as const);}if (c === "commercial") return "product";if (has(n, "car", "building", "street", "city", "train", "helicopter", "road", "giant", "colossus", "concert", "tiny planet")) return "city";if (has(n, "fish", "ocean", "flood", "water", "sand", "earth", "nature", "garden", "northern", "timelapse", "planet")) return "landscape";- if (["destruction", "scale"].includes(c)) return "city";- if (["elements", "nature", "color grade", "transitions"].includes(c)) return "landscape";- return "portrait";+ if (has(n, "head", "face", "eyes", "body", "hair", "skin", "tears", "mask")) return "portrait";+ if (["destruction", "scale"].includes(c)) return pick(p.id, ["city", "landscape", "portrait"] as const);+ if (["elements", "nature", "color grade", "transitions"].includes(c)) return pick(p.id, ["landscape", "city", "portrait"] as const);+ return pick(p.id, ["portrait", "landscape", "city", "portrait"] as const);}export function previewFor(p: Pick<Preset, "id" | "type" | "name" | "category">): PresetPreview {@@ -367,6 +388,15 @@ export function previewFor(p: Pick<Preset, "id" | "type" | "name" | "category">)};}+/**+ * Whether a card shows its still mirrored, so neighbouring treatments on the same still differ.+ * Never for camera moves (a pan left must still go left). Derived from the id on the client, so it+ * costs nothing in the gallery payload.+ */+export function previewFlip(c: { id: string; preview: Pick<PresetPreview, "move"> }): boolean {+ return !c.preview.move && ((stableHash(c.id) >>> 3) & 1) === 1;+}+/** The hue a preset's look was built from (`oklch(L C <hue>)`), for tinting its preview. */export function lookHue(look: Preset["look"]): number {const m = /oklch\([^)]*?\s([\d.]+)\s*\)/.exec(look.from);@@ -396,6 +426,33 @@ export function toPresetCard(p: Preset): PresetCardData {};}+/**+ * A showcase row: one preset per category (its "top" one when it has one), in catalog order, so+ * the row shows `n` different kinds of effect instead of the first category's six.+ */+export function homeEffects<T extends Pick<Preset, "category" | "badges">>(presets: T[], n: number): T[] {+ const best = new Map<string, T>();+ for (const p of presets) {+ const cur = best.get(p.category);+ if (!cur || (!cur.badges?.includes("top") && p.badges?.includes("top"))) best.set(p.category, p);+ }+ return [...best.values()].slice(0, n);+}++/**+ * The "All" view of a gallery: categories taken in turn (first of each, then second of each…), so+ * the first screen shows the range of the catalog instead of one category's near-identical cards.+ * Stable: within a category the catalog order is kept.+ */+export function interleaveByCategory<T extends { category: string }>(items: T[]): T[] {+ const groups = new Map<string, T[]>();+ for (const it of items) groups.set(it.category, [...(groups.get(it.category) ?? []), it]);+ const lists = [...groups.values()];+ const out: T[] = [];+ for (let i = 0; out.length < items.length; i++) for (const l of lists) if (i < l.length) out.push(l[i]);+ return out;+}+/** Lower-cased text a gallery search matches against. */export const searchText = (c: Pick<PresetCardData, "name" | "description" | "category">) => `${c.name} ${c.description} ${c.category}`.toLowerCase();diff --git a/src/lib/preview-playback.ts b/src/lib/preview-playback.tsnew file mode 100644index 00000000..f1534d9c--- /dev/null+++ b/src/lib/preview-playback.ts@@ -0,0 +1,116 @@+/**+ * Which gallery preview plays (preset-preview.tsx). One at a time everywhere: the hovered or+ * focused card on devices that can hover, otherwise the card nearest the middle of the screen+ * while it's mostly in view (phones). Nothing plays when the user prefers reduced motion.+ *+ * Pure apart from the environment it's given, so the rules are testable without a browser.+ */++/** What the store needs from the browser. */+export interface PlaybackEnv {+ matches(query: string): boolean;+ /** Undefined where IntersectionObserver doesn't exist (then nothing auto-plays). */+ IntersectionObserver?: new (cb: IntersectionObserverCallback, opts?: IntersectionObserverInit) => Pick<IntersectionObserver, "observe" | "unobserve">;+ requestFrame(cb: () => void): number;+ viewportHeight(): number;+ onScroll(cb: () => void): void;+ offScroll(cb: () => void): void;+}++/** A card must be at least this much in view to play on a phone. */+export const MIN_VISIBLE = 0.6;++export function createPlaybackStore(env: PlaybackEnv) {+ const listeners = new Set<() => void>();+ let active: string | null = null;+ const watched = new Map<Element, string>();+ const ratios = new Map<Element, number>();+ let observer: Pick<IntersectionObserver, "observe" | "unobserve"> | null = null;+ let frame = 0;++ const setActive = (id: string | null) => {+ if (active === id) return;+ active = id;+ listeners.forEach((l) => l());+ };++ /** Phones: the most visible card closest to the viewport's middle plays. */+ const pickCentered = () => {+ frame = 0;+ const mid = env.viewportHeight() / 2;+ let best: string | null = null;+ let bestDist = Infinity;+ for (const [el, ratio] of ratios) {+ if (ratio < MIN_VISIBLE) continue;+ const r = el.getBoundingClientRect();+ const dist = Math.abs(r.top + r.height / 2 - mid);+ if (dist < bestDist) {+ bestDist = dist;+ best = watched.get(el) ?? null;+ }+ }+ setActive(best);+ };+ const schedule = () => {+ frame ||= env.requestFrame(pickCentered);+ };++ return {+ subscribe(l: () => void) {+ listeners.add(l);+ return () => {+ listeners.delete(l);+ };+ },+ getActive: () => active,+ isActive: (id: string) => active === id,+ canHover: () => env.matches("(hover: hover) and (pointer: fine)"),+ reducedMotion: () => env.matches("(prefers-reduced-motion: reduce)"),+ /** Hover / focus: play this one (unless motion is reduced). */+ play(id: string) {+ if (!env.matches("(prefers-reduced-motion: reduce)")) setActive(id);+ },+ /** Stop this one, if it's the one playing. */+ stop(id: string) {+ if (active === id) setActive(null);+ },+ /** Touch devices: let visibility decide whether `el` plays. Returns the cleanup. */+ watch(el: Element, id: string): () => void {+ const IO = env.IntersectionObserver;+ if (!IO) return () => {};+ observer ??= new IO(+ (entries) => {+ for (const e of entries) ratios.set(e.target, e.isIntersecting ? e.intersectionRatio : 0);+ schedule();+ },+ { threshold: [0, MIN_VISIBLE, 0.85, 1] },+ );+ if (!watched.size) env.onScroll(schedule);+ watched.set(el, id);+ observer.observe(el);+ return () => {+ observer?.unobserve(el);+ watched.delete(el);+ ratios.delete(el);+ if (!watched.size) env.offScroll(schedule);+ if (active === id) setActive(null);+ };+ },+ /** For tests: how many cards are watched. */+ watchedCount: () => watched.size,+ };+}++export type PlaybackStore = ReturnType<typeof createPlaybackStore>;++/** The real browser; every member is safe to call during server rendering. */+export const browserPlaybackEnv: PlaybackEnv = {+ matches: (q) => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(q).matches,+ get IntersectionObserver() {+ return typeof IntersectionObserver === "undefined" ? undefined : IntersectionObserver;+ },+ requestFrame: (cb) => requestAnimationFrame(cb),+ viewportHeight: () => window.innerHeight,+ onScroll: (cb) => window.addEventListener("scroll", cb, { passive: true, capture: true }),+ offScroll: (cb) => window.removeEventListener("scroll", cb, { capture: true }),+};diff --git a/src/lib/progressive.ts b/src/lib/progressive.tsnew file mode 100644index 00000000..f6f476fa--- /dev/null+++ b/src/lib/progressive.ts@@ -0,0 +1,15 @@+/** Paging state for lists rendered a page at a time (components/use-progressive.ts). Pure. */+export interface ProgressiveState {+ /** The filter/search the count belongs to: a new one starts from the first page again. */+ key: string;+ shown: number;+}++export const progressiveStart = (key: string, first: number): ProgressiveState => ({ key, shown: first });++/** The same state while the filter is unchanged; the first page again once it changes. */+export const syncProgressive = (state: ProgressiveState, key: string, first: number): ProgressiveState =>+ state.key === key ? state : progressiveStart(key, first);++/** How many items show after one more page. */+export const pageAfter = (shown: number, page: number) => shown + Math.max(1, page);