From 5e1c6a8ca75ec3ae6800a10f0ca24f4fa946f840 Mon Sep 17 00:00:00 2001 From: Grisha Lavrov Date: Fri, 4 Dec 2026 17:02:05 +0100 Subject: [PATCH] Bit: sound, clearer dialog, live Bit on the home CTA MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Sound: short 8-bit beeps synthesized with Web Audio, melody by tone (cheer up, calm down, fire alarm-ish), an arpeggio when the dialog opens. Silent until the first user gesture, throttled to one beep per 300 ms, toggle in the dialog remembered in localStorage. - Dialog (BitDialog): status line ("Помощник · слушает/думает/дремлет") instead of a random joke, "Ещё совет" with an "N из M" counter, the last 4 lines Bit said, "Понятно" plus one page-specific action (or none). - Home CTA: the static picture is now BitAvatar; Bit greets when the block scrolls into view, cheers on hovering the button and answers a poke, with its own speech bubble. - Fix: the visually hidden status used width: 1, which MUI reads as 100%, so every page scrolled horizontally. Same fix in TopicNav. - Fix: clicks on Bit could be lost because the move layer remounts on every move; the avatar now ignores pointer events and the wrapper gets the click. --- frontend/src/components/ui/BitAvatar.tsx | 3 + frontend/src/components/ui/BitDialog.test.tsx | 62 +++++ frontend/src/components/ui/BitDialog.tsx | 216 ++++++++++++++++++ frontend/src/components/ui/PracticeMascot.tsx | 107 +-------- frontend/src/components/ui/bitSound.ts | 87 +++++++ frontend/src/components/ui/bitVoice.ts | 9 + frontend/src/pages/HomePage/CtaSection.tsx | 174 +++++++++----- .../src/pages/QuestionDetailPage/TopicNav.tsx | 2 +- 8 files changed, 508 insertions(+), 152 deletions(-) create mode 100644 frontend/src/components/ui/BitDialog.test.tsx create mode 100644 frontend/src/components/ui/BitDialog.tsx create mode 100644 frontend/src/components/ui/bitSound.ts diff --git a/frontend/src/components/ui/BitAvatar.tsx b/frontend/src/components/ui/BitAvatar.tsx index 071d4ca..09174bd 100644 --- a/frontend/src/components/ui/BitAvatar.tsx +++ b/frontend/src/components/ui/BitAvatar.tsx @@ -143,6 +143,9 @@ export const BitAvatar = ({ height = { xs: 37, md: 42 } }: BitAvatarProps) => { data-bit-mood={mood} sx={{ position: 'relative', height, aspectRatio: '197 / 250', flexShrink: 0, display: 'inline-block', + // слой движения пересоздаётся на каждое движение: без этого клик, попавший между + // нажатием и отпусканием на старый слой, терялся бы. Кликабельна обёртка, а не картинка. + pointerEvents: 'none', transformOrigin: '50% 82%', transition: 'opacity .6s, filter .6s', opacity: asleep ? 0.7 : 1, diff --git a/frontend/src/components/ui/BitDialog.test.tsx b/frontend/src/components/ui/BitDialog.test.tsx new file mode 100644 index 0000000..e53e35e --- /dev/null +++ b/frontend/src/components/ui/BitDialog.test.tsx @@ -0,0 +1,62 @@ +import { MemoryRouter } from 'react-router-dom'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { ThemeProvider as MuiThemeProvider } from '@mui/material'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { ThemeProvider } from '../../context/ThemeContext'; +import { darkTheme } from '../../theme/muiTheme'; +import { BitDialog } from './BitDialog'; +import type { BitSection } from './BitDialog'; +import { bitSay, resetBitForTests } from './bitVoice'; + +const renderDialog = (section: BitSection, isAuthenticated = true) => + render( + + + + {}} section={section} isAuthenticated={isAuthenticated} /> + + + , + ); + +beforeEach(() => { + resetBitForTests(); + window.localStorage.removeItem('bit:sound'); +}); + +describe('BitDialog', () => { + it('cycles page tips with a visible counter', () => { + renderDialog('roadmap'); + expect(screen.getByText(/Совет · 1 из 2/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Ещё совет' })); + expect(screen.getByText(/Совет · 2 из 2/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Ещё совет' })); + expect(screen.getByText(/1 из 2/)).toBeInTheDocument(); + }); + + it('offers a page action when there is one, otherwise only «Понятно»', () => { + const { unmount } = renderDialog('questions'); + expect(screen.getByRole('link', { name: 'Собеседование по компании' })).toHaveAttribute('href', '/companies'); + unmount(); + renderDialog('roadmap'); + expect(screen.queryByRole('link')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Понятно' })).toBeInTheDocument(); + }); + + it('shows what Bit said recently', () => { + act(() => bitSay('Шаг «Основы» закрыт!', 'cheer')); + renderDialog('roadmap'); + expect(screen.getByText('Недавно говорил')).toBeInTheDocument(); + expect(screen.getByText('Шаг «Основы» закрыт!')).toBeInTheDocument(); + }); + + it('toggles sound and remembers the choice', () => { + renderDialog('home'); + const toggle = screen.getByRole('button', { name: 'Выключить звук Бита' }); + expect(toggle).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(toggle); + expect(screen.getByRole('button', { name: 'Включить звук Бита' })).toHaveAttribute('aria-pressed', 'false'); + expect(window.localStorage.getItem('bit:sound')).toBe('0'); + fireEvent.click(screen.getByRole('button', { name: 'Включить звук Бита' })); + }); +}); diff --git a/frontend/src/components/ui/BitDialog.tsx b/frontend/src/components/ui/BitDialog.tsx new file mode 100644 index 0000000..9a0a521 --- /dev/null +++ b/frontend/src/components/ui/BitDialog.tsx @@ -0,0 +1,216 @@ +import { useEffect, useId, useState } from 'react'; +import { Box, Button, Dialog, IconButton, Stack, Tooltip, Typography } from '@mui/material'; +import { ArrowForward, Close, VolumeOff, VolumeUp } from '@mui/icons-material'; +import { Link as RouterLink } from 'react-router-dom'; +import { useTokens } from '../../theme/tokens'; +import { BitAvatar } from './BitAvatar'; +import { playBitSound, setBitSoundEnabled, useBitSoundEnabled } from './bitSound'; +import { bitMove, useBitHistory, useBitPose } from './bitVoice'; +import type { BitMood, BitTone } from './bitVoice'; + +export type BitSection = 'home' | 'questions' | 'question' | 'companies' | 'interview' | 'roadmap' | 'favorites' | 'account'; + +/** Советы для страницы: листаются по кругу кнопкой «Ещё совет». */ +const TIPS: Record = { + home: [ + 'Начните с одного вопроса. Сформулируйте ответ своими словами и только потом откройте разбор.', + 'Не знаете, с чего начать? Возьмите тему, которую давно не повторяли. Одного вопроса достаточно.', + 'Пять минут каждый день полезнее, чем три часа накануне собеседования.', + ], + questions: [ + 'Выберите одну тему и ответьте на вопрос вслух. Так легче заметить, где в объяснении не хватает связки.', + 'Застряли? Придумайте самый маленький пример и разберите его вручную.', + 'Отмечайте честно: «Частично» вернёт вопрос в фильтр «На повтор», и вы к нему вернётесь.', + ], + question: [ + 'Перед разбором попробуйте дать короткий ответ: что происходит, почему и на каком примере это видно.', + 'После разбора закройте ответ и перескажите суть. Один честный повтор полезнее нескольких быстрых просмотров.', + 'Включите «Тренировку» — ответ спрячется, пока вы не сформулируете свой.', + ], + companies: [ + 'Откройте компанию, которая вам интересна. Сначала попробуйте ответить на один вопрос без подсказок.', + 'В компании есть пробное собеседование: я задам вопросы по очереди и подведу итоги.', + ], + interview: [ + 'Объясняйте ход мысли вслух. Если не знаете ответ сразу, начните с того, что уже понятно.', + 'Назовите одно допущение и проверьте его на примере. Это даст вам следующую точку опоры.', + 'Можно надиктовать ответ голосом — так ближе к настоящему собеседованию.', + ], + roadmap: [ + 'Откройте текущий шаг и возьмите первый неотмеченный вопрос. Остальные подождут.', + 'Если тема уже знакома, проверьте её одним вопросом. Если вспоминается тяжело, останьтесь на этом шаге.', + ], + favorites: [ + 'Возьмите один вопрос из избранного и ответьте на него без подсказки.', + 'Начните с того, что добавили раньше всех: его вы помните хуже всего.', + ], + account: [ + 'Войдите в аккаунт, чтобы сохранять прогресс. На главной можно попробовать демовопрос без входа.', + 'После входа начните с одной темы и одного вопроса. Маленький шаг тоже считается.', + ], +}; + +/** Главное действие для страницы: куда Бит предлагает пойти. null — только «Понятно». */ +const actionFor = (section: BitSection, auth: boolean): { label: string; to: string } | null => { + if (section === 'account') return { label: 'К демовопросу', to: '/' }; + if (!auth) return section === 'home' ? { label: 'Начать подготовку', to: '/register' } : null; + if (section === 'home' || section === 'favorites') return { label: 'К вопросам', to: '/questions' }; + if (section === 'questions') return { label: 'Собеседование по компании', to: '/companies' }; + if (section === 'question') return { label: 'Все вопросы', to: '/questions' }; + return null; +}; + +const STATUS: Record = { + idle: 'на связи', + listening: 'слушает', + thinking: 'думает', + sleeping: 'дремлет', +}; + +const ago = (at: number) => { + const s = Math.round((Date.now() - at) / 1000); + if (s < 60) return 'только что'; + const m = Math.round(s / 60); + return m < 60 ? `${m} мин назад` : 'давно'; +}; + +const SectionLabel = ({ children }: { children: string }) => { + const { c } = useTokens(); + return ( + + {children} + + ); +}; + +interface BitDialogProps { + open: boolean; + onClose: () => void; + section: BitSection; + isAuthenticated: boolean; +} + +/** Окно Бита: статус, совет для текущей страницы, недавние реплики, звук и одно понятное действие. */ +export const BitDialog = ({ open, onClose, section, isAuthenticated }: BitDialogProps) => { + const titleId = useId(); + const { c, shadow } = useTokens(); + const { mood } = useBitPose(); + const history = useBitHistory(); + const sound = useBitSoundEnabled(); + const [tip, setTip] = useState(0); + const tips = TIPS[section]; + const action = actionFor(section, isAuthenticated); + const toneColor: Record = { calm: c.accent, cheer: c.success, fire: c.danger, focus: c.warning }; + + useEffect(() => { + if (!open) return; + playBitSound('open'); + bitMove('hop'); + }, [open]); + + const nextTip = () => { + setTip((i) => (i + 1) % tips.length); + playBitSound('focus'); + bitMove('nod'); + }; + + const toggleSound = () => { + setBitSoundEnabled(!sound); + // включили — сразу слышно, как звучит + if (!sound) window.setTimeout(() => playBitSound('cheer'), 0); + }; + + return ( + + {/* шапка: кто это и что он сейчас делает */} + + + + + Бит + + + + Помощник · {STATUS[mood]} + + + + + {sound ? : } + + + + + + + + {/* совет для этой страницы */} + + + {tips.length > 1 ? `Совет · ${tip + 1} из ${tips.length}` : 'Совет'} + {tips.length > 1 && ( + + )} + + + {tips[tip]} + + + + {/* что Бит недавно говорил: реплики в облачке исчезают, здесь их можно перечитать */} + {history.length > 0 && ( + + Недавно говорил + + {history.map((line) => ( + + + {line.text} + {ago(line.at)} + + ))} + + + )} + + + + {action && ( + + )} + + + ); +}; diff --git a/frontend/src/components/ui/PracticeMascot.tsx b/frontend/src/components/ui/PracticeMascot.tsx index 474d768..cff22d9 100644 --- a/frontend/src/components/ui/PracticeMascot.tsx +++ b/frontend/src/components/ui/PracticeMascot.tsx @@ -1,58 +1,22 @@ -import { type MutableRefObject, useEffect, useId, useRef, useState } from 'react'; -import { Box, Button, ClickAwayListener, Dialog, DialogContent, DialogTitle, Grow, IconButton, Popper, Stack, Typography } from '@mui/material'; -import { ArrowForward, Close, Loop } from '@mui/icons-material'; -import { Link as RouterLink, useLocation } from 'react-router-dom'; +import { type MutableRefObject, useEffect, useRef, useState } from 'react'; +import { Box, Button, ClickAwayListener, Grow, Popper, Typography } from '@mui/material'; +import { useLocation } from 'react-router-dom'; import { useAuth } from '../../context/auth-context'; import { useTokens } from '../../theme/tokens'; import { bitMove, useBitHosted, useBitPose, useBitVoice } from './bitVoice'; import type { BitTone } from './bitVoice'; import { BitAvatar } from './BitAvatar'; import { useBitSenses } from './bitSenses'; +import { BitDialog } from './BitDialog'; +import type { BitSection } from './BitDialog'; -type TipSet = [string, string]; - -const tips = { - home: [ - 'Начните с одного вопроса. Сформулируйте ответ своими словами и только потом откройте разбор.', - 'Если сложно выбрать тему, возьмите ту, которую давно не повторяли. Одного вопроса достаточно, чтобы начать.', - ], - questions: [ - 'Выберите одну тему и ответьте на вопрос вслух. Так легче заметить, где в объяснении не хватает связки.', - 'Застряли? Придумайте самый маленький пример и разберите его вручную.', - ], - question: [ - 'Перед разбором попробуйте дать короткий ответ: что происходит, почему и на каком примере это видно.', - 'После разбора закройте ответ и перескажите суть. Один честный повтор полезнее нескольких быстрых просмотров.', - ], - companies: [ - 'Откройте компанию, которая вам интересна. Сначала попробуйте ответить на один вопрос без подсказок.', - 'Вопросы компаний помогают познакомиться с форматом. Отмечайте темы, которые хочется повторить отдельно.', - ], - interview: [ - 'Объясняйте ход мысли вслух. Если не знаете ответ сразу, начните с того, что уже понятно.', - 'Назовите одно допущение и проверьте его на примере. Это даст вам следующую точку опоры.', - ], - roadmap: [ - 'Откройте текущий шаг и возьмите первый незавершённый вопрос. Остальные подождут.', - 'Если тема уже знакома, проверьте её одним вопросом. Если вспоминается тяжело, останьтесь на этом шаге.', - ], - favorites: [ - 'Сохранил вопрос «Что такое кэш?». Если забуду, знаю, где искать.', - 'Вернитесь к сохранённому вопросу и попробуйте ответить без подсказки.', - ], - account: [ - 'Войдите в аккаунт, чтобы сохранять прогресс. На главной можно попробовать демовопрос без входа.', - 'После входа начните с одной темы и одного вопроса. Маленький шаг тоже считается.', - ], -} satisfies Record; - -function getSection(pathname: string) { +function getSection(pathname: string): BitSection { if (pathname.startsWith('/questions/')) return 'question'; if (pathname === '/questions') return 'questions'; if (pathname === '/favorites') return 'favorites'; if (pathname.includes('/interview/')) return 'interview'; if (pathname.startsWith('/companies')) return 'companies'; - if (pathname === '/roadmap') return 'roadmap'; + if (pathname.startsWith('/roadmap')) return 'roadmap'; if (['/login', '/register', '/forgot-password'].includes(pathname)) return 'account'; return 'home'; } @@ -68,11 +32,9 @@ const comments = [ ]; const MascotPanel = ({ pathname, selfRef }: { pathname: string; selfRef: MutableRefObject }) => { - const titleId = useId(); const { isAuthenticated } = useAuth(); const { c, shadow } = useTokens(); const [open, setOpen] = useState(false); - const [alternate, setAlternate] = useState(false); const [commentIndex, setCommentIndex] = useState(0); const section = getSection(pathname); // Реплики (bitSay) показываются облачком под Битом; сказанное до перехода на страницу не повторяем. @@ -101,9 +63,6 @@ const MascotPanel = ({ pathname, selfRef }: { pathname: string; selfRef: Mutable }, []); const comment = mood === 'sleeping' ? 'Сплю… тапни, если что' : mood === 'thinking' ? 'Думаю…' : mood === 'listening' ? 'Слушаю…' : comments[commentIndex]; - const keepPracticing = section === 'questions' || section === 'roadmap' || section === 'interview'; - const to = section === 'account' ? '/' : isAuthenticated ? '/questions' : '/register'; - const action = section === 'account' ? 'К демовопросу' : isAuthenticated ? 'К вопросам' : 'Начать подготовку'; return ( <> @@ -138,7 +97,7 @@ const MascotPanel = ({ pathname, selfRef }: { pathname: string; selfRef: Mutable - + {said ? `Бит: ${said.text}` : ''} t.zIndex.appBar + 1 }} @@ -185,55 +144,7 @@ const MascotPanel = ({ pathname, selfRef }: { pathname: string; selfRef: Mutable )} - setOpen(false)} - aria-labelledby={titleId} - fullWidth - maxWidth="xs" - sx={{ '& .MuiDialog-container': { alignItems: { xs: 'flex-end', sm: 'flex-start' }, justifyContent: { xs: 'center', sm: 'flex-end' } } }} - slotProps={{ - paper: { - sx: { - m: { xs: 1.5, md: 3 }, mt: { sm: 9 }, width: { xs: 'calc(100% - 24px)', md: 390 }, - border: `1px solid ${c.borderStrong}`, borderRadius: '20px', - background: c.surface, boxShadow: shadow.lg, - }, - }, - }} - > - - - Бит - setOpen(false)} sx={{ ml: 'auto' }}> - - - - - {comment} - - {tips[section][alternate ? 1 : 0]} - - - {keepPracticing ? ( - - ) : ( - - )} - - - - + setOpen(false)} section={section} isAuthenticated={isAuthenticated} /> ); }; diff --git a/frontend/src/components/ui/bitSound.ts b/frontend/src/components/ui/bitSound.ts new file mode 100644 index 0000000..ec16c6d --- /dev/null +++ b/frontend/src/components/ui/bitSound.ts @@ -0,0 +1,87 @@ +import { useSyncExternalStore } from 'react'; +import { storage } from '../../lib/storage'; + +/** + * Голос Бита: короткие 8-битные «бипы», синтезируются Web Audio, без файлов. + * Включается переключателем в диалоге Бита, выбор хранится в браузере. + */ + +export type BitSound = 'calm' | 'cheer' | 'fire' | 'focus' | 'open' | 'poke'; + +const KEY = 'bit:sound'; +/** Ноты (Гц): у каждого настроения своя интонация. */ +const MELODIES: Record = { + cheer: [660, 880], + focus: [587, 698], + calm: [523, 392], + fire: [440, 330, 494], + open: [392, 523, 659], + poke: [988], +}; +const NOTE_S = 0.075; +const GAP_S = 0.025; +const VOLUME = 0.035; +/** Чаще не пищим: серия реплик подряд звучит одним бипом. */ +const MIN_INTERVAL_MS = 300; + +let enabled = storage.get(KEY) !== '0'; +const listeners = new Set<() => void>(); +let ctx: AudioContext | null = null; +let lastPlayed = 0; +// Браузер разрешает звук только после жеста пользователя: до него молчим, а не сыплем предупреждениями +let unlocked = false; +if (typeof window !== 'undefined') { + const unlock = () => { + unlocked = true; + }; + window.addEventListener('pointerdown', unlock, { once: true, capture: true }); + window.addEventListener('keydown', unlock, { once: true, capture: true }); +} + +export const setBitSoundEnabled = (value: boolean) => { + enabled = value; + storage.set(KEY, value ? '1' : '0'); + listeners.forEach((l) => l()); +}; + +export const useBitSoundEnabled = () => + useSyncExternalStore( + (l) => { + listeners.add(l); + return () => { + listeners.delete(l); + }; + }, + () => enabled, + () => enabled, + ); + +export const playBitSound = (kind: BitSound) => { + if (!enabled || !unlocked || typeof window === 'undefined' || document.visibilityState !== 'visible') return; + const now = Date.now(); + if (now - lastPlayed < MIN_INTERVAL_MS) return; + lastPlayed = now; + try { + const Ctor = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext; + if (!Ctor) return; + ctx ??= new Ctor(); + if (ctx.state === 'suspended') void ctx.resume(); + const start = ctx.currentTime + 0.01; + MELODIES[kind].forEach((freq, i) => { + const at = start + i * (NOTE_S + GAP_S); + const osc = ctx!.createOscillator(); + const gain = ctx!.createGain(); + osc.type = 'square'; + osc.frequency.setValueAtTime(freq, at); + // мягкая атака и затухание: без щелчков + gain.gain.setValueAtTime(0, at); + gain.gain.linearRampToValueAtTime(VOLUME, at + 0.008); + gain.gain.exponentialRampToValueAtTime(0.0001, at + NOTE_S); + osc.connect(gain).connect(ctx!.destination); + osc.start(at); + osc.stop(at + NOTE_S + 0.02); + }); + } catch { + /* звук — украшение: если Web Audio недоступен, Бит просто молчит */ + } +}; diff --git a/frontend/src/components/ui/bitVoice.ts b/frontend/src/components/ui/bitVoice.ts index c8254f9..ce35a58 100644 --- a/frontend/src/components/ui/bitVoice.ts +++ b/frontend/src/components/ui/bitVoice.ts @@ -1,4 +1,5 @@ import { useSyncExternalStore } from 'react'; +import { playBitSound } from './bitSound'; /** * «Нервная система» Бита: реплики, движения и настроение. Модуль без React-состояния, поэтому @@ -51,6 +52,9 @@ const createSignal = () => { // ---- голос ---- let current: BitLine | null = null; +/** Последние реплики (новые сверху): диалог Бита показывает, что он недавно говорил. */ +let history: BitLine[] = []; +const HISTORY_SIZE = 4; let seq = 0; const voice = createSignal(); @@ -91,11 +95,15 @@ export const bitSay = (text: string, tone: BitTone = 'calm', { move, priority = const now = Date.now(); if (current && priority < current.priority && now - current.at < YIELD_MS) return; current = { id: ++seq, text, tone, priority, at: now }; + history = [current, ...history.filter((l) => l.text !== text)].slice(0, HISTORY_SIZE); voice.emit(); + playBitSound(tone); bitMove(move ?? TONE_MOVE[tone]); }; export const useBitVoice = () => useSyncExternalStore(voice.subscribe, () => current, () => null); +const NO_HISTORY: BitLine[] = []; +export const useBitHistory = () => useSyncExternalStore(voice.subscribe, () => history, () => NO_HISTORY); export const useBitPose = () => useSyncExternalStore(body.subscribe, () => pose, () => pose); /** Пока держится — Бит слушает или думает (диктовка, проверка ИИ). Возвращает отпускание. */ @@ -150,6 +158,7 @@ export const pickLine = (key: string, lines: string[]) => { /** Только для тестов: сбросить состояние между кейсами. */ export const resetBitForTests = () => { current = null; + history = []; pose = { move: null, moveId: 0, mood: 'idle' }; lastBigMoveAt = 0; typing = false; diff --git a/frontend/src/pages/HomePage/CtaSection.tsx b/frontend/src/pages/HomePage/CtaSection.tsx index 76840d2..dc83192 100644 --- a/frontend/src/pages/HomePage/CtaSection.tsx +++ b/frontend/src/pages/HomePage/CtaSection.tsx @@ -1,66 +1,134 @@ +import { useEffect, useRef, useState } from 'react'; import { Box, Button, Typography } from '@mui/material'; import { Link as RouterLink } from 'react-router-dom'; import { ArrowForward as ArrowForwardIcon } from '@mui/icons-material'; -import bit from '../../assets/mascot/bit.webp'; +import { BitAvatar } from '../../components/ui/BitAvatar'; +import { playBitSound } from '../../components/ui/bitSound'; +import type { BitSound } from '../../components/ui/bitSound'; +import { bitMove, pickLine } from '../../components/ui/bitVoice'; +import type { BitMove } from '../../components/ui/bitVoice'; + +const POKE_LINES = [ + 'Эй, щекотно! Лучше ткни в «К вопросам».', + 'Бип! Я тут, если что.', + 'Ещё раз — и я начну задавать вопросы.', + 'Тыкать в Бита не засчитывается как подготовка.', +]; +const HOVER_LINES = ['Жми, я подержу кулачки!', 'Один вопрос — пять минут. Погнали?', 'Вот это настрой!']; interface CtaSectionProps { isAuthenticated: boolean; } -export const CtaSection = ({ isAuthenticated }: CtaSectionProps) => ( - { + const ref = useRef(null); + const [line, setLine] = useState(null); + + const react = (text: string, sound: BitSound, move: BitMove) => { + setLine(text); + playBitSound(sound); + bitMove(move); + }; + + // долистали до конца главной — Бит здоровается (один раз) + useEffect(() => { + const el = ref.current; + if (!el || typeof IntersectionObserver === 'undefined') return; + const observer = new IntersectionObserver( + ([entry]) => { + if (!entry.isIntersecting) return; + observer.disconnect(); + react(isAuthenticated ? 'Дочитал до конца? Значит, готов к первому вопросу!' : 'Дочитал до конца? Регистрируйся — и начнём с одного вопроса.', 'cheer', 'hop'); }, - }} - > + { threshold: 0.6 }, + ); + observer.observe(el); + return () => observer.disconnect(); + }, [isAuthenticated]); + + const cheer = () => react(pickLine('cta:hover', HOVER_LINES), 'focus', 'glanceR'); + + return ( - - - Начните с одного вопроса - - - {isAuthenticated - ? 'Выберите тему, дайте короткий ответ и сверьтесь с разбором.' - : 'Создайте аккаунт, чтобы открыть каталог и сохранять прогресс.'} - - - - -); + + {/* облачко с репликой Бита */} + + {line} + + react(pickLine('cta:poke', POKE_LINES), 'poke', 'hop')} + sx={{ + all: 'unset', cursor: 'pointer', borderRadius: '16px', display: 'grid', placeItems: 'center', + filter: 'drop-shadow(0 8px 10px #1a100abb)', + '&:focus-visible': { outline: '2px solid #fde2c7', outlineOffset: 4 }, + }} + > + + + + + + Начните с одного вопроса + + + {isAuthenticated + ? 'Выберите тему, дайте короткий ответ и сверьтесь с разбором.' + : 'Создайте аккаунт, чтобы открыть каталог и сохранять прогресс.'} + + + + + ); +}; diff --git a/frontend/src/pages/QuestionDetailPage/TopicNav.tsx b/frontend/src/pages/QuestionDetailPage/TopicNav.tsx index 878715c..af3c149 100644 --- a/frontend/src/pages/QuestionDetailPage/TopicNav.tsx +++ b/frontend/src/pages/QuestionDetailPage/TopicNav.tsx @@ -9,7 +9,7 @@ import type { Category, Question } from '../../types'; /** Сколько вопросов темы показываем в навигаторе: с запасом больше самой крупной темы. */ const TOPIC_LIMIT = 500; -const visuallyHidden = { position: 'absolute', width: 1, height: 1, overflow: 'hidden', clip: 'rect(0 0 0 0)', whiteSpace: 'nowrap' } as const; +const visuallyHidden = { position: 'absolute', width: '1px', height: '1px', overflow: 'hidden', clip: 'rect(0 0 0 0)', whiteSpace: 'nowrap' } as const; const DIFFICULTY_LABEL: Record = { easy: 'Лёгкий', medium: 'Средний', hard: 'Сложный' };