Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/eighty-masks-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@alfalab/core-components': patch
'@alfalab/core-components-gallery': patch
---

##### Gallery

- Заменен статический импорт hls.js на динамический.
- Добавлена retry логика для надежной загрузки.
104 changes: 80 additions & 24 deletions packages/gallery/src/components/image-viewer/video/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import React, {
useContext,
useEffect,
useRef,
useState,
} from 'react';
import cn from 'classnames';
import Hls from 'hls.js';
import type Hls from 'hls.js';

import { Circle } from '@alfalab/core-components-icon-view/circle';
import PlayCompactMIcon from '@alfalab/icons-glyph/PlayCompactMIcon';
Expand All @@ -28,6 +29,7 @@ type Props = {
export const Video = ({ url, index, className, isActive }: Props) => {
const playerRef = useRef<HTMLVideoElement>(null);
const timer = useRef<ReturnType<typeof setTimeout>>();
const [hlsSupported, setHlsSupported] = useState<boolean>(true);

const {
setImageMeta,
Expand All @@ -49,32 +51,86 @@ export const Video = ({ url, index, className, isActive }: Props) => {
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, [index]);

const loadHlsLibrary = useCallback(
async (attempt = 1, maxAttempts = 3): Promise<typeof Hls | null> => {
try {
const { default: HlsLib } = await import(
/* webpackChunkName: "hls-js-gallery" */ 'hls.js'
Copy link
Contributor

Choose a reason for hiding this comment

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

может лучше взять hls.js/dist/hls.min.js? он вроде поменьше размером. или добавить флажек, какой грузить...

Copy link
Author

Choose a reason for hiding this comment

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

  1. По поводу hls.js/dist/hls.min.js — переход на использование только этой версии (лёгкой) нам не подходит: пропадают субтитры (скрин выше, можно собрать демо и посмотреть).

  2. По поводу флага — такой подход тоже рассматривал, но у него есть минусы:

  • Пользователь галереи не владеет контентом: сейчас субтитров может не быть и стоит флаг на лёгкую версию, а если их потом добавят в поток — субтитры не появятся, пока флаг не сменим.

  • Если на странице есть и «полная», и «лёгкая» галереи, при открытии видео в обеих подгрузятся оба чанка.

Copy link
Contributor

Choose a reason for hiding this comment

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

2 галереи ето конечно плохо да.

но цена субтитров конечно запредельная :(

);

return HlsLib;
} catch {
if (attempt < maxAttempts) {
/* Экспоненциальная задержка ретрая: 300ms, 600ms, 1200ms */
await new Promise<void>((resolve) => {
setTimeout(
() => {
resolve();
},
300 * 2 ** (attempt - 1),
);
});

return loadHlsLibrary(attempt + 1, maxAttempts);
}

setHlsSupported(false);
setImageMeta({ player: { current: null }, broken: true }, index);

return null;
}
},
[setImageMeta, index],
);

useEffect(() => {
const hls = new Hls();

if (Hls.isSupported()) {
hls.on(Hls.Events.ERROR, (_, data) => {
if (data.fatal) {
switch (data.type) {
case Hls.ErrorTypes.MEDIA_ERROR:
hls.recoverMediaError();
break;
case Hls.ErrorTypes.NETWORK_ERROR:
setImageMeta({ player: { current: null }, broken: true }, index);
break;
default:
hls.destroy();
break;
}
let hls: Hls | null = null;

const initHls = async () => {
try {
const HlsLib = await loadHlsLibrary();

if (!HlsLib || !playerRef.current) {
return;
}
});

hls.loadSource(url);
if (playerRef.current) {
hls.attachMedia(playerRef.current);
hls.subtitleDisplay = false;
if (!HlsLib.isSupported()) {
setHlsSupported(false);

return;
}

hls = new HlsLib();

hls.on(HlsLib.Events.ERROR, (_, data) => {
if (data.fatal && hls) {
switch (data.type) {
case HlsLib.ErrorTypes.MEDIA_ERROR:
hls.recoverMediaError();
break;
case HlsLib.ErrorTypes.NETWORK_ERROR:
setImageMeta({ player: { current: null }, broken: true }, index);
break;
default:
hls.destroy();
break;
}
}
});

hls.loadSource(url);

if (playerRef.current) {
hls.attachMedia(playerRef.current);
hls.subtitleDisplay = false;
}
} catch {
setHlsSupported(false);
setImageMeta({ player: { current: null }, broken: true }, index);
}
}
};

initHls();

return () => {
if (hls) {
Expand Down Expand Up @@ -183,7 +239,7 @@ export const Video = ({ url, index, className, isActive }: Props) => {
playsInline={true}
muted={mutedVideo}
loop={true}
src={Hls.isSupported() ? undefined : url}
src={hlsSupported ? undefined : url}
className={cn(styles.video, { [styles.mobile]: view === 'mobile' }, className)}
>
<track kind='captions' />
Expand Down