-
Notifications
You must be signed in to change notification settings - Fork 12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Модуль 5 «React и паттерны» #5
Commits on Dec 1, 2023
-
5.1. Добавит новый компонент AudioPlayer.
Для воспроизведения мелодий создадим новый компонент «AudioPlayer». Оба игровых экрана (`ArtistQuestionScreen`, `GenreQuestionScreen`) умеют воспроизводить мелодии. Поэтому функциональность для воспроизведения разумно вынести в отдельный компонент и переиспользовать многократно. Проигрывать мелодии будем с помощью тега `<audio>` и хука `useRef`. Чтобы связать `ref` с компонентом `audio`, передадим ему в пропе `ref`, созданную после вызова `useRef` ссылку. Поскольку в игре предусмотрена возможность приостанавливать и возобновлять воспроизведение мелодий, компоненту `AudioPlayer` потребуется состояние. В стейте сохраним информацию о готовности воспроизводить мелодию (`isLoaded`), и статусу воспроизведения (`isPlaying`): проигрывается или приостановлено.
Configuration menu - View commit details
-
Copy full SHA for e916782 - Browse repository at this point
Copy the full SHA e916782View commit details -
Воспользуемся пакетом `classnames`, чтобы изменять классы элемента в зависимости от состояния.
Configuration menu - View commit details
-
Copy full SHA for 3f0f45c - Browse repository at this point
Copy the full SHA 3f0f45cView commit details -
5.3. Подключит компонент AudioPlayer в ArtistQuestionScreen.
Воспользуемся компонентом `AudioPlayer` в `ArtistQuestionScreen`. Плееру требуется передать путь к мелодии, которую следует воспроизводить (`src`) и необходимость воспроизведения сразу как только мелодия будет готова для воспроизведения.
Configuration menu - View commit details
-
Copy full SHA for 8b33803 - Browse repository at this point
Copy the full SHA 8b33803View commit details -
5.4. Подключит компонент AudioPlayer в GenreQuestionScreen.
Аналогичную процедуру проделаем в компоненте `GenreQuestionScreen`.
Configuration menu - View commit details
-
Copy full SHA for 41711ab - Browse repository at this point
Copy the full SHA 41711abView commit details -
5.5. Перенесёт контроль за состоянием плеера в родительский компонент.
Мелодии проигрываются, но есть сложности с управлением воспроизведением. Например, в игре «Угадай жанр» можно одновременно запустить несколько мелодий. Перенос контроля за состоянием плеера в родительские компоненты поможет решить эту проблему. Проведём небольшой рефакторинг `ArtistQuestionScreen` и `GenreQuestionScreen`. В первом компоненте определим стейт с одним полем: `isPlaying`. А для `GenreQuestionScreen` добавим в стейт поле `activePlayer`. В нём будем фиксировать плеер, который воспроизводит мелодию в данный момент. В компоненте `AudioPlayer` удалим из стейта поле `isPlaying`. Больше оно нам не потребуется.
Configuration menu - View commit details
-
Copy full SHA for 77d9ca5 - Browse repository at this point
Copy the full SHA 77d9ca5View commit details -
5.6. Добавит HOC withAudioPlayer.
Создадим директорию hocs, а в ней новый модуль `with-audio-player.jsx`. В нём опишем одноимённый HOC. В этом HOC реализуем стейт для хранения информации о плеере, который воспроизводит мелодию в настоящий момент времени. HOC вернёт новый компонент и через render-prop прокинет `AudioPlayer`.
Configuration menu - View commit details
-
Copy full SHA for 84fbe57 - Browse repository at this point
Copy the full SHA 84fbe57View commit details -
5.7. Уберёт подключение AudioPlayer из ArtistQuestionScreen. WIP
Стейт в компоненте `ArtistQuestionScreen` больше не нужен. Ровным счётом как и подключение `AudioPlayer`. Выполним небольшой рефакторинг и для отрисовки плеера воспользуемся рендер-пропом `renderPlayer`.
Configuration menu - View commit details
-
Copy full SHA for 8660266 - Browse repository at this point
Copy the full SHA 8660266View commit details -
5.8. Уберёт подключение AudioPlayer из GenreQuestionScreen. WIP
Компонент `AudioPlayer` больше не нужен в `GenreQuestionScreen`. Для этого мы создали HOC. Следовательно, подключение компонента необходимо удалить, а заодно убрать из стейта `activePlayer`.
Configuration menu - View commit details
-
Copy full SHA for 421a8b4 - Browse repository at this point
Copy the full SHA 421a8b4View commit details -
5.9. Подключит HOC в GameScreen.
Воспользуемся HOC `withActivePlayer` в компоненте `GameScreen`. Подключим HOC, создадим обёртки (`GenreQuestionScreenWrapped`, `ArtistQuestionScreenWrapped`) и воспользуемся ими.
Configuration menu - View commit details
-
Copy full SHA for 38503a5 - Browse repository at this point
Copy the full SHA 38503a5View commit details -
5.10. Добавит новый хук useElementListener
Компонент `AudioPlayer` можно оптимизировать. Для этого вынесем логику добавления и удаления событий на элемент `<audio>` в новый хук useElementListener.
Configuration menu - View commit details
-
Copy full SHA for f64158c - Browse repository at this point
Copy the full SHA f64158cView commit details -
5.11. Добавит типизацию хука useElementListener
Отдельно добавим типизацию хука useElementListener.
Configuration menu - View commit details
-
Copy full SHA for 7c46a9b - Browse repository at this point
Copy the full SHA 7c46a9bView commit details