Add first-visit tip and how-to guide for guests
- guests in the feed see a "New here?" tip with a waving hand: swipe up to dismiss on mobile (top), close button on desktop (bottom right); shown once, remembered in localStorage - GuideModal: six short steps (feed and map, map pins, posting, chat with photos/video, phone reveal, marking as returned) plus safety tips; guests get a sign-in button - "How it works" item in the mobile menu and the desktop sidebar - ru/en texts, tests, README Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
118
src/components/GuestGuide.test.jsx
Normal file
118
src/components/GuestGuide.test.jsx
Normal file
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Подсказка гостю «Ты здесь впервые?» и инструкция: появление с задержкой,
|
||||
* закрытие крестиком и смахиванием вверх, запоминание, открытие инструкции.
|
||||
*/
|
||||
import { render, screen, fireEvent, act } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom";
|
||||
import "../i18n";
|
||||
import i18n from "../i18n";
|
||||
import GuestGuideBanner, { GUIDE_BANNER_KEY } from "./GuestGuideBanner";
|
||||
import GuideModal from "./GuideModal";
|
||||
|
||||
beforeAll(() => i18n.changeLanguage("ru"));
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
jest.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
function showBanner(props = {}) {
|
||||
render(<GuestGuideBanner onOpenGuide={jest.fn()} {...props} />);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(1500);
|
||||
});
|
||||
}
|
||||
|
||||
test("подсказка появляется не сразу, а через секунду", () => {
|
||||
render(<GuestGuideBanner onOpenGuide={jest.fn()} />);
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(1500);
|
||||
});
|
||||
expect(screen.getByText("Ты здесь впервые?")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Посмотри, как пользоваться приложением/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("крестик закрывает подсказку навсегда", () => {
|
||||
showBanner();
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Скрыть подсказку"));
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(300);
|
||||
});
|
||||
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
expect(localStorage.getItem(GUIDE_BANNER_KEY)).toBe("1");
|
||||
});
|
||||
|
||||
test("закрытая подсказка больше не показывается", () => {
|
||||
localStorage.setItem(GUIDE_BANNER_KEY, "1");
|
||||
showBanner();
|
||||
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
});
|
||||
|
||||
test("смахивание вверх закрывает, короткое движение — нет", () => {
|
||||
showBanner();
|
||||
const banner = screen.getByRole("status");
|
||||
|
||||
// Чуть-чуть потянули — карточка возвращается на место
|
||||
fireEvent.touchStart(banner, { touches: [{ clientY: 100 }] });
|
||||
fireEvent.touchMove(banner, { touches: [{ clientY: 85 }] });
|
||||
fireEvent.touchEnd(banner);
|
||||
expect(localStorage.getItem(GUIDE_BANNER_KEY)).toBeNull();
|
||||
expect(screen.getByText("Ты здесь впервые?")).toBeInTheDocument();
|
||||
|
||||
// Смахнули вверх — закрылась и запомнилась
|
||||
fireEvent.touchStart(banner, { touches: [{ clientY: 100 }] });
|
||||
fireEvent.touchMove(banner, { touches: [{ clientY: 30 }] });
|
||||
fireEvent.touchEnd(banner);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(300);
|
||||
});
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
expect(localStorage.getItem(GUIDE_BANNER_KEY)).toBe("1");
|
||||
});
|
||||
|
||||
test("кнопка открывает инструкцию и убирает подсказку", () => {
|
||||
const onOpenGuide = jest.fn();
|
||||
showBanner({ onOpenGuide });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Как пользоваться" }));
|
||||
|
||||
expect(onOpenGuide).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByText("Ты здесь впервые?")).toBeNull();
|
||||
expect(localStorage.getItem(GUIDE_BANNER_KEY)).toBe("1");
|
||||
});
|
||||
|
||||
test("инструкция: шаги, безопасность и вход для гостя", () => {
|
||||
const onClose = jest.fn();
|
||||
const onLoginClick = jest.fn();
|
||||
render(<GuideModal onClose={onClose} onLoginClick={onLoginClick} />);
|
||||
|
||||
expect(screen.getByRole("dialog", { name: "Как пользоваться Находкой" })).toBeInTheDocument();
|
||||
// 6 шагов + 4 совета по безопасности
|
||||
expect(screen.getAllByRole("listitem")).toHaveLength(6 + 4);
|
||||
expect(screen.getByText("Ищи в ленте или на карте")).toBeInTheDocument();
|
||||
expect(screen.getByText("Смотри на карте")).toBeInTheDocument();
|
||||
expect(screen.getByText("Пиши автору")).toBeInTheDocument();
|
||||
expect(screen.getByText("Будь осторожен", { exact: false })).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Войти или зарегистрироваться" }));
|
||||
expect(onLoginClick).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.keyDown(window, { key: "Escape" });
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("инструкция для вошедшего — без кнопки входа", () => {
|
||||
render(<GuideModal onClose={jest.fn()} />);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Войти или зарегистрироваться" })).toBeNull();
|
||||
expect(screen.getByRole("button", { name: "Понятно" })).toBeInTheDocument();
|
||||
});
|
||||
124
src/components/GuestGuideBanner.jsx
Normal file
124
src/components/GuestGuideBanner.jsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
import "../styles/guide.css";
|
||||
|
||||
export const GUIDE_BANNER_KEY = "nakhodka:guideBannerDismissed";
|
||||
/** Подсказка появляется не сразу: сначала человек видит ленту. */
|
||||
const SHOW_DELAY_MS = 1200;
|
||||
/** Насколько смахнуть вверх, чтобы карточка закрылась, px. */
|
||||
const SWIPE_DISMISS_PX = 40;
|
||||
const LEAVE_ANIMATION_MS = 250;
|
||||
|
||||
export function isGuideBannerDismissed() {
|
||||
try {
|
||||
return localStorage.getItem(GUIDE_BANNER_KEY) === "1";
|
||||
} catch {
|
||||
return false; // приватный режим — просто покажем ещё раз
|
||||
}
|
||||
}
|
||||
|
||||
function rememberDismissed() {
|
||||
try {
|
||||
localStorage.setItem(GUIDE_BANNER_KEY, "1");
|
||||
} catch {
|
||||
// нет хранилища — подсказка вернётся при следующем визите, это не страшно
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ненавязчивая подсказка для гостя в ленте: «Ты здесь впервые?» с кнопкой
|
||||
* инструкции. На телефоне смахивается вверх, на десктопе закрывается крестиком
|
||||
* (крестик есть и на телефоне — смахивание доступно не всем). Закрытая или
|
||||
* открытая один раз подсказка больше не показывается.
|
||||
*
|
||||
* @param {{ onOpenGuide: () => void }} props
|
||||
*/
|
||||
export default function GuestGuideBanner({ onOpenGuide }) {
|
||||
const { t } = useTranslation();
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [leaving, setLeaving] = useState(false);
|
||||
const [drag, setDrag] = useState(0);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const startYRef = useRef(null);
|
||||
const leaveTimerRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isGuideBannerDismissed()) return undefined;
|
||||
const timer = setTimeout(() => setVisible(true), SHOW_DELAY_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => clearTimeout(leaveTimerRef.current), []);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
rememberDismissed();
|
||||
setLeaving(true);
|
||||
leaveTimerRef.current = setTimeout(() => setVisible(false), LEAVE_ANIMATION_MS);
|
||||
}, []);
|
||||
|
||||
const openGuide = () => {
|
||||
rememberDismissed();
|
||||
setVisible(false);
|
||||
onOpenGuide();
|
||||
};
|
||||
|
||||
const onTouchStart = (e) => {
|
||||
startYRef.current = e.touches[0].clientY;
|
||||
setDragging(true);
|
||||
};
|
||||
|
||||
const onTouchMove = (e) => {
|
||||
if (startYRef.current == null) return;
|
||||
const dy = e.touches[0].clientY - startYRef.current;
|
||||
// Вверх — тянется за пальцем, вниз — едва поддаётся (как у системных уведомлений)
|
||||
setDrag(dy < 0 ? dy : dy / 6);
|
||||
};
|
||||
|
||||
const onTouchEnd = () => {
|
||||
const shouldDismiss = drag < -SWIPE_DISMISS_PX;
|
||||
startYRef.current = null;
|
||||
setDragging(false);
|
||||
if (shouldDismiss) {
|
||||
dismiss();
|
||||
} else {
|
||||
setDrag(0);
|
||||
}
|
||||
};
|
||||
|
||||
if (!visible) return null;
|
||||
|
||||
const className = [
|
||||
"guest-banner",
|
||||
dragging ? "is-dragging" : "is-settling",
|
||||
leaving ? "is-leaving" : "",
|
||||
].join(" ");
|
||||
|
||||
return (
|
||||
<div
|
||||
className={className}
|
||||
role="status"
|
||||
style={{ "--banner-drag": `${drag}px` }}
|
||||
onTouchStart={onTouchStart}
|
||||
onTouchMove={onTouchMove}
|
||||
onTouchEnd={onTouchEnd}
|
||||
onTouchCancel={onTouchEnd}
|
||||
>
|
||||
<span className="guest-banner-icon" aria-hidden="true">
|
||||
<span className="guest-banner-wave">👋</span>
|
||||
</span>
|
||||
<div className="guest-banner-body">
|
||||
<div className="guest-banner-title">{t("guide.bannerTitle")}</div>
|
||||
<div className="guest-banner-text">{t("guide.bannerText")}</div>
|
||||
<button type="button" className="guest-banner-btn" onClick={openGuide}>
|
||||
{t("guide.bannerButton")}
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" className="guest-banner-close" onClick={dismiss}
|
||||
aria-label={t("guide.bannerClose")} title={t("guide.bannerClose")}>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
<span className="guest-banner-handle" aria-hidden="true" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
86
src/components/GuideModal.jsx
Normal file
86
src/components/GuideModal.jsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
import "../styles/guide.css";
|
||||
|
||||
const STEPS = [
|
||||
{ key: "search", icon: "🔎" },
|
||||
{ key: "map", icon: "🗺️" },
|
||||
{ key: "create", icon: "📝" },
|
||||
{ key: "chat", icon: "💬" },
|
||||
{ key: "phone", icon: "📞" },
|
||||
{ key: "done", icon: "✅" },
|
||||
];
|
||||
|
||||
const SAFETY = ["safety1", "safety2", "safety3", "safety4"];
|
||||
|
||||
/**
|
||||
* Короткая инструкция для обычного пользователя: шесть шагов и правила
|
||||
* безопасности. Открывается из приветственной подсказки в ленте и из меню.
|
||||
* onLoginClick — для гостя: кнопка «Войти или зарегистрироваться».
|
||||
*
|
||||
* @param {{ onClose: () => void, onLoginClick?: () => void }} props
|
||||
*/
|
||||
export default function GuideModal({ onClose, onLoginClick }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
const prev = document.body.style.overflow;
|
||||
document.body.style.overflow = "hidden";
|
||||
const onKey = (e) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
document.body.style.overflow = prev;
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
return (
|
||||
<div className="f-modal-bg" onClick={(e) => e.target === e.currentTarget && onClose()}>
|
||||
<div className="f-modal guide-modal" role="dialog" aria-modal="true" aria-labelledby="guide-title">
|
||||
<div className="f-modal-head">
|
||||
<span className="f-modal-title" id="guide-title">{t("guide.title")}</span>
|
||||
<button type="button" className="f-close-btn" onClick={onClose} aria-label={t("common.close")}>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="guide-intro">{t("guide.intro")}</p>
|
||||
|
||||
<ol className="guide-steps">
|
||||
{STEPS.map(({ key, icon }, i) => (
|
||||
<li key={key} className="guide-step">
|
||||
<span className="guide-step-icon" aria-hidden="true">{icon}</span>
|
||||
<div className="guide-step-body">
|
||||
<div className="guide-step-title">
|
||||
<span className="guide-step-num">{i + 1}.</span> {t(`guide.${key}Title`)}
|
||||
</div>
|
||||
<div className="guide-step-text">{t(`guide.${key}Text`)}</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
<section className="guide-safety" aria-labelledby="guide-safety-title">
|
||||
<div className="guide-safety-title" id="guide-safety-title">⚠️ {t("guide.safetyTitle")}</div>
|
||||
<ul>
|
||||
{SAFETY.map((key) => <li key={key}>{t(`guide.${key}`)}</li>)}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<div className="guide-actions">
|
||||
{onLoginClick && (
|
||||
<button type="button" className="guide-btn guide-btn-primary" onClick={onLoginClick}>
|
||||
{t("guide.login")}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className={`guide-btn${onLoginClick ? "" : " guide-btn-primary"}`} onClick={onClose}>
|
||||
{t("guide.gotIt")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { useAuthContext } from "../context/AuthContext";
|
||||
import { useIsDesktop } from "../hooks/useIsDesktop";
|
||||
import SupportModal from "./SupportModal";
|
||||
import GuideModal from "./GuideModal";
|
||||
import UploadAdModal from "./UploadAdModal";
|
||||
import ProfileAvatar from "./profile/ProfileAvatar";
|
||||
import NahodkaLogo from "./MainNahodkaLogo";
|
||||
@@ -50,7 +51,9 @@ export default function Sidebar({
|
||||
const { language, toggleLanguage } = useLanguageToggle();
|
||||
const [supportOpen, setSupportOpen] = useState(false);
|
||||
const [uploadAdOpen, setUploadAdOpen] = useState(false);
|
||||
const [guideOpen, setGuideOpen] = useState(false);
|
||||
const HelpIcon = NavIcons.help;
|
||||
const BookIcon = NavIcons.book;
|
||||
|
||||
// Десктоп (>= 900px) — отдельная навигация с картой, CTA и свёрткой в рейку.
|
||||
// Мобильный drawer ниже остаётся без изменений.
|
||||
@@ -210,6 +213,16 @@ export default function Sidebar({
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
type="button"
|
||||
className="f-sb-item"
|
||||
onClick={() => {
|
||||
setGuideOpen(true);
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
<BookIcon /> {t('nav.guide')}
|
||||
</button>
|
||||
<button type="button" className="f-sb-item" onClick={() => setSupportOpen(true)}>
|
||||
<HelpIcon /> {t('nav.support')} </button>
|
||||
<div className="f-sb-divider" />
|
||||
@@ -246,6 +259,15 @@ export default function Sidebar({
|
||||
</div>
|
||||
{supportOpen && <SupportModal onClose={() => setSupportOpen(false)} />}
|
||||
{uploadAdOpen && <UploadAdModal onClose={() => setUploadAdOpen(false)} />}
|
||||
{guideOpen && (
|
||||
<GuideModal
|
||||
onClose={() => setGuideOpen(false)}
|
||||
onLoginClick={isAuthenticated ? undefined : () => {
|
||||
setGuideOpen(false);
|
||||
onLoginClick();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import GlobeIcon from "../icons/GlobeIcon";
|
||||
import NahodkaLogo from "../MainNahodkaLogo";
|
||||
import ProfileAvatar from "../profile/ProfileAvatar";
|
||||
import SupportModal from "../SupportModal";
|
||||
import GuideModal from "../GuideModal";
|
||||
import UploadAdModal from "../UploadAdModal";
|
||||
import { useTheme } from "../../context/ThemeContext";
|
||||
import { useUnread } from "../../context/UnreadContext";
|
||||
@@ -59,6 +60,7 @@ export default function DesktopSidebar({
|
||||
const { language, toggleLanguage } = useLanguageToggle();
|
||||
const [supportOpen, setSupportOpen] = useState(false);
|
||||
const [uploadAdOpen, setUploadAdOpen] = useState(false);
|
||||
const [guideOpen, setGuideOpen] = useState(false);
|
||||
|
||||
const profileName = `${profileData?.firstName || ""} ${profileData?.lastName || ""}`.trim();
|
||||
|
||||
@@ -180,6 +182,15 @@ export default function DesktopSidebar({
|
||||
<span className="fd-sb-icon">{NavIcons.star()}</span>
|
||||
<span className="fd-sb-label">{t("nav.reviews")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-item fd-sb-item-sm"
|
||||
onClick={() => setGuideOpen(true)}
|
||||
title={t("nav.guide")}
|
||||
>
|
||||
<span className="fd-sb-icon">{NavIcons.book()}</span>
|
||||
<span className="fd-sb-label">{t("nav.guide")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="fd-sb-item fd-sb-item-sm"
|
||||
@@ -245,6 +256,15 @@ export default function DesktopSidebar({
|
||||
</aside>
|
||||
{supportOpen && <SupportModal onClose={() => setSupportOpen(false)} />}
|
||||
{uploadAdOpen && <UploadAdModal onClose={() => setUploadAdOpen(false)} />}
|
||||
{guideOpen && (
|
||||
<GuideModal
|
||||
onClose={() => setGuideOpen(false)}
|
||||
onLoginClick={isAuthenticated ? undefined : () => {
|
||||
setGuideOpen(false);
|
||||
onLoginClick();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -56,6 +56,13 @@ export const NavIcons = {
|
||||
<line x1="12" y1="17" x2="12.01" y2="17" />
|
||||
</svg>
|
||||
),
|
||||
// Открытая книга — «Инструкция»
|
||||
book: () => (
|
||||
<svg width={20} height={20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M2 4h6a4 4 0 0 1 4 4v13a3 3 0 0 0-3-3H2z" />
|
||||
<path d="M22 4h-6a4 4 0 0 0-4 4v13a3 3 0 0 1 3-3h7z" />
|
||||
</svg>
|
||||
),
|
||||
megaphone: () => (
|
||||
<svg width={20} height={20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="m3 11 18-5v12L3 14v-3z" />
|
||||
|
||||
Reference in New Issue
Block a user