-
Notifications
You must be signed in to change notification settings - Fork 1
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
feat(23UG-74): добавляет Player (ипользовано Page Visibility API) #44
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
isPlaying.current = !isPlaying.current; | ||
setNewRender(!newRender); | ||
refIsAudioPlay.current = !refIsAudioPlay.current; | ||
setFoo(!foo); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А это для чего? Не нашел, где foo
используется.
Ну и название переменной, конечно, огонь ))
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Нигде больше не используется)) Нужно как-то отображение кнопки Музыка поменять при её нажатии, делаю это через useState. А название переменной показывает, что оно не имеет значение (foo, bar - общепринятые). Думаешь лучше переименовать? Или комментарий оставить?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Честно говоря, мне в целом не нравится, как компонент написан. Как будто ненужные флаги, шаманское foo
, ну и опять же, смешались вместе кони, люди,...
Я бы вынес проверку видимости в отдельный хук, т.к. это может понадобиться и в других местах. Пускай не в нашем проекте, но надо же в общем думать и делать удобно для людей. Сейчас это не переиспользуемый сложночитаемый монолит. Я так считаю ))
В общем, я бы написал как-то так:
const usePageVisibility = (initialState = true) => {
const [pageIsVisible, setPageIsVisible] = useState(initialState);
useEffect(() => {
const handleVisibilitychange = () => {
if (document.hidden) {
setPageIsVisible(false);
} else {
setPageIsVisible(true);
}
};
document.addEventListener("visibilitychange", handleVisibilitychange);
return () => {
document.removeEventListener("visibilitychange", handleVisibilitychange);
};
}, []);
return pageIsVisible;
};
const Player: React.FC<PlayerType> = ({ url }) => {
const pageIsVisible = usePageVisibility();
const refAudio = useRef<HTMLAudioElement | null>(null);
const [isAudioOn, setIsAudioOn] = useState(false);
const toggle = () => {
setIsAudioOn(!isAudioOn);
};
useLayoutEffect(() => {
refAudio.current = new Audio(url);
return () => {
refAudio.current?.pause();
refAudio.current = null;
};
}, []);
useEffect(() => {
if (!pageIsVisible) {
refAudio.current?.pause();
return;
}
if (isAudioOn) {
refAudio.current?.play();
return;
}
refAudio.current?.pause();
}, [pageIsVisible, isAudioOn]);
return (
<Button
variant="contained"
sx={{ position: "absolute", top: "10px", left: "85px", zIndex: "1" }}
onClick={toggle}
>
{isAudioOn ? <VolumeUpIcon /> : <VolumeOffIcon />}
</Button>
);
};
Но, раз всем OK, то, вероятно, здесь вопрос дискуссионный, так, что я не настаиваю.
const refIsAudioPlay = useRef<true | false>(false); | ||
const [foo, setFoo] = useState(false); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А чем эти 2 строчки в плане типов отличаются, почему они по-разному написаны?
Вообще говоря, тут тип автоматически выводится (как во второй строчке), но если уж хочется указать, почему не boolean
? <true | false>
- это какая-то конвенция? ))
isPlaying.current = !isPlaying.current; | ||
setNewRender(!newRender); | ||
refIsAudioPlay.current = !refIsAudioPlay.current; | ||
setFoo(!foo); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Честно говоря, мне в целом не нравится, как компонент написан. Как будто ненужные флаги, шаманское foo
, ну и опять же, смешались вместе кони, люди,...
Я бы вынес проверку видимости в отдельный хук, т.к. это может понадобиться и в других местах. Пускай не в нашем проекте, но надо же в общем думать и делать удобно для людей. Сейчас это не переиспользуемый сложночитаемый монолит. Я так считаю ))
В общем, я бы написал как-то так:
const usePageVisibility = (initialState = true) => {
const [pageIsVisible, setPageIsVisible] = useState(initialState);
useEffect(() => {
const handleVisibilitychange = () => {
if (document.hidden) {
setPageIsVisible(false);
} else {
setPageIsVisible(true);
}
};
document.addEventListener("visibilitychange", handleVisibilitychange);
return () => {
document.removeEventListener("visibilitychange", handleVisibilitychange);
};
}, []);
return pageIsVisible;
};
const Player: React.FC<PlayerType> = ({ url }) => {
const pageIsVisible = usePageVisibility();
const refAudio = useRef<HTMLAudioElement | null>(null);
const [isAudioOn, setIsAudioOn] = useState(false);
const toggle = () => {
setIsAudioOn(!isAudioOn);
};
useLayoutEffect(() => {
refAudio.current = new Audio(url);
return () => {
refAudio.current?.pause();
refAudio.current = null;
};
}, []);
useEffect(() => {
if (!pageIsVisible) {
refAudio.current?.pause();
return;
}
if (isAudioOn) {
refAudio.current?.play();
return;
}
refAudio.current?.pause();
}, [pageIsVisible, isAudioOn]);
return (
<Button
variant="contained"
sx={{ position: "absolute", top: "10px", left: "85px", zIndex: "1" }}
onClick={toggle}
>
{isAudioOn ? <VolumeUpIcon /> : <VolumeOffIcon />}
</Button>
);
};
Но, раз всем OK, то, вероятно, здесь вопрос дискуссионный, так, что я не настаиваю.
const usePageVisibility = (initialState = true) => { | ||
const [pageIsVisible, setPageIsVisible] = useState(initialState); | ||
|
||
useEffect(() => { | ||
const handleVisibilitychange = () => { | ||
if (document.hidden) { | ||
setPageIsVisible(false); | ||
} else { | ||
setPageIsVisible(true); | ||
} | ||
}; | ||
|
||
document.addEventListener("visibilitychange", handleVisibilitychange); | ||
|
||
return () => { | ||
document.removeEventListener("visibilitychange", handleVisibilitychange); | ||
}; | ||
}, []); | ||
|
||
return pageIsVisible; | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это хук. Нужно создать папку hooks
и поместить его туда.
- в
vite.config.ts
добавить alias для этой папки.
class timer { | ||
private currentTime: Date | undefined; | ||
start() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Название классов вроде с большой буквы обычно пишут.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- видимо пока не используется, потому что методы start/stop не рабочие (
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В целом все ок, но вот бы убрать неиспользуемый/не дописанный класс timer или доделать его
Какую задачу решаем
Добавляет Player на страницу с игрой.
Использован Page Visibility API для постановки фоновой музыки на паузу при не активной вкладке.