у меня есть проект на Next.js 14 + tailwind + я установил… · The Chat Archive
Explore / Programming o1-preview-2024-09-12 · OpenAI WildChat-4.8M (AI2)у меня есть проект на Next.js 14 + tailwind + я установил плагины… Save Share Download ▾ Reportу меня есть проект на Next.js 14 + tailwind + я установил плагины @tailwindcss/typography, @tailwindcss/forms, @tailwindcss/aspect-ratio, @tailwindcss/line-clamp, framer-motion, так же проект использует typescript, с учетом этого мне нужна помощь. я тебе сейчас отправлю все необзодимсые странциы и компоненты с моего сайта. у меня такая проблема, что перед тем, как проигрывается анимация затухания текущей страницы, она в начале поднимается в самый верх, только потом затухает и затем появялется новая страница, ссылку на которую я нажимаю в панели навигации navbar или footer. Я хочу, чтобы как было, при нажатии на ссылку в панели навигации не было нкиакого перемещения текущей страницы, а вот новая страница, на которую я делаю переход была сверху. Я тебе отправляю для примера 2 страницы меду которыми я делаю переход.
// src/components/Layout.tsx
import Head from 'next/head';
import { useRouter } from 'next/router';
import Footer from './Footer';
import Navbar from './Navbar';
import { ReactNode } from 'react';
import { motion } from 'framer-motion';
interface LayoutProps {
children: ReactNode;
image?: string;
type?: string;
metadata?: {
title?: string;
description?: string;
keywords?: string;
};
}
const variants = {
initial: { opacity: 0 },
animate: { opacity: 1 },
exit: { opacity: 0 },
};
const Layout = ({ children, image, type, metadata }: LayoutProps) => {
const router = useRouter();
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || '';
return (
{/* Мета-данные страницы /}
{metadata && (
<>
{metadata.title}
</>
)}
{/ Open Graph и другие мета-данные */}
<meta property="og:type" content={type || 'website'} />
<meta property="og:url" content={${siteUrl}${router.asPath}} />
<meta property="og:image" content={image || '/images/seo/halley-banner.png'} />
<link rel="canonical" href={${siteUrl}${router.asPath}} />
<motion.main
className="flex-grow"
variants={variants}
initial="initial"
animate="animate"
exit="exit"
transition={{ duration: 0.5, ease: 'easeInOut' }}
>
{children}
</motion.main>
);
};
export default Layout;
// components/Navbar.tsx
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import ThemeSwitchButton from './ThemeSwitchButton';
import { ChevronDownIcon, Bars3Icon, XMarkIcon } from '@heroicons/react/24/solid';
import { motion, AnimatePresence } from 'framer-motion';
// Типизация для навигационных ссылок
interface NavItem {
name: string;
href: string;
emoji?: string;
}
interface StoreLink {
name: string;
href: string;
iconSrc: string;
bgGradient: string;
textColor: string;
}
// Навигационные элементы
const navigation: NavItem[] = [
{ name: 'Главная', href: '/', emoji: '🏠' },
{ name: 'Программы', href: '/soft', emoji: '💻' },
{ name: 'Статьи', href: '/articles', emoji: '📝' },
{ name: 'О нас', href: '/about', emoji: 'ℹ️' },
{ name: 'Обратная связь', href: '/contact', emoji: '📩' },
];
Assistant2024-10-09 17:00 UTC Copy response
Copy first prompt
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Model o1-preview-2024-09-12
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Oct 9, 2024
Added to archive Nov 16, 2026
ID 01m7h41x6f2ew0mtfxxy4q59m2Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 234ba28d21fa4c3a91217ca4f4f28e08
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
Dataset releases Not yet included in a published release.
// Ссылки магазинов
const storeLinks: StoreLink[] = [
{
name: 'OZON',
href: 'https://www.ozon.ru/seller/smartdiag-862410/ ',
iconSrc: '/images/logos/favicon.ico',
bgGradient: 'bg-gradient-to-r from-blue-500 to-blue-700 hover:from-blue-600 hover:to-blue-900',
textColor: 'text-white',
},
{
name: 'Яндекс Маркет',
href: 'https://market.yandex.ru/business--smartdiag/50025236 ',
iconSrc: 'https://yastatic.net/market-export/_/i/favicon/ymnew/favicon.ico ',
bgGradient: 'bg-gradient-to-r from-yellow-400 to-yellow-600 hover:from-yellow-500 hover:to-yellow-700',
textColor: 'text-black',
},
{
name: 'Wildberries',
href: 'https://www.wildberries.ru/seller/1343369 ',
iconSrc: '/images/logos/favicon.ico',
bgGradient: 'bg-gradient-to-r from-purple-500 to-purple-700 hover:from-purple-600 hover:to-purple-900',
textColor: 'text-white',
},
];
// Подкомпонент для навигационных ссылок
const NavLinks: React.FC<{ items: NavItem[] }> = ({ items }) => (
<>
{items.map((item) => (
{item.name}
))}
</>
);
// Подкомпонент для ссылок магазинов
const StoreButtons: React.FC = () => (
// Подкомпонент для выпадающего меню магазинов
const StoreDropdown: React.FC<{ isOpen: boolean; toggle: () => void; breakpoint: string }> = ({
isOpen,
toggle,
breakpoint,
}) => {
const subMenuRef = useRef(null);
return (
Магазины
<ChevronDownIcon className={h-5 w-5 ml-1 transition-transform ${isOpen ? 'rotate-180' : 'rotate-0'}} />
{isOpen && (
<motion.div
ref={subMenuRef}
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
className="absolute mt-2 bg-white dark:bg-neutral-800 border border-neutral-300 dark:border-neutral-700 rounded-lg shadow-lg py-2 w-48"
>
{storeLinks.map((store) => (
<Image src={store.iconSrc} alt={${store.name} Icon} className="w-5 h-5 mr-2" width={20} height={20} loading="lazy" />
{store.name}
))}
</motion.div>
)}
);
};
export default function Navbar() {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const [isSubMenuOpen, setIsSubMenuOpen] = useState(false);
const [currentBreakpoint, setCurrentBreakpoint] = useState('');
const subMenuButtonRef = useRef(null);
const subMenuRef = useRef(null);
// Определение брейкпоинта
const getBreakpoint = useCallback((width: number): string => {
if (width >= 1536) return '2xl';
if (width >= 1280) return 'xl';
if (width >= 1024) return 'lg';
if (width >= 768) return 'md';
if (width >= 640) return 'sm';
return 'xs';
}, []);
// Обновление брейкпоинта при изменении размера окна
useEffect(() => {
const updateBreakpoint = () => {
const width = window.innerWidth;
const bp = getBreakpoint(width);
setCurrentBreakpoint(bp);
};
updateBreakpoint();
window.addEventListener('resize', updateBreakpoint);
return () => window.removeEventListener('resize', updateBreakpoint);
// Закрытие подменю при клике вне его
useEffect(() => {
if (!isSubMenuOpen) return;
const handleClickOutside = (event: MouseEvent) => {
const button = subMenuButtonRef.current;
const menu = subMenuRef.current;
if (button && menu && !button.contains(event.target as Node) && !menu.contains(event.target as Node)) {
setIsSubMenuOpen(false);
}
};
document.addEventListener('click', handleClickOutside);
return () => document.removeEventListener('click', handleClickOutside);
// Блокировка прокрутки при открытом мобильном меню
useEffect(() => {
if (isMenuOpen) {
const originalStyle = window.getComputedStyle(document.body).overflow;
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = originalStyle;
};
}
}, [isMenuOpen]);
// Закрытие мобильного меню при смене брейкпоинта на больший
useEffect(() => {
if (currentBreakpoint === 'lg' && isMenuOpen) {
setIsMenuOpen(false);
}
}, [currentBreakpoint, isMenuOpen]);
// Оптимизация переключения мобильного меню
const toggleMenu = useCallback(() => {
setIsMenuOpen((prev) => !prev);
}, []);
// Оптимизация переключения подменю
const toggleSubMenu = useCallback(() => {
setIsSubMenuOpen((prev) => !prev);
}, []);
// Мемоизация навигационных ссылок
const memoizedNavLinks = useMemo(() => , []);
return (
<>
{/* Логотип и основные ссылки /}
{/ Навигационные ссылки для больших экранов /}
{memoizedNavLinks}
{currentBreakpoint === 'lg' && (
)}
{/ Ссылки магазинов для больших экранов */}
{currentBreakpoint !== 'lg' && }
{/* Кнопки справа */}
<div className="flex items-center space-x-2">
<ThemeSwitchButton />
{/* Отображение брейкпоинта на больших экранах */}
<div className="hidden lg:flex items-center ml-2">
<span className="px-2 py-1 text-xs font-semibold text-white bg-blue-500 rounded-full">
{currentBreakpoint.toUpperCase()}
</span>
</div>
{/* Кнопка мобильного меню */}
<div className="lg:hidden">
<button
className="inline-flex items-center justify-center p-2 rounded-full h-10 w-10 text-neutral-900 dark:text-white hover:bg-gray-200 dark:hover:bg-neutral-800 transition-colors relative"
onClick={toggleMenu}
aria-label="Toggle Menu"
aria-expanded={isMenuOpen}
>
<div className="relative w-6 h-6">
<AnimatePresence mode="wait" initial={false}>
{isMenuOpen ? (
<motion.div
key="xmark"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.3 }}
className="absolute inset-0"
>
<XMarkIcon className="h-6 w-6" />
</motion.div>
) : (
<motion.div
key="bars"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.3 }}
className="absolute inset-0"
>
<Bars3Icon className="h-6 w-6" />
</motion.div>
)}
</AnimatePresence>
</div>
<span className="absolute -top-2 -right-2 bg-blue-500 text-white text-xs rounded-full px-1">
{currentBreakpoint.toUpperCase()}
</span>
</button>
</div>
</div>
</div>
</div>
</nav>
{/* Мобильное меню */}
<AnimatePresence>
{isMenuOpen && (
<motion.div
key="mobile-menu"
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.3 }}
className="fixed inset-0 bg-white dark:bg-neutral-900 z-20 pt-16 overflow-y-auto"
>
<div className="flex flex-col items-center space-y-4 py-8 px-4">
{navigation.map((item) => (
<Link key={item.name} href={item.href}>
<span
className="w-full flex items-center justify-center text-xl font-medium hover:text-red-500 cursor-pointer"
onClick={() => setIsMenuOpen(false)}
>
{item.emoji && <span className="mr-2 text-2xl">{item.emoji}</span>}
{item.name}
</span>
</Link>
))}
{/* Подменю магазинов в мобильном меню */}
<div className="w-full">
<button
onClick={toggleSubMenu}
className="w-full flex items-center justify-center text-xl font-medium hover:text-red-500 focus:outline-none"
aria-haspopup="true"
aria-expanded={isSubMenuOpen}
>
<span className="mr-2 text-2xl">🛒</span>
Магазины
<ChevronDownIcon className={`h-6 w-6 ml-1 transition-transform ${isSubMenuOpen ? 'rotate-180' : 'rotate-0'}`} />
</button>
<AnimatePresence>
{isSubMenuOpen && (
<motion.div
key="submenu"
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.3 }}
className="flex flex-col items-center mt-4 space-y-4"
>
<div className="w-full max-w-xs mx-auto flex flex-col space-y-4">
{storeLinks.map((store) => (
<Link
key={store.name}
href={store.href}
className="flex items-center justify-center w-full text-lg font-medium px-4 py-2 bg-neutral-100 dark:bg-neutral-700 rounded-md transition-transform duration-300 hover:scale-105 whitespace-nowrap"
target="_blank"
rel="noopener noreferrer"
>
<Image src={store.iconSrc} alt={`${store.name} Icon`} className="w-6 h-6 mr-3" width={24} height={24} loading="lazy" />
{store.name}
</Link>
))}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
</>
import { useState, useMemo } from "react";
import Link from "next/link";
import {
CheckIcon,
XMarkIcon,
MagnifyingGlassIcon,
ChevronDownIcon,
} from "@heroicons/react/24/solid";
import { motion } from "framer-motion";
// Types and Interfaces
type ProductType = "Все" | "Мультимарочные" | "Марочные" | "Адаптеры elm";
interface Product {
title: string;
description: string;
features: string[];
downloadLinks: DownloadLink[];
mostPopular: boolean;
docs: boolean;
docsLinks: DownloadLink[];
type: ProductType;
}
interface DownloadLink {
link: string;
label: string;
}
interface ProductCardProps {
product: Product;
onDownloadClick: (links: DownloadLink[]) => void;
}
interface ModalProps {
modalLinks: DownloadLink[] | null;
onCloseModal: () => void;
}
// Static Content
const products: Product[] = [
{
title: "Delphi DS150e",
description: "Многофункциональный диагностический инструмент для легковых и грузовых автомобилей.",
features: ["Delphi 2021.10b, Delphi + Delphi 2020.23", "Инструкции по установке ПО", "Руководство пользователя", "Руководство пользователя"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/BiaqYzKpxZRTc58 ", label: "Скачать с сервера 1" },
{ link: "https://nch.pl/s/8MZQfLRjSy9z4Bk ", label: "Скачать с сервера 2" }
],
mostPopular: false,
docs: true,
docsLinks: [
{ link: "https://i.getspace.us/cloud/s/7BwyBJf2YHxEkaC ", label: "Инструкция по установке Delphi 2020.23" },
{ link: "https://i.getspace.us/cloud/s/qJRfJdgjsqkPxme ", label: "Инструкция по установке Delphi 2021.10b" }
],
type: "Мультимарочные"
},
{
title: "Autocom CDP+",
description: "Универсальный диагностический сканер для чтения и удаления кодов неисправностей.",
features: ["Autocom 2021.11, Delphi + Autocom 2020.23"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/S9CKwWMNDbeB2XH ", label: "Скачать с сервера 1" },
{ link: "https://nch.pl/s/XbJnfSYNiw3dzFm ", label: "Скачать с сервера 2" }
],
mostPopular: true,
docs: true,
docsLinks: [
{ link: "https://i.getspace.us/cloud/s/xdr4QZqwsR6k8rr ", label: "Инструкция по установке Autocom 2020.23" },
{ link: "https://i.getspace.us/cloud/s/bbRzaksyH6LkSg4 ", label: "Инструкция по установке Autocom 2021.11" },
],
type: "Мультимарочные"
},
{
title: "Wurth WoW Snooper+",
description: "Инструмент диагностики автомобилей для чтения и удаления кодов неисправностей.",
features: ["Wurth WoW 5.00.8", "Инструкция по установке ПО", "Руководство пользователя"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/eTR2gqbEbZi66Md ", label: "Скачать с сервера 1" },
{ link: "https://nch.pl/s/KCCEPPDbpb7j7oJ ", label: "Скачать с сервера 2" },
],
mostPopular: false,
docs: false,
docsLinks: [],
type: "Мультимарочные"
},
{
title: "MUCAR BT200/Thinkcar Mini/Thinkdiag",
description: "Универсальные мобильные приборы для диагностики автомобилей.",
features: ["Diagzone", "ProDiag", "X-DIAG", "X-PRO5"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/fAMr3QsBMekwR2n ", label: "Скачать с сервера 1" },
{ link: "https://nch.pl/s/T6c4C7Gj5Me3mGF ", label: "Скачать с сервера 2" },
],
mostPopular: false,
docs: false,
docsLinks: [],
type: "Мультимарочные"
},
{
title: "Galletto 1260",
description: "Универсальный программатор для чип-тюнинга, чтения и удаления кодов неисправностей.",
features: ["Galletto 1260", "Драйвер"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/dfYejQP9rZGK9Td ", label: "Скачать с сервера 1" }
],
mostPopular: false,
docs: false,
docsLinks: [],
type: "Мультимарочные"
},
{
title: "VCDS + Вася",
description: "Диагностический инструмент для автомобилей Volkswagen Group.",
features: ["Вася, VCDS", "Инструкции по установке ПО", "Сборники кодировок", "Видеокурсы"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/R7ycKecn9P6b55a ", label: "Скачать с сервера 1" },
{ link: "https://nch.pl/s/mnBd982CC52NEko ", label: "Скачать с сервера 2" },
],
mostPopular: true,
docs: true,
docsLinks: [
{ link: "https://i.getspace.us/cloud/s/bmi7a7zdHbXHMnB ", label: "Инструкция 1" },
],
type: "Марочные"
},
{
title: "BMW E-NET (E-Sys)",
description: "Диагностическая система для автомобилей BMW.",
features: ["E-SYS", "Rheingold", "ISTA+", "ISTA-P", "Инструкции по установке ПО"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/jiiandKXdi6BEJS ", label: "Скачать с сервера 1" }
],
mostPopular: false,
docs: false,
docsLinks: [],
type: "Марочные"
},
{
title: "K-Dcan INPA",
description: "Диагностическая система для автомобилей BMW.",
features: ["Rheingold", "INPA", "ISTA-D", "DIS", "NCS", "Инструкции по установке ПО"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/jiiandKXdi6BEJS ", label: "Скачать с сервера 1" }
],
mostPopular: false,
docs: false,
docsLinks: [],
type: "Марочные"
},
{
title: "ELS 27",
description: "Диагностический интерфейс для автомобилей Ford и Mazda.",
features: ["FORScan", "FoCCCus", "ELMConfig", "Инструкции по установке ПО"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/oBNcC2w85wnj2Lx ", label: "Скачать с сервера 1" }
],
mostPopular: false,
docs: false,
docsLinks: [],
type: "Марочные"
},
{
title: "Mini-VCI",
description: "Диагностический инструмент для автомобилей Toyota и Lexus.",
features: ["Techstream ", "Инструкция по установке ПО"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/Q3kWQ8ajB8WdF5g ", label: "Скачать с сервера 1" }
],
mostPopular: false,
docs: false,
docsLinks: [],
type: "Марочные"
},
{
title: "Lexia 3/PP2000",
description: "Диагностический инструмент для автомобилей Peugeot и Citroen.",
features: ["Diagbox", "Инструкция по установке ПО"],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/eBmZpZWza2kt2Dc ", label: "Скачать с сервера 1" }
],
mostPopular: false,
docs: false,
docsLinks: [],
type: "Марочные"
},
{
title: "ELM 327 Mini",
description: "Универсальный диагностический сканер для автомобилей, который подключается к порту OBD-II и работает через приложение на смартфоне или компьютере.",
features: ["EOBD Facile", "Car Scanner", "Torque", "ELMScan", "Carista", "BimmerCode", "LeafSpy", "и т.д."],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/Xg9rLCQgfZbedxe ", label: "Скачать с сервера 1" },
{ link: "https://nch.pl/s/7jirqk7RWaqYwCM ", label: "Скачать с сервера 1" },
],
mostPopular: true,
docs: false,
docsLinks: [],
type: "Адаптеры elm"
},
{
title: "Kingbolen ELM",
description: "Диагностический инструмент для автомобилей, оснащенный функцией Bluetooth/Wi-Fi и поддерживающий различные протоколы OBD-II, что позволяет работать с разными автомобильными брендами.",
features: ["EOBD Facile", "Car Scanner", "Torque", "ELMScan", "Carista", "BimmerCode", "LeafSpy", "и т.д."],
downloadLinks: [
{ link: "https://i.getspace.us/cloud/s/Xg9rLCQgfZbedxe ", label: "Скачать с сервера 1" },
{ link: "https://nch.pl/s/7jirqk7RWaqYwCM ", label: "Скачать с сервера 1" },
],
mostPopular: false,
docs: false,
docsLinks: [],
type: "Адаптеры elm"
}
];
const deviceTypes: ProductType[] = [
"Все",
"Мультимарочные",
"Марочные",
"Адаптеры elm",
];
// Helper Components
function ProductCard({ product, onDownloadClick }: ProductCardProps) {
const { title, mostPopular, description, features, downloadLinks, docs, docsLinks } = product;
const displayedFeatures =
features.length > 4 ? [...features.slice(0, 3), "и т.д."] : features;
return (
<motion.div
className="relative rounded-2xl p-6 bg-white dark:bg-gray-800 shadow-md hover:shadow-xl transition-shadow duration-300 flex flex-col border border-gray-300 dark:border-gray-700"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
whileHover={{ scale: 1.02 }}
>
{mostPopular && (
Топ продаж
)}
{title}
{description}
<motion.button
onClick={() => onDownloadClick(downloadLinks)}
className="flex-1 px-4 py-2 bg-red-500 text-white rounded-lg shadow hover:bg-red-600 transition-colors duration-300"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
Скачать
</motion.button>
{docs && docsLinks.length > 0 && (
<motion.button
onClick={() => onDownloadClick(docsLinks)}
className="flex-1 px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-300 rounded-lg shadow hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors duration-300"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
Инструкция
</motion.button>
)}
В комплекте:
{displayedFeatures.map((feature, index) => (
{feature}
))}
</motion.div>
);
}
function Modal({ modalLinks, onCloseModal }: ModalProps) {
if (!modalLinks) return null;
return (
<motion.div
className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={onCloseModal}
>
<motion.div
className="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-lg max-w-sm w-full relative"
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.8, opacity: 0 }}
transition={{ duration: 0.3 }}
onClick={(e) => e.stopPropagation()}
>
Выберите ссылку для скачивания
{modalLinks.map(({ link, label }) => (
{label}
))}
</motion.div>
</motion.div>
);
}
// Main Component
export default function Soft() {
const [selectedType, setSelectedType] = useState("Все");
const [modalLinks, setModalLinks] = useState<DownloadLink[] | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const [isSearchOpen, setIsSearchOpen] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const productsPerPage = 8;
const handleDownloadClick = (links: DownloadLink[]) => {
if (links.length === 1) {
window.open(links[0].link, "_blank", "noopener noreferrer");
} else {
setModalLinks(links);
}
};
const closeModal = () => setModalLinks(null);
const filteredProducts = useMemo(
() =>
products.filter(
({ type, title }) =>
(selectedType === "Все" || type === selectedType) &&
title.toLowerCase().includes(searchQuery.toLowerCase())
),
[selectedType, searchQuery]
);
const totalPages = useMemo(
() => Math.ceil(filteredProducts.length / productsPerPage),
[filteredProducts]
);
const currentProducts = useMemo(() => {
const indexOfLastProduct = currentPage * productsPerPage;
const indexOfFirstProduct = indexOfLastProduct - productsPerPage;
return filteredProducts.slice(indexOfFirstProduct, indexOfLastProduct);
}, [filteredProducts, currentPage]);
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
const nextPage = () =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages));
const prevPage = () =>
setCurrentPage((prev) => Math.max(prev - 1, 1));
return (
{/* Main Content */}
<motion.h2
className="text-4xl font-extrabold text-center text-black dark:text-white"
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.6 }}
>
Программы для оборудования 💻
</motion.h2>
<motion.p
className="pt-6 text-lg max-w-2xl text-center m-auto text-gray-700 dark:text-gray-300"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.3, duration: 0.6 }}
>
В этом разделе вы можете скачать программное обеспечение для своего
устройства. Для начала определите тип вашего устройства — "Марочный" или "Мультимарочный". Информацию о типе устройства вы найдёте в упаковке. После этого найдите карточку с вашим устройством и нажмите кнопку "Скачать". Инструкция по установке программного обеспечения находится на кнопке "Инструкция".
</motion.p>
{/* Mobile Menu */}
<div className="lg:hidden flex flex-col items-center pt-4">
<motion.div
className="bg-gray-100 dark:bg-gray-800 p-4 rounded-lg shadow-md w-full max-w-xs"
layout
>
<div className="flex items-center justify-between">
<motion.button
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-black dark:text-white rounded-full flex items-center justify-between w-full"
onClick={() => {
setIsMobileMenuOpen((prev) => !prev);
if (isSearchOpen) setIsSearchOpen(false);
}}
aria-expanded={isMobileMenuOpen}
aria-label="Выберите категорию"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<span>{selectedType}</span>
<motion.div
animate={{ rotate: isMobileMenuOpen ? 180 : 0 }}
transition={{ duration: 0.2 }}
>
<ChevronDownIcon className="w-5 h-5" />
</motion.div>
</motion.button>
<motion.button
className="ml-4 px-4 py-2 bg-gray-200 dark:bg-gray-700 text-black dark:text-white rounded-full shadow"
onClick={() => {
setIsSearchOpen((prev) => !prev);
if (isMobileMenuOpen) setIsMobileMenuOpen(false);
}}
aria-label="Поиск"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<MagnifyingGlassIcon className="w-6 h-6" />
</motion.button>
</div>
{/* Dropdown */}
<motion.ul
className="bg-gray-100 dark:bg-gray-800 rounded-lg overflow-hidden text-center m-0 p-0 list-none"
initial={false}
animate={
isMobileMenuOpen
? { opacity: 1, height: "auto", marginTop: "1rem" }
: { opacity: 0, height: 0, marginTop: 0 }
}
transition={{ duration: 0.3 }}
>
{deviceTypes.map((type, index) => (
<li
key={type}
className={`text-black dark:text-white px-4 py-2 leading-tight hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer rounded-none ${
index === 0 ? "first:rounded-t-none" : ""
} ${
index === deviceTypes.length - 1 ? "last:rounded-b-none" : ""
}`}
onClick={() => {
setSelectedType(type);
setIsMobileMenuOpen(false);
}}
>
{type}
</li>
))}
</motion.ul>
{/* Search Bar */}
<motion.div
className="overflow-hidden w-full"
initial={false}
animate={
isSearchOpen
? { opacity: 1, height: "auto", marginTop: "1rem" }
: { opacity: 0, height: 0, marginTop: 0 }
}
transition={{ duration: 0.3 }}
>
<input
type="text"
placeholder="Поиск..."
id="mobile-search"
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
setCurrentPage(1);
}}
className="w-full px-4 py-2 border-none focus:outline-none bg-gray-100 dark:bg-gray-700 dark:text-white rounded-lg"
/>
</motion.div>
</motion.div>
</div>
{/* Desktop Filters and Search */}
<div className="hidden lg:block max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 mt-8">
<div className="max-w-max mx-auto flex flex-wrap items-center bg-gray-100 dark:bg-gray-800 p-2 rounded-lg shadow space-y-4 sm:space-y-0 sm:space-x-4">
<div className="flex flex-wrap gap-2">
{deviceTypes.map((type) => (
<motion.button
key={type}
onClick={() => {
setSelectedType(type);
setCurrentPage(1);
}}
className={`px-4 py-2 rounded-full text-sm font-medium transition-colors duration-300 ${
selectedType === type
? "bg-red-500 text-white shadow-lg"
: "bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600"
}`}
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
{type}
</motion.button>
))}
</div>
<div className="w-full sm:w-auto mt-4 sm:mt-0">
<input
type="text"
placeholder="Поиск..."
id="desktop-search"
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
setCurrentPage(1);
}}
className="w-full sm:w-64 px-4 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 dark:bg-gray-700 dark:text-white"
/>
</div>
</div>
</div>
{/* Product Cards */}
<motion.div
className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-16 pb-16 grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-x-6 gap-y-16"
initial={false}
animate="visible"
variants={{
hidden: {},
visible: {
transition: { staggerChildren: 0.1 },
},
}}
>
{currentProducts.map((product) => (
<ProductCard
key={product.title}
product={product}
onDownloadClick={handleDownloadClick}
/>
))}
</motion.div>
{/* Pagination */}
{totalPages > 1 && (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-16 flex justify-center items-center space-x-2">
<button
onClick={prevPage}
disabled={currentPage === 1}
className={`px-3 py-1 rounded-md text-sm font-medium ${
currentPage === 1
? "bg-gray-300 text-gray-500 cursor-not-allowed"
: "bg-red-500 text-white hover:bg-red-600"
} transition-colors duration-300`}
>
Предыдущая
</button>
{Array.from({ length: totalPages }, (_, index) => index + 1).map(
(number) => (
<button
key={number}
onClick={() => paginate(number)}
className={`px-3 py-1 rounded-md text-sm font-medium ${
currentPage === number
? "bg-red-600 text-white"
: "bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600"
} transition-colors duration-300`}
>
{number}
</button>
)
)}
<button
onClick={nextPage}
disabled={currentPage === totalPages}
className={`px-3 py-1 rounded-md text-sm font-medium ${
currentPage === totalPages
? "bg-gray-300 text-gray-500 cursor-not-allowed"
: "bg-red-500 text-white hover:bg-red-600"
} transition-colors duration-300`}
>
Следующая
</button>
</div>
)}
{/* Modal */}
{modalLinks && <Modal modalLinks={modalLinks} onCloseModal={closeModal} />}
</div>
import React, { useState, useMemo } from "react";
import Image from "next/image";
import Link from "next/link";
import { motion } from "framer-motion";
const categories = [
{ name: "Все", value: "Все" },
{ name: "Установка ПО", value: "Установка ПО" },
{ name: "Оборудование", value: "Оборудование" },
{ name: "Советы", value: "Советы" },
{ name: "Общее", value: "Общее" },
{ name: "Ошибки", value: "Ошибки" },
];
const blogPosts = [
{
title: "Как справиться с ошибкой при открытии архива",
image: "/images/blog/post1.jpg",
excerpt: "Узнайте, как справиться с наиболее частыми ошибками при открытии архивов.",
link: "/articles/errors/archive",
category: "Ошибки",
keywords: ["ошибки архива", "проблемы с архивом", "ошибка открытия архива", "архив"],
},
{
title: "Инструкция по установке Autocom 2021",
image: "/images/blog/post1.jpg",
excerpt: "Полноценная, подробная инструкция по установке программного обеспечения.",
link: "/articles/software/autocom2021",
category: "Установка ПО",
keywords: ["установка ПО", "Autocom 2021", "инструкция"],
},
{
title: "тест",
image: "/images/blog/post1.jpg",
excerpt: "тест.",
link: "/articles/software/autocom2021",
category: "Установка ПО",
keywords: ["установка ПО", "Autocom 2021", "инструкция"],
},
{
title: "Инструкdция по установке Autocom 2021 Инструкdция по установке Autocom 2021 Инструкdция по установке Autocom 2021",
image: "/images/blog/post1.jpg",
excerpt: "Инструкdция по установке Autocom 2021 Инструкdция по установке Autocom 2021 Инструкdция по установке Autocom 2021",
link: "/articles/software/autocom2021",
category: "Установка ПО",
keywords: ["установка ПО", "Autocom 2021", "инструкция"],
},
];
export default function Blog() {
const [selectedCategory, setSelectedCategory] = useState("Все");
const [searchTerm, setSearchTerm] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const filteredPosts = useMemo(() => {
const filteredByCategory = selectedCategory === "Все" ? blogPosts : blogPosts.filter((post) => post.category === selectedCategory);
return filteredByCategory.filter(
(post) =>
post.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
post.excerpt.toLowerCase().includes(searchTerm.toLowerCase())
);
}, [selectedCategory, searchTerm]);
const paginatedPosts = useMemo(() => {
const startIndex = (currentPage - 1) * postsPerPage;
return filteredPosts.slice(startIndex, startIndex + postsPerPage);
}, [currentPage, filteredPosts]);
const totalPages = Math.ceil(filteredPosts.length / postsPerPage);
const handlePageChange = (page: number) => {
setCurrentPage(page);
};
return (
{/* Заголовок */}
<motion.h2
className="text-4xl font-extrabold text-center text-black dark:text-white"
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.6 }}
>
Статьи 💻
</motion.h2>
<motion.p
className="pt-6 text-lg max-w-2xl text-center m-auto text-gray-700 dark:text-gray-300"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.3, duration: 0.6 }}
>
В этом разделе вы можете найти статьи и решения по программному обеспечению.
</motion.p>
{/* Фильтры */}
<div className="max-w-max mx-auto px-4 sm:px-6 lg:px-8 mt-8">
<div className="flex flex-wrap items-center bg-gray-100 dark:bg-gray-800 p-4 rounded-lg shadow space-y-4 sm:space-y-0 sm:space-x-4">
<div className="flex flex-wrap gap-2">
{categories.map((category) => (
<motion.button
key={category.value}
onClick={() => setSelectedCategory(category.value)}
className={`px-4 py-2 rounded-full text-sm font-medium transition-colors duration-300 ${
selectedCategory === category.value
? "bg-red-500 text-white shadow-lg"
: "bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600"
}`}
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
{category.name}
</motion.button>
))}
</div>
{/* Поиск */}
<div className="w-full sm:w-auto mt-4 sm:mt-0">
<input
type="text"
placeholder="Поиск..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full sm:w-64 px-4 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 dark:bg-gray-700 dark:text-white"
/>
</div>
</div>
</div>
{/* Карточки статей */}
<motion.div
className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-16 pb-16 grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-x-6 gap-y-16"
initial="hidden"
animate="visible"
variants={{
hidden: {},
visible: {
transition: {
staggerChildren: 0.1,
},
},
}}
>
{paginatedPosts.map(({ title, image, excerpt, link }) => (
<motion.div
key={title}
className="relative rounded-2xl p-6 bg-white dark:bg-gray-800 shadow-md hover:shadow-xl transition-shadow duration-300 flex flex-col border border-gray-300 dark:border-gray-700"
variants={{
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 },
}}
whileHover={{ scale: 1.02 }}
>
{/* Изображение */}
<Link href={link}>
<div className="relative h-48 mb-4 rounded-lg overflow-hidden">
<Image
src={image}
alt={title}
layout="fill"
objectFit="cover"
className="w-full h-full"
/>
</div>
</Link>
{/* Заголовок */}
<h3 className="text-xl font-extrabold text-black dark:text-white mb-2 line-clamp-3">{title}</h3>
{/* Описание */}
<p className="text-gray-700 dark:text-gray-300 flex-grow line-clamp-5 mb-4">{excerpt}</p>
{/* Кнопка */}
<Link href={link}>
<motion.button
className="w-full px-4 py-2 bg-red-500 text-white rounded-lg shadow hover:bg-red-600 transition-colors duration-300"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
Читать далее
</motion.button>
</Link>
</motion.div>
))}
</motion.div>
{/* Пагинация */}
{totalPages > 1 && (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-16 flex justify-center items-center space-x-2">
<button
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
className={`px-3 py-1 rounded-md text-sm font-medium ${
currentPage === 1
? "bg-gray-300 text-gray-500 cursor-not-allowed"
: "bg-red-500 text-white hover:bg-red-600"
} transition-colors duration-300`}
>
Предыдущая
</button>
{Array.from({ length: totalPages }, (_, index) => index + 1).map((number) => (
<button
key={number}
onClick={() => handlePageChange(number)}
className={`px-3 py-1 rounded-md text-sm font-medium ${
currentPage === number
? "bg-red-600 text-white"
: "bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600"
} transition-colors duration-300`}
>
{number}
</button>
))}
<button
onClick={() => handlePageChange(currentPage + 1)}
disabled={currentPage === totalPages}
className={`px-3 py-1 rounded-md text-sm font-medium ${
currentPage === totalPages
? "bg-gray-300 text-gray-500 cursor-not-allowed"
: "bg-red-500 text-white hover:bg-red-600"
} transition-colors duration-300`}
>
Следующая
</button>
</div>
)}
</div>
import Link from 'next/link';
import { motion } from 'framer-motion';
// Определение интерфейсов внутри файла
interface MenuItem {
title: string;
url: string;
}
interface SocialLink {
name: string;
href: string;
iconPath: string;
}
// Определение меню
const menus: MenuItem[] = [
{ title: 'Главная', url: '/' },
{ title: 'Программы', url: '/soft' },
{ title: 'О нас', url: '/about' },
{ title: 'Статьи', url: '/articles' },
{ title: 'Обратная связь', url: '/contact' },
];
// Определение социальных ссылок с SVG путями
const socialLinks: SocialLink[] = [
{
name: 'Telegram',
href: 'https://смартдиаг-поддержка.рф/telegram',
iconPath:
'M18.384,22.779c0.322,0.228 0.737,0.285 1.107,0.145c0.37,-0.141 0.642,-0.457 0.724,-0.84c0.869,-4.084 2.977,-14.421 3.768,-18.136c0.06,-0.28 -0.04,-0.571 -0.26,-0.758c-0.22,-0.187 -0.525,-0.241 -0.797,-0.14c-4.193,1.552 -17.106,6.397 -22.384,8.35c-0.335,0.124 -0.553,0.446 -0.542,0.799c0.012,0.354 0.25,0.661 0.593,0.764c2.367,0.708 5.474,1.693 5.474,1.693c0,0 1.452,4.385 2.209,6.615c0.095,0.28 0.314,0.5 0.603,0.576c0.288,0.075 0.596,-0.004 0.811,-0.207c1.216,-1.148 3.096,-2.923 3.096,-2.923c0,0 3.572,2.619 5.598,4.062Zm-11.01,-8.677l1.679,5.538l0.373,-3.507c0,0 6.487,-5.851 10.185,-9.186c0.108,-0.098 0.123,-0.262 0.033,-0.377c-0.089,-0.115 -0.253,-0.142 -0.376,-0.064c-4.286,2.737 -11.894,7.596 -11.894,7.596Z',
},
{
name: 'WhatsApp',
href: 'https://смартдиаг-поддержка.рф/whatsapp',
iconPath:
'M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.893-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.481 5.236 3.48 8.414-.003 6.557-5.338 11.892-11.893 11.892-1.99-.001-3.951-.5-5.688-1.448l-6.305 1.654zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884-.001 2.225.651 3.891 1.746 5.634l-.999 3.648 3.742-.981zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.695.248-1.29.173-1.414z',
},
];
// Начальный год
const startYear = 2023;
export default function Footer() {
const currentYear = new Date().getFullYear();
return (
{/* Раздел авторских прав */}
SmartDiag © {startYear}-{currentYear}
{/* Раздел меню */}
<nav className="mb-4 lg:mb-0">
<ul className="flex flex-wrap gap-6 justify-center">
{menus.map(({ title, url }) => (
<li key={title}>
<Link href={url} className="hover:text-red-500 font-medium">
{title}
</Link>
</li>
))}
</ul>
</nav>
{/* Раздел социальных ссылок */}
<div className="flex space-x-4 justify-center lg:justify-end">
{socialLinks.map(({ name, href, iconPath }) => (
<motion.a
key={name}
href={href}
target="_blank"
rel="noopener noreferrer"
aria-label={name}
className="hover:text-red-500"
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.95 }}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="currentColor"
className="h-6 w-6"
xmlns="http://www.w3.org/2000/svg"
>
<path d={iconPath} />
</svg>
</motion.a>
))}
</div>
</div>
</footer>
// src/pages/articles.tsx
import Head from "next/head";
import Articles from "../components/Articles";
const ArticlesPage: React.FC = () => {
return (
<>
{/* Мета-теги для SEO /}
Статьи - SmartDiag
{/ Дополнительные мета-теги можно добавить по необходимости */}
{/* Компонент Статей */}
<Articles />
</>
export default ArticlesPage;
import Head from "next/head";
import Soft from "../components/Soft"; // Импорт компонента Soft без деструктуризации
const SoftPage: React.FC = () => {
return (
<>
{/* Мета-теги для SEO /}
Программы - SmartDiag
{/ Указываем favicon */}
{/* Компонент Программ */}
<Soft />
</>
The issue you're experiencing is due to how Next.js handles route changes and the need to properly set up page transitions with Framer Motion. When you navigate between pages, Next.js by default scrolls to the top, which causes your current page to jump to the top before the exit animation plays. To fix this, you need to:
Wrap your pages with AnimatePresence in _app.tsx : This allows Framer Motion to handle page transitions properly.
Prevent Next.js from automatically scrolling to the top on route changes : You can do this by setting scroll={false} on your Link components or by customizing the scroll behavior globally.
Ensure your motion components have the correct keys : This helps AnimatePresence detect route changes and apply animations correctly.
Here's how you can implement these steps:
1. Create or Modify src/pages/_app.tsx
In Next.js, the _app.tsx file allows you to override the default App component and wrap your pages with additional components like AnimatePresence. Here's how you can set it up:
// src/pages/_app.tsx
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { AnimatePresence, motion } from 'framer-motion';
import type { AppProps } from 'next/app';
import Layout from '../components/Layout'; // Ensure you have this import
function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter();
useEffect(() => {
// Prevent Next.js from restoring scroll position on route changes
if ('scrollRestoration' in window.history) {
window.history.scrollRestoration = 'manual';
}
}, []);
return (
<AnimatePresence exitBeforeEnter initial={false}>
<motion.div
key={router.asPath}
initial="initial"
animate="animate"
exit="exit"
variants={{
initial: { opacity: 0 },
animate: { opacity: 1 },
exit: { opacity: 0 },
}}
transition={{ duration: 0.5, ease: 'easeInOut' }}
>
<Layout>
<Component {...pageProps} />
</Layout>
</motion.div>
</AnimatePresence>
);
}
export default MyApp;
Explanation:
We wrap the entire application with AnimatePresence to handle exit animations.
The key prop on motion.div is set to router.asPath to ensure that the animations trigger when the route changes.
By setting window.history.scrollRestoration = 'manual', we prevent Next.js from automatically scrolling to the top during route changes.
2. Adjust Your Layout.tsx
Since we're handling the animations in _app.tsx, you can remove the motion.main from your Layout.tsx or adjust it accordingly:
// src/components/Layout.tsx
// ... (imports remain the same)
const Layout = ({ children, image, type, metadata }: LayoutProps) => {
const router = useRouter();
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || '';
return (
<div className="flex flex-col min-h-screen">
{/* ... (Head component remains the same) */}
<Navbar />
<main className="flex-grow">
{children}
</main>
<Footer />
</div>
);
};
export default Layout;
Explanation:
We replaced motion.main with a regular <main> because we're now handling page transitions in the _app.tsx file.
3. Add scroll={false} to Your Link Components
To prevent individual Link components from scrolling to the top when clicked, add the scroll={false} prop to them:
// Example modification in components/Navbar.tsx (and similarly in Footer.tsx)
<Link
key={item.name}
href={item.href}
scroll={false} // Add this prop
className="relative text-base lg:text-lg font-bold text-neutral-900 dark:text-neutral-400 hover:text-red-500 before:content-[''] before:absolute before:bottom-0 before:left-0 before:w-0 before:h-[2px] before:bg-red-500 hover:before:w-full before:transition-all before:duration-300 before:ease-in-out whitespace-nowrap"
>
{item.name}
</Link>
Explanation:
Adding scroll={false} to the Link component tells Next.js not to scroll to the top when navigating to a new page using that link.
4. Test Your Application
After making these changes, test your application by navigating between pages. You should observe that:
The current page no longer jumps to the top before the exit animation plays.
The new page appears at the top after the transition.
Additional Notes
Managing Scroll Position on Entry: If you want the new page to scroll to the top after the animation, you can add a useEffect in your page components to scroll to the top when they mount.
import { useEffect } from 'react';
const PageComponent = () => {
useEffect(() => {
window.scrollTo(0, 0);
}, []);
// ... rest of your component
};
Consistency Across All Links: Make sure to add scroll={false} to all Link components that navigate between pages, including those in your footer or any other navigation elements.
Why This Works
AnimatePresence in _app.tsx: By wrapping your pages with AnimatePresence and motion.div in _app.tsx, you ensure that animations are applied during route changes. The key prop triggers the animation when the route (router.asPath) changes.
Preventing Scroll to Top: By disabling the automatic scroll behavior, we prevent the page from jumping to the top before the exit animation completes.
Persistent Layout Component: Keeping the Layout component wrapped around your pages ensures that the navigation and footer remain consistent and don't unmount during transitions, which can help maintain scroll positions and prevent unexpected behavior.
References
By following these steps, you should achieve smooth page transitions where the current page doesn't jump to the top before fading out, and the new page appears smoothly at the top after the transition.
Copy first response