Skip to content

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

Site nav mega menu: sections with live component previews (#276)

KapishDima34dcdbbc9e66
diff --git a/app/(home)/components/header-nav.tsx b/app/(home)/components/header-nav.tsx
index bb058280..f7d32721 100644
--- a/app/(home)/components/header-nav.tsx
+++ b/app/(home)/components/header-nav.tsx
@@ -1,11 +1,22 @@
"use client";
import Link from "next/link";
-import { useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { SlidingHighlight } from "@/components/sliding-highlight";
import { SheetClose } from "@/components/ui/sheet";
+import { MEGA_MENU_SECTIONS } from "@/config/mega-menu";
import type { NavLink } from "@/config/site";
import { cn } from "@/lib/utils";
+import { MegaMenuPanel } from "./mega-menu";
+
+const SECTION_HREFS = new Set(MEGA_MENU_SECTIONS.map((s) => s.href));
+
+// The mega panel is desktop-only: below `lg` it is display:none, and on touch
+// devices hover-open fights with tap-to-navigate. Checked at interaction time
+// so no resize listener or hydration mismatch is needed.
+const canOpenMenu = () =>
+ typeof window !== "undefined" &&
+ window.matchMedia("(min-width: 64rem) and (hover: hover)").matches;
/**
* Desktop nav whose items behave like ghost buttons: a single rounded
@@ -13,6 +24,11 @@ import { cn } from "@/lib/utils";
* to the next instead of popping. Rendered once and animated via transform, so
* moving between items reads as the same pill sliding across the row. Hidden
* below `sm`, where the header falls back to the mobile sheet.
+ *
+ * Registry links (Components / Shaders / Icons) additionally open a shared
+ * mega-menu panel: a short intent delay on open, a grace delay on close so the
+ * pointer can travel into the panel, and instant section switching while the
+ * panel is already open (the panel slides its content instead of reopening).
*/
export function NavDesktop({
links,
@@ -26,6 +42,49 @@ export function NavDesktop({
left: number;
width: number;
} | null>(null);
+ const [open, setOpen] = useState<string | null>(null);
+ const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const clearTimers = () => {
+ if (openTimer.current) clearTimeout(openTimer.current);
+ if (closeTimer.current) clearTimeout(closeTimer.current);
+ openTimer.current = null;
+ closeTimer.current = null;
+ };
+
+ useEffect(
+ () => () => {
+ if (openTimer.current) clearTimeout(openTimer.current);
+ if (closeTimer.current) clearTimeout(closeTimer.current);
+ },
+ [],
+ );
+
+ const scheduleOpen = (href: string) => {
+ if (!canOpenMenu()) return;
+ clearTimers();
+ if (open) {
+ setOpen(href);
+ } else {
+ openTimer.current = setTimeout(() => setOpen(href), 50);
+ }
+ };
+
+ const scheduleClose = (delay = 120) => {
+ clearTimers();
+ closeTimer.current = setTimeout(() => setOpen(null), delay);
+ };
+
+ const cancelClose = () => {
+ if (closeTimer.current) clearTimeout(closeTimer.current);
+ closeTimer.current = null;
+ };
+
+ const closeNow = () => {
+ clearTimers();
+ setOpen(null);
+ };
// Measure the item relative to the nav so the pill can be positioned with a
// transform (left:0 + translateX) rather than animating layout.
@@ -40,28 +99,57 @@ export function NavDesktop({
return (
<nav
ref={navRef}
- onMouseLeave={() => setHighlight(null)}
+ onMouseEnter={cancelClose}
+ onMouseLeave={() => {
+ setHighlight(null);
+ scheduleClose();
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") closeNow();
+ }}
// Retract the pill once focus leaves the nav entirely (not while tabbing
// between items), mirroring the mouse-leave behaviour for keyboard users.
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
setHighlight(null);
+ closeNow();
}
}}
className={cn("relative hidden items-center gap-1 sm:flex", className)}
>
<SlidingHighlight rect={highlight} />
- {links.map((link) => (
- <Link
- key={link.href}
- href={link.href}
- onMouseEnter={(event) => moveTo(event.currentTarget)}
- onFocus={(event) => moveTo(event.currentTarget)}
- className="relative rounded-full px-3 py-2 text-sm font-medium text-foreground focus-visible:outline-none"
- >
- {link.label}
- </Link>
- ))}
+ {links.map((link) => {
+ const hasMenu = SECTION_HREFS.has(link.href);
+ return (
+ <Link
+ key={link.href}
+ href={link.href}
+ onMouseEnter={(event) => {
+ moveTo(event.currentTarget);
+ if (hasMenu) {
+ scheduleOpen(link.href);
+ } else {
+ scheduleClose(100);
+ }
+ }}
+ onFocus={(event) => {
+ moveTo(event.currentTarget);
+ if (hasMenu && canOpenMenu()) {
+ clearTimers();
+ setOpen(link.href);
+ }
+ }}
+ onClick={closeNow}
+ aria-haspopup={hasMenu ? "true" : undefined}
+ aria-expanded={hasMenu ? open === link.href : undefined}
+ aria-controls={hasMenu ? "site-mega-menu" : undefined}
+ className="relative rounded-full px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:text-foreground focus-visible:outline-none"
+ >
+ {link.label}
+ </Link>
+ );
+ })}
+ <MegaMenuPanel open={open} onNavigate={closeNow} />
</nav>
);
}
diff --git a/app/(home)/components/mega-menu-preview.tsx b/app/(home)/components/mega-menu-preview.tsx
new file mode 100644
index 00000000..f13dacbb
--- /dev/null
+++ b/app/(home)/components/mega-menu-preview.tsx
@@ -0,0 +1,51 @@
+"use client";
+
+import { Player, type PlayerRef } from "@remotion/player";
+import { useRef } from "react";
+import registry from "@/registry/__index__";
+import { previewManifest } from "@/registry/__manifest__";
+import { useAutoplay } from "./use-autoplay";
+
+export default function MegaMenuPreview({ name }: { name: string }) {
+ const entry = registry[name];
+ const preview = previewManifest[name];
+ const playerRef = useRef<PlayerRef>(null);
+ const { containerRef } = useAutoplay(playerRef);
+
+ if (!entry || !preview) return null;
+
+ const backdrop = preview.previewBackdrop;
+ const background =
+ backdrop && backdrop.type !== "image" ? backdrop.value : "#f5f5f5";
+
+ // Слот в панели всегда 16:9, композиции — нет (иконки 48×48). Плеер получает
+ // бокс с аспектом композиции, вписанный в слот, — иначе Remotion обрезает.
+ const wide = preview.compositionWidth / preview.compositionHeight >= 16 / 9;
+
+ return (
+ <div
+ ref={containerRef}
+ className="pointer-events-none flex size-full items-center justify-center"
+ >
+ <Player
+ ref={playerRef}
+ lazyComponent={entry.load}
+ inputProps={preview.defaults}
+ durationInFrames={preview.durationInFrames}
+ fps={preview.fps}
+ compositionWidth={preview.compositionWidth}
+ compositionHeight={preview.compositionHeight}
+ style={{
+ aspectRatio: `${preview.compositionWidth} / ${preview.compositionHeight}`,
+ width: wide ? "100%" : "auto",
+ height: wide ? "auto" : "100%",
+ borderRadius: 8,
+ background,
+ }}
+ controls={false}
+ loop
+ acknowledgeRemotionLicense
+ />
+ </div>
+ );
+}
diff --git a/app/(home)/components/mega-menu.tsx b/app/(home)/components/mega-menu.tsx
new file mode 100644
index 00000000..2526dda5
--- /dev/null
+++ b/app/(home)/components/mega-menu.tsx
@@ -0,0 +1,207 @@
+"use client";
+
+import { AnimatePresence, motion, useReducedMotion } from "motion/react";
+import dynamic from "next/dynamic";
+import Link from "next/link";
+import { useEffect, useRef, useState } from "react";
+import {
+ MEGA_MENU_SECTIONS,
+ type MegaMenuItem,
+ type MegaMenuSection,
+} from "@/config/mega-menu";
+import { cn } from "@/lib/utils";
+
+const MegaMenuPreview = dynamic(() => import("./mega-menu-preview"), {
+ ssr: false,
+});
+
+const OPEN_SPRING = {
+ type: "spring",
+ stiffness: 520,
+ damping: 40,
+} as const;
+const SLIDE_SPRING = {
+ type: "spring",
+ stiffness: 480,
+ damping: 44,
+} as const;
+
+function useDebouncedValue<T>(value: T, delay: number): T {
+ const [debounced, setDebounced] = useState(value);
+ useEffect(() => {
+ const timer = setTimeout(() => setDebounced(value), delay);
+ return () => clearTimeout(timer);
+ }, [value, delay]);
+ return debounced;
+}
+
+export function MegaMenuPanel({
+ open,
+ onNavigate,
+}: {
+ open: string | null;
+ onNavigate: () => void;
+}) {
+ const reduced = useReducedMotion() ?? false;
+ // Keep the last open section rendered through the exit fade so the panel
+ // doesn't blank out mid-close.
+ const lastOpen = useRef<string | null>(open);
+ if (open) lastOpen.current = open;
+ const activeHref = open ?? lastOpen.current;
+ const activeIndex = Math.max(
+ 0,
+ MEGA_MENU_SECTIONS.findIndex((section) => section.href === activeHref),
+ );
+
+ return (
+ <div
+ inert={!open}
+ className={cn(
+ "absolute left-1/2 top-full z-50 -translate-x-1/2 pt-3 max-lg:hidden",
+ open
+ ? "visible"
+ : "invisible pointer-events-none [transition:visibility_0s_linear_150ms]",
+ )}
+ >
+ <motion.div
+ id="site-mega-menu"
+ initial={false}
+ animate={open ? "open" : "closed"}
+ variants={{
+ open: {
+ opacity: 1,
+ scale: 1,
+ y: 0,
+ transition: reduced ? { duration: 0 } : OPEN_SPRING,
+ },
+ closed: {
+ opacity: 0,
+ scale: 0.97,
+ y: -6,
+ transition: reduced
+ ? { duration: 0 }
+ : { duration: 0.13, ease: "easeIn" },
+ },
+ }}
+ className="origin-top rounded-[20px] bg-popover p-3 text-popover-foreground shadow-lg ring-1 ring-foreground/5 dark:ring-foreground/10"
+ >
+ <motion.div
+ initial={false}
+ animate={{
+ width: MEGA_MENU_SECTIONS[activeIndex].listWidth + 20 + 384,
+ }}
+ transition={reduced ? { duration: 0 } : SLIDE_SPRING}
+ className="relative h-[216px]"
+ >
+ {MEGA_MENU_SECTIONS.map((section, index) => (
+ <Section
+ key={section.href}
+ section={section}
+ offset={index - activeIndex}
+ menuOpen={open === section.href}
+ onNavigate={onNavigate}
+ reduced={reduced}
+ />
+ ))}
+ </motion.div>
+ </motion.div>
+ </div>
+ );
+}
+
+function Section({
+ section,
+ offset,
+ menuOpen,
+ onNavigate,
+ reduced,
+}: {
+ section: MegaMenuSection;
+ offset: number;
+ menuOpen: boolean;
+ onNavigate: () => void;
+ reduced: boolean;
+}) {
+ const active = offset === 0;
+ const [hoveredIndex, setHoveredIndex] = useState(0);
+ const item = section.items[hoveredIndex] ?? section.items[0];
+ const previewItem = useDebouncedValue(item, 90);
+
+ return (
+ <motion.div
+ inert={!active || !menuOpen}
+ initial={false}
+ animate={{
+ x: reduced || active ? 0 : offset < 0 ? -28 : 28,
+ opacity: active ? 1 : 0,
+ }}
+ transition={reduced ? { duration: 0 } : SLIDE_SPRING}
+ className={cn(
+ "absolute left-0 top-0 flex h-full gap-5",
+ active
+ ? "visible"
+ : "invisible [transition:visibility_0s_linear_200ms]",
+ )}
+ >
+ <div
+ style={{ width: section.listWidth }}
+ className="grid shrink-0 auto-cols-fr grid-flow-col grid-rows-6 gap-x-2 gap-y-1"
+ >
+ {section.items.map((menuItem, index) => (
+ <MenuRow
+ key={`${menuItem.preview}-${index}`}
+ item={menuItem}
+ hovered={index === hoveredIndex}
+ onHover={() => setHoveredIndex(index)}
+ onNavigate={onNavigate}
+ />
+ ))}
+ </div>
+ <div className="w-96 shrink-0">
+ <div className="relative aspect-video w-full overflow-hidden rounded-lg bg-muted/40">
+ <AnimatePresence initial={false}>
+ {active && menuOpen && (
+ <motion.div
+ key={previewItem.preview}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: reduced ? 0 : 0.15 }}
+ className="absolute inset-0"
+ >
+ <MegaMenuPreview name={previewItem.preview} />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ </div>
+ </motion.div>
+ );
+}
+
+function MenuRow({
+ item,
+ hovered,
+ onHover,
+ onNavigate,
+}: {
+ item: MegaMenuItem;
+ hovered: boolean;
+ onHover: () => void;
+ onNavigate: () => void;
+}) {
+ return (
+ <Link
+ href={item.href}
+ onClick={onNavigate}
+ onMouseEnter={onHover}
+ onFocus={onHover}
+ className={cn(
+ "flex min-w-0 items-center rounded-lg px-3 text-sm font-medium transition-colors duration-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",
+ hovered ? "bg-muted text-foreground" : "text-muted-foreground",
+ )}
+ >
+ <span className="truncate">{item.label}</span>
+ </Link>
+ );
+}
diff --git a/config/mega-menu.ts b/config/mega-menu.ts
new file mode 100644
index 00000000..f9dbd750
--- /dev/null
+++ b/config/mega-menu.ts
@@ -0,0 +1,91 @@
+import shadersMeta from "@/content/docs/shaders/components/meta.json";
+import remocnIconsRegistry from "@/registry/remocn-icons/registry.json";
+
+export type MegaMenuItem = {
+ label: string;
+ href: string;
+ /** Ключ из registry/__index__, который играет в preview-панели при ховере строки. */
+ preview: string;
+};
+
+export type MegaMenuSection = {
+ /** href пункта NAV_LINKS, к которому привязана секция. */
+ href: string;
+ /** Ширина колонки списка в px; панель анимирует ширину между секциями. */
+ listWidth: number;
+ items: MegaMenuItem[];
+};
+
+const humanize = (slug: string) =>
+ slug
+ .split("-")
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(" ");
+
+const COMPONENT_CATEGORIES: MegaMenuItem[] = [
+ { label: "Typography", href: "/docs/typography", preview: "soft-blur-in" },
+ { label: "Layout", href: "/docs/layout", preview: "drift" },
+ { label: "UI", href: "/docs/ui", preview: "accordion" },
+ {
+ label: "Transitions",
+ href: "/docs/transitions",
+ preview: "grain-dissolve",
+ },
+ { label: "Effects", href: "/docs/effects", preview: "tv-power-off" },
+ {
+ label: "Filters",
+ href: "/docs/filters/getting-started/introduction",
+ preview: "camera-lens",
+ },
+];
+
+const SHADER_ITEMS: MegaMenuItem[] = shadersMeta.pages.map((slug) => ({
+ label: humanize(slug.replace(/^shader-/, "")),
+ href: `/docs/shaders/components/${slug}`,
+ preview: slug,
+}));
+
+/**
+ * Курируемая выборка: весь каталог (100 иконок) в меню без скролла не влезает,
+ * а каждая строка всё равно ведёт в галерею.
+ */
+const FEATURED_ICONS = [
+ "icon-check",
+ "icon-x",
+ "icon-heart",
+ "icon-star",
+ "icon-search",
+ "icon-bell",
+ "icon-download",
+ "icon-copy",
+ "icon-trash",
+ "icon-plus",
+ "icon-send",
+ "icon-loader",
+ "icon-play",
+ "icon-settings",
+ "icon-thumbs-up",
+ "icon-party-popper",
+ "icon-arrow-right",
+ "icon-refresh-cw",
+];
+
+const ICON_ITEMS: MegaMenuItem[] = FEATURED_ICONS.flatMap((name) => {
+ const item = remocnIconsRegistry.items.find((entry) => entry.name === name);
+ if (!item) return [];
+ return {
+ label: item.title,
+ href: "/docs/icons/gallery",
+ preview: item.name,
+ };
+});
+
+export const MEGA_MENU_SECTIONS: MegaMenuSection[] = [
+ { href: "/docs/typography", listWidth: 176, items: COMPONENT_CATEGORIES },
+ {
+ href: "/docs/shaders/getting-started/introduction",
+ listWidth: 552,
+ items: SHADER_ITEMS,
+ },
+ { href: "/docs/icons/gallery", listWidth: 496, items: ICON_ITEMS },
+];