Skip to content
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

Merged
merged 7 commits into from
Apr 8, 2023

Conversation

EAbashin
Copy link
Contributor

@EAbashin EAbashin commented Apr 3, 2023

Какую задачу решаем

Добавляет Player на страницу с игрой.

Использован Page Visibility API для постановки фоновой музыки на паузу при не активной вкладке.

@vercel
Copy link

vercel bot commented Apr 3, 2023

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
uno-game-client ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 8, 2023 4:41pm

isPlaying.current = !isPlaying.current;
setNewRender(!newRender);
refIsAudioPlay.current = !refIsAudioPlay.current;
setFoo(!foo);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А это для чего? Не нашел, где foo используется.
Ну и название переменной, конечно, огонь ))

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нигде больше не используется)) Нужно как-то отображение кнопки Музыка поменять при её нажатии, делаю это через useState. А название переменной показывает, что оно не имеет значение (foo, bar - общепринятые). Думаешь лучше переименовать? Или комментарий оставить?

Copy link
Contributor

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, то, вероятно, здесь вопрос дискуссионный, так, что я не настаиваю.

Comment on lines 13 to 14
const refIsAudioPlay = useRef<true | false>(false);
const [foo, setFoo] = useState(false);
Copy link
Contributor

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);
Copy link
Contributor

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, то, вероятно, здесь вопрос дискуссионный, так, что я не настаиваю.

Comment on lines 11 to 31
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;
};
Copy link
Contributor

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 для этой папки.

Comment on lines +1 to +3
class timer {
private currentTime: Date | undefined;
start() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Название классов вроде с большой буквы обычно пишут.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • видимо пока не используется, потому что методы start/stop не рабочие (

Copy link

@Olegas Olegas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В целом все ок, но вот бы убрать неиспользуемый/не дописанный класс timer или доделать его

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants