lbry-desktop/ui/component/fileRenderFloating/view.jsx

401 lines
14 KiB
React
Raw Normal View History

2018-03-26 23:32:43 +02:00
// @flow
2019-08-13 07:35:13 +02:00
import * as ICONS from 'constants/icons';
import * as RENDER_MODES from 'constants/file_render_modes';
import React from 'react';
2019-08-13 07:35:13 +02:00
import Button from 'component/button';
2018-03-26 23:32:43 +02:00
import classnames from 'classnames';
import LoadingScreen from 'component/common/loading-screen';
import FileRender from 'component/fileRender';
2019-08-13 07:35:13 +02:00
import UriIndicator from 'component/uriIndicator';
2019-09-27 20:56:15 +02:00
import usePersistedState from 'effects/use-persisted-state';
import { PRIMARY_PLAYER_WRAPPER_CLASS } from 'page/file/view';
import Draggable from 'react-draggable';
2019-10-14 00:28:12 +02:00
import { onFullscreenChange } from 'util/full-screen';
import { generateListSearchUrlParams, formatLbryChannelName } from 'util/url';
2020-08-10 22:47:39 +02:00
import { useIsMobile } from 'effects/use-screensize';
import debounce from 'util/debounce';
import { useHistory } from 'react-router';
import { isURIEqual } from 'util/lbryURI';
import AutoplayCountdown from 'component/autoplayCountdown';
import usePlayNext from 'effects/use-play-next';
import { getScreenWidth, getScreenHeight, clampFloatingPlayerToScreen, calculateRelativePos } from './helper-functions';
2021-12-20 13:40:24 +01:00
// scss/init/vars.scss
// --header-height
const HEADER_HEIGHT = 60;
// --header-height-mobile
export const HEADER_HEIGHT_MOBILE = 56;
2021-12-20 13:40:24 +01:00
const IS_DESKTOP_MAC = typeof process === 'object' ? process.platform === 'darwin' : false;
const DEBOUNCE_WINDOW_RESIZE_HANDLER_MS = 100;
export const INLINE_PLAYER_WRAPPER_CLASS = 'inline-player__wrapper';
export const FLOATING_PLAYER_CLASS = 'content__viewer--floating';
// ****************************************************************************
// ****************************************************************************
2018-03-26 23:32:43 +02:00
type Props = {
claimId: ?string,
2022-03-16 12:35:58 +01:00
channelUrl: ?string,
2020-04-14 01:48:11 +02:00
isFloating: boolean,
2018-03-26 23:32:43 +02:00
uri: string,
2019-08-02 08:28:14 +02:00
streamingUrl?: string,
2019-08-13 07:35:13 +02:00
title: ?string,
floatingPlayerEnabled: boolean,
renderMode: string,
playingUri: PlayingUri,
primaryUri: ?string,
2021-01-08 16:21:27 +01:00
videoTheaterMode: boolean,
collectionId: string,
costInfo: any,
claimWasPurchased: boolean,
nextListUri: string,
previousListUri: string,
doFetchRecommendedContent: (uri: string) => void,
doUriInitiatePlay: (playingOptions: PlayingUri, isPlayable: ?boolean, isFloating: ?boolean) => void,
doSetPlayingUri: ({ uri?: ?string }) => void,
isCurrentClaimLive?: boolean,
mobilePlayerDimensions?: any,
socketConnected: boolean,
2022-03-15 17:48:57 +01:00
isLivestreamClaim: boolean,
2022-03-23 19:24:16 +01:00
geoRestriction: ?GeoRestriction,
doSetMobilePlayerDimensions: ({ height?: ?number, width?: ?number }) => void,
doCommentSocketConnect: (string, string, string) => void,
doCommentSocketDisconnect: (string, string) => void,
2018-03-26 23:32:43 +02:00
};
2017-04-23 11:56:50 +02:00
2020-04-14 01:48:11 +02:00
export default function FileRenderFloating(props: Props) {
const {
claimId,
2022-03-16 12:35:58 +01:00
channelUrl,
uri,
streamingUrl,
title,
isFloating,
floatingPlayerEnabled,
renderMode,
playingUri,
primaryUri,
2021-01-08 16:21:27 +01:00
videoTheaterMode,
collectionId,
costInfo,
claimWasPurchased,
nextListUri,
previousListUri,
socketConnected,
2022-03-15 17:48:57 +01:00
isLivestreamClaim,
doFetchRecommendedContent,
doUriInitiatePlay,
doSetPlayingUri,
isCurrentClaimLive,
mobilePlayerDimensions,
2022-03-23 19:24:16 +01:00
geoRestriction,
doSetMobilePlayerDimensions,
doCommentSocketConnect,
doCommentSocketDisconnect,
} = props;
2019-12-18 06:27:08 +01:00
const isMobile = useIsMobile();
const {
location: { state },
} = useHistory();
const hideFloatingPlayer = state && state.hideFloatingPlayer;
const { uri: playingUrl, source: playingUriSource, primaryUri: playingPrimaryUri } = playingUri;
const isComment = playingUriSource === 'comment';
2022-03-15 19:03:47 +01:00
const mainFilePlaying = !isFloating && primaryUri && isURIEqual(uri, primaryUri);
const noFloatingPlayer = !isFloating || !floatingPlayerEnabled || hideFloatingPlayer;
const [fileViewerRect, setFileViewerRect] = React.useState();
const [wasDragging, setWasDragging] = React.useState(false);
const [doNavigate, setDoNavigate] = React.useState(false);
const [shouldPlayNext, setPlayNext] = React.useState(true);
const [countdownCanceled, setCountdownCanceled] = React.useState(false);
2019-08-13 07:35:13 +02:00
const [position, setPosition] = usePersistedState('floating-file-viewer:position', {
x: -25,
y: window.innerHeight - 400,
});
const relativePosRef = React.useRef({ x: 0, y: 0 });
2020-04-14 01:48:11 +02:00
const navigateUrl =
(playingPrimaryUri || playingUrl || '') + (collectionId ? generateListSearchUrlParams(collectionId) : '');
const isFree = costInfo && costInfo.cost === 0;
const canViewFile = isFree || claimWasPurchased;
const isPlayable = RENDER_MODES.FLOATING_MODES.includes(renderMode) || isCurrentClaimLive;
2022-03-15 17:18:08 +01:00
const isReadyToPlay = isCurrentClaimLive || (isPlayable && streamingUrl);
// ****************************************************************************
// FUNCTIONS
// ****************************************************************************
const handleResize = React.useCallback(() => {
const element = mainFilePlaying
? document.querySelector(`.${PRIMARY_PLAYER_WRAPPER_CLASS}`)
: document.querySelector(`.${INLINE_PLAYER_WRAPPER_CLASS}`);
if (!element) return;
const rect = element.getBoundingClientRect();
// getBoundingClientRect returns a DomRect, not an object
const objectRect = {
top: rect.top,
right: rect.right,
bottom: rect.bottom,
left: rect.left,
width: rect.width,
height: rect.height,
2020-11-09 19:36:35 +01:00
// $FlowFixMe
x: rect.x,
};
// $FlowFixMe
setFileViewerRect({ ...objectRect, windowOffset: window.pageYOffset });
2019-08-13 07:35:13 +02:00
if (!mobilePlayerDimensions || mobilePlayerDimensions.height !== rect.height) {
doSetMobilePlayerDimensions({ height: rect.height, width: getScreenWidth() });
}
}, [doSetMobilePlayerDimensions, mainFilePlaying, mobilePlayerDimensions]);
const restoreToRelativePosition = React.useCallback(() => {
const SCROLL_BAR_PX = 12; // root: --body-scrollbar-width
const screenW = getScreenWidth() - SCROLL_BAR_PX;
const screenH = getScreenHeight();
const newX = Math.round(relativePosRef.current.x * screenW);
const newY = Math.round(relativePosRef.current.y * screenH);
setPosition(clampFloatingPlayerToScreen(newX, newY));
}, [setPosition]);
const clampToScreenOnResize = React.useCallback(
debounce(restoreToRelativePosition, DEBOUNCE_WINDOW_RESIZE_HANDLER_MS),
[]
);
// For playlists when pressing next/previous etc and switching players
function resetState() {
setCountdownCanceled(false);
setDoNavigate(false);
setPlayNext(true);
}
// ****************************************************************************
// EFFECTS
// ****************************************************************************
usePlayNext(
isFloating,
collectionId,
shouldPlayNext,
nextListUri,
previousListUri,
doNavigate,
doUriInitiatePlay,
resetState
);
// Establish web socket connection for viewer count.
React.useEffect(() => {
2022-03-16 12:35:58 +01:00
if (!claimId || !channelUrl || !isCurrentClaimLive) return;
2022-03-16 12:35:58 +01:00
const channelName = formatLbryChannelName(channelUrl);
2022-03-16 12:35:58 +01:00
// Only connect if not yet connected, so for example clicked on an embed instead of accessing
// from the Livestream page
if (!socketConnected) doCommentSocketConnect(uri, channelName, claimId);
2022-03-16 12:35:58 +01:00
// This will be used to disconnect for every case, since this is the main player component
return () => doCommentSocketDisconnect(claimId, channelName);
// only listen to socketConnected on initial mount
// eslint-disable-next-line react-hooks/exhaustive-deps
2022-03-16 12:35:58 +01:00
}, [channelUrl, claimId, doCommentSocketConnect, doCommentSocketDisconnect, isCurrentClaimLive, uri]);
React.useEffect(() => {
if (playingPrimaryUri || playingUrl) {
handleResize();
2019-08-13 07:35:13 +02:00
}
}, [handleResize, playingPrimaryUri, videoTheaterMode, playingUrl]);
2019-08-13 07:35:13 +02:00
// Listen to main-window resizing and adjust the floating player position accordingly:
React.useEffect(() => {
if (isFloating) {
// Ensure player is within screen when 'isFloating' changes.
restoreToRelativePosition();
} else {
handleResize();
}
function onWindowResize() {
return isFloating ? clampToScreenOnResize() : handleResize();
}
window.addEventListener('resize', onWindowResize);
if (!isFloating) onFullscreenChange(window, 'add', handleResize);
2019-12-19 21:43:49 +01:00
return () => {
window.removeEventListener('resize', onWindowResize);
if (!isFloating) onFullscreenChange(window, 'remove', handleResize);
2019-12-19 21:43:49 +01:00
};
// Only listen to these and avoid infinite loops
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [clampToScreenOnResize, handleResize, isFloating]);
React.useEffect(() => {
// Initial update for relativePosRef:
relativePosRef.current = calculateRelativePos(position.x, position.y);
// only on mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
React.useEffect(() => {
if (isFloating && isComment) {
// When the player begins floating, remove the comment source
// so that it doesn't try to resize again in case of going back
// to the origin's comment section and fail to position correctly
doSetPlayingUri({ ...playingUri, source: null });
}
}, [doSetPlayingUri, isComment, isFloating, playingUri]);
React.useEffect(() => {
if (isFloating) doFetchRecommendedContent(uri);
}, [doFetchRecommendedContent, isFloating, uri]);
React.useEffect(() => {
if (isFloating && isMobile) {
doSetMobilePlayerDimensions({ height: null, width: null });
}
}, [doSetMobilePlayerDimensions, doSetPlayingUri, isFloating, isMobile]);
if (
2022-03-23 19:24:16 +01:00
geoRestriction ||
!isPlayable ||
!uri ||
(isFloating && noFloatingPlayer) ||
2022-03-15 17:48:57 +01:00
(collectionId && !isFloating && ((!canViewFile && !nextListUri) || countdownCanceled)) ||
(isLivestreamClaim && !isCurrentClaimLive)
) {
return null;
}
// ****************************************************************************
// RENDER
// ****************************************************************************
function handleDragStart() {
// Not really necessary, but reset just in case 'handleStop' didn't fire.
setWasDragging(false);
}
function handleDragMove(e, ui) {
2019-08-14 05:04:08 +02:00
const { x, y } = position;
const newX = ui.x;
const newY = ui.y;
// Mark as dragging if the position changed and we were not dragging before.
if (!wasDragging && (newX !== x || newY !== y)) {
setWasDragging(true);
}
2019-08-14 05:04:08 +02:00
}
function handleDragStop(e, ui) {
if (wasDragging) setWasDragging(false);
const { x, y } = ui;
let newPos = { x, y };
if (newPos.x !== position.x || newPos.y !== position.y) {
newPos = clampFloatingPlayerToScreen(newPos.x, newPos.y);
setPosition(newPos);
relativePosRef.current = calculateRelativePos(newPos.x, newPos.y);
}
}
2019-08-02 08:28:14 +02:00
return (
<Draggable
2022-04-04 13:02:27 +02:00
onDrag={!isMobile ? handleDragMove : null}
onStart={!isMobile ? handleDragStart : null}
onStop={!isMobile ? handleDragStop : null}
defaultPosition={position}
position={isFloating ? position : { x: 0, y: 0 }}
bounds="parent"
disabled={noFloatingPlayer}
2022-04-04 13:02:27 +02:00
handle={!isMobile ? '.draggable' : ''}
cancel=".button"
>
<div
className={classnames('content__viewer', {
[FLOATING_PLAYER_CLASS]: isFloating,
'content__viewer--inline': !isFloating,
'content__viewer--secondary': isComment,
2022-03-15 17:18:08 +01:00
'content__viewer--theater-mode': videoTheaterMode && mainFilePlaying && !isCurrentClaimLive && !isMobile,
'content__viewer--disable-click': wasDragging,
2022-03-16 14:47:30 +01:00
'content__viewer--mobile': isMobile && !playingUriSource,
})}
style={
!isFloating && fileViewerRect
? {
width: fileViewerRect.width,
height: fileViewerRect.height,
left: fileViewerRect.x,
2022-03-16 14:47:30 +01:00
top:
isMobile && !playingUriSource
? HEADER_HEIGHT_MOBILE
: fileViewerRect.windowOffset +
fileViewerRect.top -
(!isMobile ? HEADER_HEIGHT - (IS_DESKTOP_MAC ? 24 : 0) : 0),
}
: {}
}
2019-08-13 07:35:13 +02:00
>
<div className={classnames('content__wrapper', { 'content__wrapper--floating': isFloating })}>
{isFloating && (
<Button
title={__('Close')}
onClick={() => doSetPlayingUri({ uri: null })}
icon={ICONS.REMOVE}
button="primary"
className="content__floating-close"
/>
)}
2022-03-15 17:18:08 +01:00
{isReadyToPlay ? (
2022-04-04 13:02:27 +02:00
<FileRender className={classnames({ draggable: !isMobile })} uri={uri} />
) : collectionId && !canViewFile ? (
<div className="content__loading">
<AutoplayCountdown
nextRecommendedUri={nextListUri}
doNavigate={() => setDoNavigate(true)}
doReplay={() => doUriInitiatePlay({ uri, collectionId }, false, isFloating)}
doPrevious={() => {
setPlayNext(false);
setDoNavigate(true);
}}
onCanceled={() => setCountdownCanceled(true)}
skipPaid
/>
</div>
) : (
<LoadingScreen status={__('Loading')} />
)}
{isFloating && (
2022-04-04 13:02:27 +02:00
<div className={classnames('content__info', { draggable: !isMobile })}>
<div className="claim-preview__title" title={title || uri}>
<Button label={title || uri} navigate={navigateUrl} button="link" className="content__floating-link" />
2019-08-13 07:35:13 +02:00
</div>
<UriIndicator link uri={uri} />
</div>
)}
2019-08-13 07:35:13 +02:00
</div>
</div>
</Draggable>
2019-08-02 08:28:14 +02:00
);
2017-04-23 11:56:50 +02:00
}