Signed-off-by: marcin mikołajczak <git@mkljczk.pl>environments/review-events-5jp5it/deployments/1372
commit
3e0b6c38cd
@ -1,27 +0,0 @@
|
||||
import { staticClient } from '../api';
|
||||
|
||||
import type { AppDispatch } from 'soapbox/store';
|
||||
|
||||
const FETCH_MOBILE_PAGE_REQUEST = 'FETCH_MOBILE_PAGE_REQUEST';
|
||||
const FETCH_MOBILE_PAGE_SUCCESS = 'FETCH_MOBILE_PAGE_SUCCESS';
|
||||
const FETCH_MOBILE_PAGE_FAIL = 'FETCH_MOBILE_PAGE_FAIL';
|
||||
|
||||
const fetchMobilePage = (slug = 'index', locale?: string) =>
|
||||
(dispatch: AppDispatch) => {
|
||||
dispatch({ type: FETCH_MOBILE_PAGE_REQUEST, slug, locale });
|
||||
const filename = `${slug}${locale ? `.${locale}` : ''}.html`;
|
||||
return staticClient.get(`/instance/mobile/${filename}`).then(({ data: html }) => {
|
||||
dispatch({ type: FETCH_MOBILE_PAGE_SUCCESS, slug, locale, html });
|
||||
return html;
|
||||
}).catch(error => {
|
||||
dispatch({ type: FETCH_MOBILE_PAGE_FAIL, slug, locale, error });
|
||||
throw error;
|
||||
});
|
||||
};
|
||||
|
||||
export {
|
||||
FETCH_MOBILE_PAGE_REQUEST,
|
||||
FETCH_MOBILE_PAGE_SUCCESS,
|
||||
FETCH_MOBILE_PAGE_FAIL,
|
||||
fetchMobilePage,
|
||||
};
|
@ -1,19 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
import { fireEvent, render, screen } from '../../../jest/test-helpers';
|
||||
import ModerationOverlay from '../moderation-overlay';
|
||||
|
||||
describe('<ModerationOverlay />', () => {
|
||||
it('defaults to enabled', () => {
|
||||
render(<ModerationOverlay />);
|
||||
expect(screen.getByTestId('moderation-overlay')).toHaveTextContent('Content Under Review');
|
||||
});
|
||||
|
||||
it('can be toggled', () => {
|
||||
render(<ModerationOverlay />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('button'));
|
||||
expect(screen.getByTestId('moderation-overlay')).not.toHaveTextContent('Content Under Review');
|
||||
expect(screen.getByTestId('moderation-overlay')).toHaveTextContent('Hide');
|
||||
});
|
||||
});
|
@ -0,0 +1,111 @@
|
||||
import { Map as ImmutableMap } from 'immutable';
|
||||
import React from 'react';
|
||||
|
||||
import { normalizeStatus } from 'soapbox/normalizers';
|
||||
import { ReducerStatus } from 'soapbox/reducers/statuses';
|
||||
|
||||
import { fireEvent, render, rootState, screen } from '../../../jest/test-helpers';
|
||||
import SensitiveContentOverlay from '../sensitive-content-overlay';
|
||||
|
||||
describe('<SensitiveContentOverlay />', () => {
|
||||
let status: ReducerStatus;
|
||||
|
||||
describe('when the Status is marked as sensitive', () => {
|
||||
beforeEach(() => {
|
||||
status = normalizeStatus({ sensitive: true }) as ReducerStatus;
|
||||
});
|
||||
|
||||
it('displays the "Sensitive content" warning', () => {
|
||||
render(<SensitiveContentOverlay status={status} />);
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Sensitive content');
|
||||
});
|
||||
|
||||
it('can be toggled', () => {
|
||||
render(<SensitiveContentOverlay status={status} />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('button'));
|
||||
expect(screen.getByTestId('sensitive-overlay')).not.toHaveTextContent('Sensitive content');
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Hide');
|
||||
|
||||
fireEvent.click(screen.getByTestId('button'));
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Sensitive content');
|
||||
expect(screen.getByTestId('sensitive-overlay')).not.toHaveTextContent('Hide');
|
||||
});
|
||||
});
|
||||
|
||||
describe('when the Status is marked as in review', () => {
|
||||
beforeEach(() => {
|
||||
status = normalizeStatus({ visibility: 'self', sensitive: false }) as ReducerStatus;
|
||||
});
|
||||
|
||||
it('displays the "Under review" warning', () => {
|
||||
render(<SensitiveContentOverlay status={status} />);
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Content Under Review');
|
||||
});
|
||||
|
||||
it('can be toggled', () => {
|
||||
render(<SensitiveContentOverlay status={status} />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('button'));
|
||||
expect(screen.getByTestId('sensitive-overlay')).not.toHaveTextContent('Content Under Review');
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Hide');
|
||||
|
||||
fireEvent.click(screen.getByTestId('button'));
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Content Under Review');
|
||||
expect(screen.getByTestId('sensitive-overlay')).not.toHaveTextContent('Hide');
|
||||
});
|
||||
});
|
||||
|
||||
describe('when the Status is marked as in review and sensitive', () => {
|
||||
beforeEach(() => {
|
||||
status = normalizeStatus({ visibility: 'self', sensitive: true }) as ReducerStatus;
|
||||
});
|
||||
|
||||
it('displays the "Under review" warning', () => {
|
||||
render(<SensitiveContentOverlay status={status} />);
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Content Under Review');
|
||||
});
|
||||
|
||||
it('can be toggled', () => {
|
||||
render(<SensitiveContentOverlay status={status} />);
|
||||
|
||||
fireEvent.click(screen.getByTestId('button'));
|
||||
expect(screen.getByTestId('sensitive-overlay')).not.toHaveTextContent('Content Under Review');
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Hide');
|
||||
|
||||
fireEvent.click(screen.getByTestId('button'));
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Content Under Review');
|
||||
expect(screen.getByTestId('sensitive-overlay')).not.toHaveTextContent('Hide');
|
||||
});
|
||||
});
|
||||
|
||||
describe('when the Status is marked as sensitive and displayMedia set to "show_all"', () => {
|
||||
let store: any;
|
||||
|
||||
beforeEach(() => {
|
||||
status = normalizeStatus({ sensitive: true }) as ReducerStatus;
|
||||
store = rootState
|
||||
.set('settings', ImmutableMap({
|
||||
displayMedia: 'show_all',
|
||||
}));
|
||||
});
|
||||
|
||||
it('displays the "Under review" warning', () => {
|
||||
render(<SensitiveContentOverlay status={status} />, undefined, store);
|
||||
expect(screen.getByTestId('sensitive-overlay')).not.toHaveTextContent('Sensitive content');
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Hide');
|
||||
});
|
||||
|
||||
it('can be toggled', () => {
|
||||
render(<SensitiveContentOverlay status={status} />, undefined, store);
|
||||
|
||||
fireEvent.click(screen.getByTestId('button'));
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Sensitive content');
|
||||
expect(screen.getByTestId('sensitive-overlay')).not.toHaveTextContent('Hide');
|
||||
|
||||
fireEvent.click(screen.getByTestId('button'));
|
||||
expect(screen.getByTestId('sensitive-overlay')).not.toHaveTextContent('Sensitive content');
|
||||
expect(screen.getByTestId('sensitive-overlay')).toHaveTextContent('Hide');
|
||||
});
|
||||
});
|
||||
});
|
@ -1,93 +0,0 @@
|
||||
import classNames from 'clsx';
|
||||
import React, { useState } from 'react';
|
||||
import { defineMessages, useIntl } from 'react-intl';
|
||||
|
||||
import { useSoapboxConfig } from 'soapbox/hooks';
|
||||
|
||||
import { Button, HStack, Text } from '../ui';
|
||||
|
||||
const messages = defineMessages({
|
||||
hide: { id: 'moderation_overlay.hide', defaultMessage: 'Hide' },
|
||||
title: { id: 'moderation_overlay.title', defaultMessage: 'Content Under Review' },
|
||||
subtitle: { id: 'moderation_overlay.subtitle', defaultMessage: 'This Post has been sent to Moderation for review and is only visible to you. If you believe this is an error please contact Support.' },
|
||||
contact: { id: 'moderation_overlay.contact', defaultMessage: 'Contact' },
|
||||
show: { id: 'moderation_overlay.show', defaultMessage: 'Show Content' },
|
||||
});
|
||||
|
||||
const ModerationOverlay = () => {
|
||||
const intl = useIntl();
|
||||
|
||||
const { links } = useSoapboxConfig();
|
||||
|
||||
const [visible, setVisible] = useState<boolean>(false);
|
||||
|
||||
const toggleVisibility = (event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
event.stopPropagation();
|
||||
|
||||
setVisible((prevValue) => !prevValue);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames('absolute z-40', {
|
||||
'cursor-default backdrop-blur-lg rounded-lg w-full h-full border-0 flex justify-center items-center': !visible,
|
||||
'bg-gray-800/75 inset-0': !visible,
|
||||
'top-1 left-1': visible,
|
||||
})}
|
||||
data-testid='moderation-overlay'
|
||||
>
|
||||
{visible ? (
|
||||
<Button
|
||||
text={intl.formatMessage(messages.hide)}
|
||||
icon={require('@tabler/icons/eye-off.svg')}
|
||||
onClick={toggleVisibility}
|
||||
theme='transparent'
|
||||
size='sm'
|
||||
/>
|
||||
) : (
|
||||
<div className='text-center w-3/4 mx-auto space-y-4'>
|
||||
<div className='space-y-1'>
|
||||
<Text theme='white' weight='semibold'>
|
||||
{intl.formatMessage(messages.title)}
|
||||
</Text>
|
||||
|
||||
<Text theme='white' size='sm' weight='medium'>
|
||||
{intl.formatMessage(messages.subtitle)}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<HStack alignItems='center' justifyContent='center' space={2}>
|
||||
{links.get('support') && (
|
||||
<a
|
||||
href={links.get('support')}
|
||||
target='_blank'
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<Button
|
||||
type='button'
|
||||
theme='outline'
|
||||
size='sm'
|
||||
icon={require('@tabler/icons/headset.svg')}
|
||||
>
|
||||
{intl.formatMessage(messages.contact)}
|
||||
</Button>
|
||||
</a>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type='button'
|
||||
theme='outline'
|
||||
size='sm'
|
||||
icon={require('@tabler/icons/eye.svg')}
|
||||
onClick={toggleVisibility}
|
||||
>
|
||||
{intl.formatMessage(messages.show)}
|
||||
</Button>
|
||||
</HStack>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ModerationOverlay;
|
@ -0,0 +1,124 @@
|
||||
import classNames from 'clsx';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { defineMessages, useIntl } from 'react-intl';
|
||||
|
||||
import { useSettings, useSoapboxConfig } from 'soapbox/hooks';
|
||||
import { defaultMediaVisibility } from 'soapbox/utils/status';
|
||||
|
||||
import { Button, HStack, Text } from '../ui';
|
||||
|
||||
import type { Status as StatusEntity } from 'soapbox/types/entities';
|
||||
|
||||
const messages = defineMessages({
|
||||
hide: { id: 'moderation_overlay.hide', defaultMessage: 'Hide content' },
|
||||
sensitiveTitle: { id: 'status.sensitive_warning', defaultMessage: 'Sensitive content' },
|
||||
underReviewTitle: { id: 'moderation_overlay.title', defaultMessage: 'Content Under Review' },
|
||||
underReviewSubtitle: { id: 'moderation_overlay.subtitle', defaultMessage: 'This Post has been sent to Moderation for review and is only visible to you. If you believe this is an error please contact Support.' },
|
||||
sensitiveSubtitle: { id: 'status.sensitive_warning.subtitle', defaultMessage: 'This content may not be suitable for all audiences.' },
|
||||
contact: { id: 'moderation_overlay.contact', defaultMessage: 'Contact' },
|
||||
show: { id: 'moderation_overlay.show', defaultMessage: 'Show Content' },
|
||||
});
|
||||
|
||||
interface ISensitiveContentOverlay {
|
||||
status: StatusEntity
|
||||
onToggleVisibility?(): void
|
||||
visible?: boolean
|
||||
}
|
||||
|
||||
const SensitiveContentOverlay = (props: ISensitiveContentOverlay) => {
|
||||
const { onToggleVisibility, status } = props;
|
||||
const isUnderReview = status.visibility === 'self';
|
||||
|
||||
const settings = useSettings();
|
||||
const displayMedia = settings.get('displayMedia') as string;
|
||||
|
||||
const intl = useIntl();
|
||||
|
||||
const { links } = useSoapboxConfig();
|
||||
|
||||
const [visible, setVisible] = useState<boolean>(defaultMediaVisibility(status, displayMedia));
|
||||
|
||||
const toggleVisibility = (event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
event.stopPropagation();
|
||||
|
||||
if (onToggleVisibility) {
|
||||
onToggleVisibility();
|
||||
} else {
|
||||
setVisible((prevValue) => !prevValue);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof props.visible !== 'undefined') {
|
||||
setVisible(!!props.visible);
|
||||
}
|
||||
}, [props.visible]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames('absolute z-40', {
|
||||
'cursor-default backdrop-blur-lg rounded-lg w-full h-full border-0 flex justify-center items-center': !visible,
|
||||
'bg-gray-800/75 inset-0': !visible,
|
||||
'bottom-1 right-1': visible,
|
||||
})}
|
||||
data-testid='sensitive-overlay'
|
||||
>
|
||||
{visible ? (
|
||||
<Button
|
||||
text={intl.formatMessage(messages.hide)}
|
||||
icon={require('@tabler/icons/eye-off.svg')}
|
||||
onClick={toggleVisibility}
|
||||
theme='primary'
|
||||
size='sm'
|
||||
/>
|
||||
) : (
|
||||
<div className='text-center w-3/4 mx-auto space-y-4'>
|
||||
<div className='space-y-1'>
|
||||
<Text theme='white' weight='semibold'>
|
||||
{intl.formatMessage(isUnderReview ? messages.underReviewTitle : messages.sensitiveTitle)}
|
||||
</Text>
|
||||
|
||||
<Text theme='white' size='sm' weight='medium'>
|
||||
{intl.formatMessage(isUnderReview ? messages.underReviewSubtitle : messages.sensitiveSubtitle)}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<HStack alignItems='center' justifyContent='center' space={2}>
|
||||
{isUnderReview ? (
|
||||
<>
|
||||
{links.get('support') && (
|
||||
<a
|
||||
href={links.get('support')}
|
||||
target='_blank'
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<Button
|
||||
type='button'
|
||||
theme='outline'
|
||||
size='sm'
|
||||
icon={require('@tabler/icons/headset.svg')}
|
||||
>
|
||||
{intl.formatMessage(messages.contact)}
|
||||
</Button>
|
||||
</a>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
type='button'
|
||||
theme='outline'
|
||||
size='sm'
|
||||
icon={require('@tabler/icons/eye.svg')}
|
||||
onClick={toggleVisibility}
|
||||
>
|
||||
{intl.formatMessage(messages.show)}
|
||||
</Button>
|
||||
</HStack>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SensitiveContentOverlay;
|
@ -0,0 +1,39 @@
|
||||
import { getSettings } from 'soapbox/actions/settings';
|
||||
import { normalizeCard } from 'soapbox/normalizers';
|
||||
|
||||
import type { AdProvider } from '.';
|
||||
import type { Card } from 'soapbox/types/entities';
|
||||
|
||||
/** TruthSocial ad API entity. */
|
||||
interface TruthAd {
|
||||
impression: string,
|
||||
card: Card,
|
||||
expires_at: string,
|
||||
reason: string,
|
||||
}
|
||||
|
||||
/** Provides ads from the TruthSocial API. */
|
||||
const TruthAdProvider: AdProvider = {
|
||||
getAds: async(getState) => {
|
||||
const state = getState();
|
||||
const settings = getSettings(state);
|
||||
|
||||
const response = await fetch('/api/v2/truth/ads?device=desktop', {
|
||||
headers: {
|
||||
'Accept-Language': settings.get('locale', '*') as string,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json() as TruthAd[];
|
||||
return data.map(item => ({
|
||||
...item,
|
||||
card: normalizeCard(item.card),
|
||||
}));
|
||||
}
|
||||
|
||||
return [];
|
||||
},
|
||||
};
|
||||
|
||||
export default TruthAdProvider;
|
@ -1,535 +0,0 @@
|
||||
import classNames from 'clsx';
|
||||
import debounce from 'lodash/debounce';
|
||||
import throttle from 'lodash/throttle';
|
||||
import PropTypes from 'prop-types';
|
||||
import React from 'react';
|
||||
import { defineMessages, injectIntl } from 'react-intl';
|
||||
|
||||
import Icon from 'soapbox/components/icon';
|
||||
import { formatTime, getPointerPosition, fileNameFromURL } from 'soapbox/features/video';
|
||||
|
||||
import Visualizer from './visualizer';
|
||||
|
||||
const messages = defineMessages({
|
||||
play: { id: 'video.play', defaultMessage: 'Play' },
|
||||
pause: { id: 'video.pause', defaultMessage: 'Pause' },
|
||||
mute: { id: 'video.mute', defaultMessage: 'Mute sound' },
|
||||
unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' },
|
||||
download: { id: 'video.download', defaultMessage: 'Download file' },
|
||||
});
|
||||
|
||||
const TICK_SIZE = 10;
|
||||
const PADDING = 180;
|
||||
|
||||
export default @injectIntl
|
||||
class Audio extends React.PureComponent {
|
||||
|
||||
static propTypes = {
|
||||
src: PropTypes.string.isRequired,
|
||||
alt: PropTypes.string,
|
||||
poster: PropTypes.string,
|
||||
duration: PropTypes.number,
|
||||
width: PropTypes.number,
|
||||
height: PropTypes.number,
|
||||
editable: PropTypes.bool,
|
||||
fullscreen: PropTypes.bool,
|
||||
intl: PropTypes.object.isRequired,
|
||||
cacheWidth: PropTypes.func,
|
||||
backgroundColor: PropTypes.string,
|
||||
foregroundColor: PropTypes.string,
|
||||
accentColor: PropTypes.string,
|
||||
currentTime: PropTypes.number,
|
||||
autoPlay: PropTypes.bool,
|
||||
volume: PropTypes.number,
|
||||
muted: PropTypes.bool,
|
||||
deployPictureInPicture: PropTypes.func,
|
||||
};
|
||||
|
||||
state = {
|
||||
width: this.props.width,
|
||||
currentTime: 0,
|
||||
buffer: 0,
|
||||
duration: null,
|
||||
paused: true,
|
||||
muted: false,
|
||||
volume: 0.5,
|
||||
dragging: false,
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.visualizer = new Visualizer(TICK_SIZE);
|
||||
}
|
||||
|
||||
setPlayerRef = c => {
|
||||
this.player = c;
|
||||
|
||||
if (this.player) {
|
||||
this._setDimensions();
|
||||
}
|
||||
}
|
||||
|
||||
_pack() {
|
||||
return {
|
||||
src: this.props.src,
|
||||
volume: this.audio.volume,
|
||||
muted: this.audio.muted,
|
||||
currentTime: this.audio.currentTime,
|
||||
poster: this.props.poster,
|
||||
backgroundColor: this.props.backgroundColor,
|
||||
foregroundColor: this.props.foregroundColor,
|
||||
accentColor: this.props.accentColor,
|
||||
};
|
||||
}
|
||||
|
||||
_setDimensions() {
|
||||
const width = this.player.offsetWidth;
|
||||
const height = this.props.fullscreen ? this.player.offsetHeight : (width / (16 / 9));
|
||||
|
||||
if (this.props.cacheWidth) {
|
||||
this.props.cacheWidth(width);
|
||||
}
|
||||
|
||||
this.setState({ width, height });
|
||||
}
|
||||
|
||||
setSeekRef = c => {
|
||||
this.seek = c;
|
||||
}
|
||||
|
||||
setVolumeRef = c => {
|
||||
this.volume = c;
|
||||
}
|
||||
|
||||
setAudioRef = c => {
|
||||
this.audio = c;
|
||||
|
||||
if (this.audio) {
|
||||
this.setState({ volume: this.audio.volume, muted: this.audio.muted });
|
||||
}
|
||||
}
|
||||
|
||||
setCanvasRef = c => {
|
||||
this.canvas = c;
|
||||
|
||||
this.visualizer.setCanvas(c);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
window.addEventListener('scroll', this.handleScroll);
|
||||
window.addEventListener('resize', this.handleResize, { passive: true });
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps, prevState) {
|
||||
if (prevProps.src !== this.props.src || this.state.width !== prevState.width || this.state.height !== prevState.height || prevProps.accentColor !== this.props.accentColor) {
|
||||
this._clear();
|
||||
this._draw();
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
window.removeEventListener('scroll', this.handleScroll);
|
||||
window.removeEventListener('resize', this.handleResize);
|
||||
|
||||
if (!this.state.paused && this.audio && this.props.deployPictureInPicture) {
|
||||
this.props.deployPictureInPicture('audio', this._pack());
|
||||
}
|
||||
}
|
||||
|
||||
togglePlay = () => {
|
||||
if (!this.audioContext) {
|
||||
this._initAudioContext();
|
||||
}
|
||||
|
||||
if (this.state.paused) {
|
||||
this.setState({ paused: false }, () => this.audio.play());
|
||||
} else {
|
||||
this.setState({ paused: true }, () => this.audio.pause());
|
||||
}
|
||||
}
|
||||
|
||||
handleResize = debounce(() => {
|
||||
if (this.player) {
|
||||
this._setDimensions();
|
||||
}
|
||||
}, 250, {
|
||||
trailing: true,
|
||||
});
|
||||
|
||||
handlePlay = () => {
|
||||
this.setState({ paused: false });
|
||||
|
||||
if (this.audioContext && this.audioContext.state === 'suspended') {
|
||||
this.audioContext.resume();
|
||||
}
|
||||
|
||||
this._renderCanvas();
|
||||
}
|
||||
|
||||
handlePause = () => {
|
||||
this.setState({ paused: true });
|
||||
|
||||
if (this.audioContext) {
|
||||
this.audioContext.suspend();
|
||||
}
|
||||
}
|
||||
|
||||
handleProgress = () => {
|
||||
const lastTimeRange = this.audio.buffered.length - 1;
|
||||
|
||||
if (lastTimeRange > -1) {
|
||||
this.setState({ buffer: Math.ceil(this.audio.buffered.end(lastTimeRange) / this.audio.duration * 100) });
|
||||
}
|
||||
}
|
||||
|
||||
toggleMute = () => {
|
||||
const muted = !this.state.muted;
|
||||
|
||||
this.setState({ muted }, () => {
|
||||
this.audio.muted = muted;
|
||||
});
|
||||
}
|
||||
|
||||
handleVolumeMouseDown = e => {
|
||||
document.addEventListener('mousemove', this.handleMouseVolSlide, true);
|
||||
document.addEventListener('mouseup', this.handleVolumeMouseUp, true);
|
||||
document.addEventListener('touchmove', this.handleMouseVolSlide, true);
|
||||
document.addEventListener('touchend', this.handleVolumeMouseUp, true);
|
||||
|
||||
this.handleMouseVolSlide(e);
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
|
||||
handleVolumeMouseUp = () => {
|
||||
document.removeEventListener('mousemove', this.handleMouseVolSlide, true);
|
||||
document.removeEventListener('mouseup', this.handleVolumeMouseUp, true);
|
||||
document.removeEventListener('touchmove', this.handleMouseVolSlide, true);
|
||||
document.removeEventListener('touchend', this.handleVolumeMouseUp, true);
|
||||
}
|
||||
|
||||
handleMouseDown = e => {
|
||||
document.addEventListener('mousemove', this.handleMouseMove, true);
|
||||
document.addEventListener('mouseup', this.handleMouseUp, true);
|
||||
document.addEventListener('touchmove', this.handleMouseMove, true);
|
||||
document.addEventListener('touchend', this.handleMouseUp, true);
|
||||
|
||||
this.setState({ dragging: true });
|
||||
this.audio.pause();
|
||||
this.handleMouseMove(e);
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
|
||||
handleMouseUp = () => {
|
||||
document.removeEventListener('mousemove', this.handleMouseMove, true);
|
||||
document.removeEventListener('mouseup', this.handleMouseUp, true);
|
||||
document.removeEventListener('touchmove', this.handleMouseMove, true);
|
||||
document.removeEventListener('touchend', this.handleMouseUp, true);
|
||||
|
||||
this.setState({ dragging: false });
|
||||
this.audio.play();
|
||||
}
|
||||
|
||||
handleMouseMove = throttle(e => {
|
||||
const { x } = getPointerPosition(this.seek, e);
|
||||
const currentTime = this.audio.duration * x;
|
||||
|
||||
if (!isNaN(currentTime)) {
|
||||
this.setState({ currentTime }, () => {
|
||||
this.audio.currentTime = currentTime;
|
||||
});
|
||||
}
|
||||
}, 15);
|
||||
|
||||
handleTimeUpdate = () => {
|
||||
this.setState({
|
||||
currentTime: this.audio.currentTime,
|
||||
duration: this.audio.duration,
|
||||
});
|
||||
}
|
||||
|
||||
handleMouseVolSlide = throttle(e => {
|
||||
const { x } = getPointerPosition(this.volume, e);
|
||||
|
||||
if (!isNaN(x)) {
|
||||
this.setState({ volume: x }, () => {
|
||||
this.audio.volume = x;
|
||||
});
|
||||
}
|
||||
}, 15);
|
||||
|
||||
handleScroll = throttle(() => {
|
||||
if (!this.canvas || !this.audio) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { top, height } = this.canvas.getBoundingClientRect();
|
||||
const inView = (top <= (window.innerHeight || document.documentElement.clientHeight)) && (top + height >= 0);
|
||||
|
||||
if (!this.state.paused && !inView) {
|
||||
this.audio.pause();
|
||||
|
||||
if (this.props.deployPictureInPicture) {
|
||||
this.props.deployPictureInPicture('audio', this._pack());
|
||||
}
|
||||
|
||||
this.setState({ paused: true });
|
||||
}
|
||||
}, 150, { trailing: true });
|
||||
|
||||
handleMouseEnter = () => {
|
||||
this.setState({ hovered: true });
|
||||
}
|
||||
|
||||
handleMouseLeave = () => {
|
||||
this.setState({ hovered: false });
|
||||
}
|
||||
|
||||
handleLoadedData = () => {
|
||||
const { autoPlay, currentTime, volume, muted } = this.props;
|
||||
|
||||
this.setState({ duration: this.audio.duration });
|
||||
|
||||
if (currentTime) {
|
||||
this.audio.currentTime = currentTime;
|
||||
}
|
||||
|
||||
if (volume !== undefined) {
|
||||
this.audio.volume = volume;
|
||||
}
|
||||
|
||||
if (muted !== undefined) {
|
||||
this.audio.muted = muted;
|
||||
}
|
||||
|
||||
if (autoPlay) {
|
||||
this.togglePlay();
|
||||
}
|
||||
}
|
||||
|
||||
_initAudioContext() {
|
||||
// eslint-disable-next-line compat/compat
|
||||
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
||||
const context = new AudioContext();
|
||||
const source = context.createMediaElementSource(this.audio);
|
||||
|
||||
this.visualizer.setAudioContext(context, source);
|
||||
source.connect(context.destination);
|
||||
|
||||
this.audioContext = context;
|
||||
}
|
||||
|
||||
handleDownload = () => {
|
||||
fetch(this.props.src).then(res => res.blob()).then(blob => {
|
||||
const element = document.createElement('a');
|
||||
const objectURL = URL.createObjectURL(blob);
|
||||
|
||||
element.setAttribute('href', objectURL);
|
||||
element.setAttribute('download', fileNameFromURL(this.props.src));
|
||||
|
||||
document.body.appendChild(element);
|
||||
element.click();
|
||||
document.body.removeChild(element);
|
||||
|
||||
URL.revokeObjectURL(objectURL);
|
||||
}).catch(err => {
|
||||
console.error(err);
|
||||
});
|
||||
}
|
||||
|
||||
_renderCanvas() {
|
||||
requestAnimationFrame(() => {
|
||||
if (!this.audio) return;
|
||||
|
||||
this.handleTimeUpdate();
|
||||
this._clear();
|
||||
this._draw();
|
||||
|
||||
if (!this.state.paused) {
|
||||
this._renderCanvas();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_clear() {
|
||||
this.visualizer.clear(this.state.width, this.state.height);
|
||||
}
|
||||
|
||||
_draw() {
|
||||
this.visualizer.draw(this._getCX(), this._getCY(), this._getAccentColor(), this._getRadius(), this._getScaleCoefficient());
|
||||
}
|
||||
|
||||
_getRadius() {
|
||||
return parseInt(((this.state.height || this.props.height) - (PADDING * this._getScaleCoefficient()) * 2) / 2);
|
||||
}
|
||||
|
||||
_getScaleCoefficient() {
|
||||
return (this.state.height || this.props.height) / 982;
|
||||
}
|
||||
|
||||
_getCX() {
|
||||
return Math.floor(this.state.width / 2) || null;
|
||||
}
|
||||
|
||||
_getCY() {
|
||||
return Math.floor(this._getRadius() + (PADDING * this._getScaleCoefficient())) || null;
|
||||
}
|
||||
|
||||
_getAccentColor() {
|
||||
return this.props.accentColor || '#ffffff';
|
||||
}
|
||||
|
||||
_getBackgroundColor() {
|
||||
return this.props.backgroundColor || '#000000';
|
||||
}
|
||||
|
||||
_getForegroundColor() {
|
||||
return this.props.foregroundColor || '#ffffff';
|
||||
}
|
||||
|
||||
seekBy(time) {
|
||||
const currentTime = this.audio.currentTime + time;
|
||||
|
||||
if (!isNaN(currentTime)) {
|
||||
this.setState({ currentTime }, () => {
|
||||
this.audio.currentTime = currentTime;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
handleAudioKeyDown = e => {
|
||||
// On the audio element or the seek bar, we can safely use the space bar
|
||||
// for playback control because there are no buttons to press
|
||||
|
||||
if (e.key === ' ') {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.togglePlay();
|
||||
}
|
||||
}
|
||||
|
||||
handleKeyDown = e => {
|
||||
switch (e.key) {
|
||||
case 'k':
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.togglePlay();
|
||||
break;
|
||||
case 'm':
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.toggleMute();
|
||||
break;
|
||||
case 'j':
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.seekBy(-10);
|
||||
break;
|
||||
case 'l':
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.seekBy(10);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const { src, intl, alt, editable } = this.props;
|
||||
const { paused, muted, volume, currentTime, buffer, dragging } = this.state;
|
||||
const duration = this.state.duration || this.props.duration;
|
||||
const progress = Math.min((currentTime / duration) * 100, 100);
|
||||
|
||||
return (
|
||||
<div className={classNames('audio-player', { editable })} ref={this.setPlayerRef} style={{ backgroundColor: this._getBackgroundColor(), color: this._getForegroundColor(), width: '100%', height: this.props.fullscreen ? '100%' : (this.state.height || this.props.height) }} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} tabIndex='0' onKeyDown={this.handleKeyDown}>
|
||||
<audio
|
||||
src={src}
|
||||
ref={this.setAudioRef}
|
||||
preload='auto'
|
||||
onPlay={this.handlePlay}
|
||||
onPause={this.handlePause}
|
||||
onProgress={this.handleProgress}
|
||||
onLoadedData={this.handleLoadedData}
|
||||
crossOrigin='anonymous'
|
||||
/>
|
||||
|
||||
<canvas
|
||||
role='button'
|
||||
tabIndex='0'
|
||||
className='audio-player__canvas'
|
||||
width={this.state.width}
|
||||
height={this.state.height}
|
||||
style={{ width: '100%', position: 'absolute', top: 0, left: 0 }}
|
||||
ref={this.setCanvasRef}
|
||||
onClick={this.togglePlay}
|
||||
onKeyDown={this.handleAudioKeyDown}
|
||||
title={alt}
|
||||
aria-label={alt}
|
||||
/>
|
||||
|
||||
{this.props.poster && <img
|
||||
src={this.props.poster}
|
||||
alt=''
|
||||
width={(this._getRadius() - TICK_SIZE) * 2 || null}
|
||||
height={(this._getRadius() - TICK_SIZE) * 2 || null}
|
||||
style={{ position: 'absolute', left: this._getCX(), top: this._getCY(), transform: 'translate(-50%, -50%)', borderRadius: '50%', pointerEvents: 'none' }}
|
||||
/>}
|
||||
|
||||
<div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}>
|
||||
<div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} />
|
||||
<div className='video-player__seek__progress' style={{ width: `${progress}%`, backgroundColor: this._getAccentColor() }} />
|
||||
|
||||
<span
|
||||
className={classNames('video-player__seek__handle', { active: dragging })}
|
||||
tabIndex='0'
|
||||
style={{ left: `${progress}%`, backgroundColor: this._getAccentColor() }}
|
||||
onKeyDown={this.handleAudioKeyDown}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='video-player__controls active'>
|
||||
<div className='video-player__buttons-bar'>
|
||||
<div className='video-player__buttons left'>
|
||||
<button type='button' title={intl.formatMessage(paused ? messages.play : messages.pause)} aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} className='player-button' onClick={this.togglePlay}><Icon src={paused ? require('@tabler/icons/player-play.svg') : require('@tabler/icons/player-pause.svg')} /></button>
|
||||
<button type='button' title={intl.formatMessage(muted ? messages.unmute : messages.mute)} aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} className='player-button' onClick={this.toggleMute}><Icon src={muted ? require('@tabler/icons/volume-3.svg') : require('@tabler/icons/volume.svg')} /></button>
|
||||
|
||||
<div className={classNames('video-player__volume', { active: this.state.hovered })} ref={this.setVolumeRef} onMouseDown={this.handleVolumeMouseDown}>
|
||||
<div className='video-player__volume__current' style={{ width: `${volume * 100}%`, backgroundColor: this._getAccentColor() }} />
|
||||
|
||||
<span
|
||||
className='video-player__volume__handle'
|
||||
tabIndex='0'
|
||||
style={{ left: `${volume * 100}%`, backgroundColor: this._getAccentColor() }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span className='video-player__time'>
|
||||
<span className='video-player__time-current'>{formatTime(Math.floor(currentTime))}</span>
|
||||
{duration && (<>
|
||||
<span className='video-player__time-sep'>/</span>
|
||||
<span className='video-player__time-total'>{formatTime(Math.floor(duration))}</span>
|
||||
</>)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className='video-player__buttons right'>
|
||||
<a
|
||||
title={intl.formatMessage(messages.download)}
|
||||
aria-label={intl.formatMessage(messages.download)}
|
||||
className='video-player__download__icon player-button'
|
||||
href={this.props.src}
|
||||
download
|
||||
target='_blank'
|
||||
>
|
||||
<Icon src={require('@tabler/icons/download.svg')} />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,583 @@
|
||||
import classNames from 'clsx';
|
||||
import debounce from 'lodash/debounce';
|
||||
import throttle from 'lodash/throttle';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { defineMessages, useIntl } from 'react-intl';
|
||||
|
||||
import Icon from 'soapbox/components/icon';
|
||||
import { formatTime, getPointerPosition } from 'soapbox/features/video';
|
||||
|
||||
import Visualizer from './visualizer';
|
||||
|
||||
const messages = defineMessages({
|
||||
play: { id: 'video.play', defaultMessage: 'Play' },
|
||||
pause: { id: 'video.pause', defaultMessage: 'Pause' },
|
||||
mute: { id: 'video.mute', defaultMessage: 'Mute sound' },
|
||||
unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' },
|
||||
download: { id: 'video.download', defaultMessage: 'Download file' },
|
||||
});
|
||||
|
||||
const TICK_SIZE = 10;
|
||||
const PADDING = 180;
|
||||
|
||||
interface IAudio {
|
||||
src: string,
|
||||
alt?: string,
|
||||
poster?: string,
|
||||
duration?: number,
|
||||
width?: number,
|
||||
height?: number,
|
||||
editable?: boolean,
|
||||
fullscreen?: boolean,
|
||||
cacheWidth?: (width: number) => void,
|
||||
backgroundColor?: string,
|
||||
foregroundColor?: string,
|
||||
accentColor?: string,
|
||||
currentTime?: number,
|
||||
autoPlay?: boolean,
|
||||
volume?: number,
|
||||
muted?: boolean,
|
||||
deployPictureInPicture?: (type: string, opts: Record<string, any>) => void,
|
||||
}
|
||||
|
||||
const Audio: React.FC<IAudio> = (props) => {
|
||||
const {
|
||||
src,
|
||||
alt = '',
|
||||
poster,
|
||||
accentColor,
|
||||
backgroundColor,
|
||||
foregroundColor,
|
||||
cacheWidth,
|
||||
fullscreen,
|
||||
autoPlay,
|
||||
editable,
|
||||
deployPictureInPicture = false,
|
||||
} = props;
|
||||
|
||||
const intl = useIntl();
|
||||
|
||||
const [width, setWidth] = useState<number | undefined>(props.width);
|
||||
const [height, setHeight] = useState<number | undefined>(props.height);
|
||||
const [currentTime, setCurrentTime] = useState(0);
|
||||
const [buffer, setBuffer] = useState(0);
|
||||
const [duration, setDuration] = useState<number | undefined>(undefined);
|
||||
const [paused, setPaused] = useState(true);
|
||||
const [muted, setMuted] = useState(false);
|
||||
const [volume, setVolume] = useState(0.5);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [hovered, setHovered] = useState(false);
|
||||
|
||||
const visualizer = useRef<Visualizer>(new Visualizer(TICK_SIZE));
|
||||
const audioContext = useRef<AudioContext | null>(null);
|
||||
|
||||
const player = useRef<HTMLDivElement>(null);
|
||||
const audio = useRef<HTMLAudioElement>(null);
|
||||
const seek = useRef<HTMLDivElement>(null);
|
||||
const slider = useRef<HTMLDivElement>(null);
|
||||
const canvas = useRef<HTMLCanvasElement>(null);
|
||||
|
||||
const _pack = () => ({
|
||||
src: props.src,
|
||||
volume: audio.current?.volume,
|
||||
muted: audio.current?.muted,
|
||||
currentTime: audio.current?.currentTime,
|
||||
poster: props.poster,
|
||||
backgroundColor: props.backgroundColor,
|
||||
foregroundColor: props.foregroundColor,
|
||||
accentColor: props.accentColor,
|
||||
});
|
||||
|
||||
const _setDimensions = () => {
|
||||
if (player.current) {
|
||||
const width = player.current.offsetWidth;
|
||||
const height = fullscreen ? player.current.offsetHeight : (width / (16 / 9));
|
||||
|
||||
if (cacheWidth) {
|
||||
cacheWidth(width);
|
||||
}
|
||||
|
||||
setWidth(width);
|
||||
setHeight(height);
|
||||
}
|
||||
};
|
||||
|
||||
const togglePlay = () => {
|
||||
if (!audioContext.current) {
|
||||
_initAudioContext();
|
||||
}
|
||||
|
||||
if (paused) {
|
||||
audio.current?.play();
|
||||
} else {
|
||||
audio.current?.pause();
|
||||
}
|
||||
|
||||
setPaused(!paused);
|
||||
};
|
||||
|
||||
const handleResize = debounce(() => {
|
||||
if (player.current) {
|
||||
_setDimensions();
|
||||
}
|
||||
}, 250, {
|
||||
trailing: true,
|
||||
});
|
||||
|
||||
const handlePlay = () => {
|
||||
setPaused(false);
|
||||
|
||||
if (audioContext.current?.state === 'suspended') {
|
||||
audioContext.current?.resume();
|
||||
}
|
||||
|
||||
_renderCanvas();
|
||||
};
|
||||
|
||||
const handlePause = () => {
|
||||
setPaused(true);
|
||||
audioContext.current?.suspend();
|
||||
};
|
||||
|
||||
const handleProgress = () => {
|
||||
if (audio.current) {
|
||||
const lastTimeRange = audio.current.buffered.length - 1;
|
||||
|
||||
if (lastTimeRange > -1) {
|
||||
setBuffer(Math.ceil(audio.current.buffered.end(lastTimeRange) / audio.current.duration * 100));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const toggleMute = () => {
|
||||
const nextMuted = !muted;
|
||||
|
||||
setMuted(nextMuted);
|
||||
|
||||
if (audio.current) {
|
||||
audio.current.muted = nextMuted;
|
||||
}
|
||||
};
|
||||
|
||||
const handleVolumeMouseDown: React.MouseEventHandler = e => {
|
||||
document.addEventListener('mousemove', handleMouseVolSlide, true);
|
||||
document.addEventListener('mouseup', handleVolumeMouseUp, true);
|
||||
document.addEventListener('touchmove', handleMouseVolSlide, true);
|
||||
document.addEventListener('touchend', handleVolumeMouseUp, true);
|
||||
|
||||
handleMouseVolSlide(e);
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
|
||||
const handleVolumeMouseUp = () => {
|
||||
document.removeEventListener('mousemove', handleMouseVolSlide, true);
|
||||
document.removeEventListener('mouseup', handleVolumeMouseUp, true);
|
||||
document.removeEventListener('touchmove', handleMouseVolSlide, true);
|
||||
document.removeEventListener('touchend', handleVolumeMouseUp, true);
|
||||
};
|
||||
|
||||
const handleMouseDown: React.MouseEventHandler = e => {
|
||||
document.addEventListener('mousemove', handleMouseMove, true);
|
||||
document.addEventListener('mouseup', handleMouseUp, true);
|
||||
document.addEventListener('touchmove', handleMouseMove, true);
|
||||
document.addEventListener('touchend', handleMouseUp, true);
|
||||
|
||||
setDragging(true);
|
||||
audio.current?.pause();
|
||||
handleMouseMove(e);
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
document.removeEventListener('mousemove', handleMouseMove, true);
|
||||
document.removeEventListener('mouseup', handleMouseUp, true);
|
||||
document.removeEventListener('touchmove', handleMouseMove, true);
|
||||
document.removeEventListener('touchend', handleMouseUp, true);
|
||||
|
||||
setDragging(false);
|
||||
audio.current?.play();
|
||||
};
|
||||
|
||||
const handleMouseMove = throttle((e) => {
|
||||
if (audio.current && seek.current) {
|
||||
const { x } = getPointerPosition(seek.current, e);
|
||||
const currentTime = audio.current.duration * x;
|
||||
|
||||
if (!isNaN(currentTime)) {
|
||||
setCurrentTime(currentTime);
|
||||
audio.current.currentTime = currentTime;
|
||||
}
|
||||
}
|
||||
}, 15);
|
||||
|
||||
const handleTimeUpdate = () => {
|
||||
if (audio.current) {
|
||||
setCurrentTime(audio.current.currentTime);
|
||||
setDuration(audio.current.duration);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseVolSlide = throttle(e => {
|
||||
if (audio.current && slider.current) {
|
||||
const { x } = getPointerPosition(slider.current, e);
|
||||
|
||||
if (!isNaN(x)) {
|
||||
setVolume(x);
|
||||
audio.current.volume = x;
|
||||
}
|
||||
}
|
||||
}, 15);
|
||||
|
||||
const handleScroll = throttle(() => {
|
||||
if (!canvas.current || !audio.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { top, height } = canvas.current.getBoundingClientRect();
|
||||
const inView = (top <= (window.innerHeight || document.documentElement.clientHeight)) && (top + height >= 0);
|
||||
|
||||
if (!paused && !inView) {
|
||||
audio.current.pause();
|
||||
|
||||
if (deployPictureInPicture) {
|
||||
deployPictureInPicture('audio', _pack());
|
||||
}
|
||||
|
||||
setPaused(true);
|
||||
}
|
||||
}, 150, { trailing: true });
|
||||
|
||||
const handleMouseEnter = () => {
|
||||
setHovered(true);
|
||||
};
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
setHovered(false);
|
||||
};
|
||||
|
||||
const handleLoadedData = () => {
|
||||
if (audio.current) {
|
||||
setDuration(audio.current.duration);
|
||||
|
||||
if (currentTime) {
|
||||
audio.current.currentTime = currentTime;
|
||||
}
|
||||
|
||||
if (volume !== undefined) {
|
||||
audio.current.volume = volume;
|
||||
}
|
||||
|
||||
if (muted !== undefined) {
|
||||
audio.current.muted = muted;
|
||||
}
|
||||
|
||||
if (autoPlay) {
|
||||
togglePlay();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const _initAudioContext = () => {
|
||||
if (audio.current) {
|
||||
// @ts-ignore
|
||||
// eslint-disable-next-line compat/compat
|
||||
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
||||
const context = new AudioContext();
|
||||
const source = context.createMediaElementSource(audio.current);
|
||||
|
||||
visualizer.current.setAudioContext(context, source);
|
||||
source.connect(context.destination);
|
||||
|
||||
audioContext.current = context;
|
||||
}
|
||||
};
|
||||
|
||||
const _renderCanvas = () => {
|
||||
requestAnimationFrame(() => {
|
||||
if (!audio.current) return;
|
||||
|
||||
handleTimeUpdate();
|
||||
_clear();
|
||||
_draw();
|
||||
|
||||
if (!paused) {
|
||||
_renderCanvas();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const _clear = () => {
|
||||
visualizer.current?.clear(width || 0, height || 0);
|
||||
};
|
||||
|
||||
const _draw = () => {
|
||||
visualizer.current?.draw(_getCX(), _getCY(), _getAccentColor(), _getRadius(), _getScaleCoefficient());
|
||||
};
|
||||
|
||||
const _getRadius = (): number => {
|
||||
return ((height || props.height || 0) - (PADDING * _getScaleCoefficient()) * 2) / 2;
|
||||
};
|
||||
|
||||
const _getScaleCoefficient = (): number => {
|
||||
return (height || props.height || 0) / 982;
|
||||
};
|
||||
|
||||
const _getCX = (): number => {
|
||||
return Math.floor((width || 0) / 2);
|
||||
};
|
||||
|
||||
const _getCY = (): number => {
|
||||
return Math.floor(_getRadius() + (PADDING * _getScaleCoefficient()));
|
||||
};
|
||||
|
||||
const _getAccentColor = (): string => {
|
||||
return accentColor || '#ffffff';
|
||||
};
|
||||
|
||||
const _getBackgroundColor = (): string => {
|
||||
return backgroundColor || '#000000';
|
||||
};
|
||||
|
||||
const _getForegroundColor = (): string => {
|
||||
return foregroundColor || '#ffffff';
|
||||
};
|
||||
|
||||
const seekBy = (time: number) => {
|
||||
if (audio.current) {
|
||||
const currentTime = audio.current.currentTime + time;
|
||||
|
||||
if (!isNaN(currentTime)) {
|
||||
setCurrentTime(currentTime);
|
||||
audio.current.currentTime = currentTime;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleAudioKeyDown: React.KeyboardEventHandler = e => {
|
||||
// On the audio element or the seek bar, we can safely use the space bar
|
||||
// for playback control because there are no buttons to press
|
||||
|
||||
if (e.key === ' ') {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
togglePlay();
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown: React.KeyboardEventHandler = e => {
|
||||
switch (e.key) {
|
||||
case 'k':
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
togglePlay();
|
||||
break;
|
||||
case 'm':
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
toggleMute();
|
||||
break;
|
||||
case 'j':
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
seekBy(-10);
|
||||
break;
|
||||
case 'l':
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
seekBy(10);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const getDuration = () => duration || props.duration || 0;
|
||||
|
||||
const progress = Math.min((currentTime / getDuration()) * 100, 100);
|
||||
|
||||
useEffect(() => {
|
||||
if (player.current) {
|
||||
_setDimensions();
|
||||
}
|
||||
}, [player.current]);
|
||||
|
||||
useEffect(() => {
|
||||
if (audio.current) {
|
||||
setVolume(audio.current.volume);
|
||||
setMuted(audio.current.muted);
|
||||
}
|
||||
}, [audio.current]);
|
||||
|
||||
useEffect(() => {
|
||||
if (canvas.current && visualizer.current) {
|
||||
visualizer.current.setCanvas(canvas.current);
|
||||
}
|
||||
}, [canvas.current, visualizer.current]);
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener('scroll', handleScroll);
|
||||
window.addEventListener('resize', handleResize, { passive: true });
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('scroll', handleScroll);
|
||||
window.removeEventListener('resize', handleResize);
|
||||
|
||||
if (!paused && audio.current && deployPictureInPicture) {
|
||||
deployPictureInPicture('audio', _pack());
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
_clear();
|
||||
_draw();
|
||||
}, [src, width, height, accentColor]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames('audio-player', { editable })}
|
||||
ref={player}
|
||||
style={{
|
||||
backgroundColor: _getBackgroundColor(),
|
||||
color: _getForegroundColor(),
|
||||
width: '100%',
|
||||
height: fullscreen ? '100%' : (height || props.height),
|
||||
}}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
tabIndex={0}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
<audio
|
||||
src={src}
|
||||
ref={audio}
|
||||
preload='auto'
|
||||
onPlay={handlePlay}
|
||||
onPause={handlePause}
|
||||
onProgress={handleProgress}
|
||||
onLoadedData={handleLoadedData}
|
||||
crossOrigin='anonymous'
|
||||
/>
|
||||
|
||||
<canvas
|
||||
role='button'
|
||||
tabIndex={0}
|
||||
className='audio-player__canvas'
|
||||
width={width}
|
||||
height={height}
|
||||
style={{ width: '100%', position: 'absolute', top: 0, left: 0 }}
|
||||
ref={canvas}
|
||||
onClick={togglePlay}
|
||||
onKeyDown={handleAudioKeyDown}
|
||||
title={alt}
|
||||
aria-label={alt}
|
||||
/>
|
||||
|
||||
{poster && (
|
||||
<img
|
||||
src={poster}
|
||||
alt=''
|
||||
width={(_getRadius() - TICK_SIZE) * 2}
|
||||
height={(_getRadius() - TICK_SIZE) * 2}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: _getCX(),
|
||||
top: _getCY(),
|
||||
transform: 'translate(-50%, -50%)',
|
||||
borderRadius: '50%',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className='video-player__seek' onMouseDown={handleMouseDown} ref={seek}>
|
||||
|
||||
<div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} />
|
||||
|
||||
<div
|
||||
className='video-player__seek__progress'
|
||||
style={{ width: `${progress}%`, backgroundColor: _getAccentColor() }}
|
||||
/>
|
||||
|
||||
<span
|
||||
className={classNames('video-player__seek__handle', { active: dragging })}
|
||||
tabIndex={0}
|
||||
style={{ left: `${progress}%`, backgroundColor: _getAccentColor() }}
|
||||
onKeyDown={handleAudioKeyDown}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='video-player__controls active'>
|
||||
<div className='video-player__buttons-bar'>
|
||||
<div className='video-player__buttons left'>
|
||||
|
||||
<button
|
||||
type='button'
|
||||
title={intl.formatMessage(paused ? messages.play : messages.pause)}
|
||||
aria-label={intl.formatMessage(paused ? messages.play : messages.pause)}
|
||||
className='player-button'
|
||||
onClick={togglePlay}
|
||||
>
|
||||
<Icon src={paused ? require('@tabler/icons/player-play.svg') : require('@tabler/icons/player-pause.svg')} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type='button'
|
||||
title={intl.formatMessage(muted ? messages.unmute : messages.mute)}
|
||||
aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)}
|
||||
className='player-button'
|
||||
onClick={toggleMute}
|
||||
>
|
||||
<Icon src={muted ? require('@tabler/icons/volume-3.svg') : require('@tabler/icons/volume.svg')} />
|
||||
</button>
|
||||
|
||||
<div
|
||||
className={classNames('video-player__volume', { active: hovered })}
|
||||
ref={slider}
|
||||
onMouseDown={handleVolumeMouseDown}
|
||||
>
|
||||
<div
|
||||
className='video-player__volume__current'
|
||||
style={{
|
||||
width: `${volume * 100}%`,
|
||||
backgroundColor: _getAccentColor(),
|
||||
}}
|
||||
/>
|
||||
|
||||
<span
|
||||
className='video-player__volume__handle'
|
||||
tabIndex={0}
|
||||
style={{ left: `${volume * 100}%`, backgroundColor: _getAccentColor() }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span className='video-player__time'>
|
||||
<span className='video-player__time-current'>{formatTime(Math.floor(currentTime))}</span>
|
||||
{getDuration() && (<>
|
||||
<span className='video-player__time-sep'>/</span>
|
||||
<span className='video-player__time-total'>{formatTime(Math.floor(getDuration()))}</span>
|
||||
</>)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className='video-player__buttons right'>
|
||||
<a
|
||||
title={intl.formatMessage(messages.download)}
|
||||
aria-label={intl.formatMessage(messages.download)}
|
||||
className='video-player__download__icon player-button'
|
||||
href={src}
|
||||
download
|
||||
target='_blank'
|
||||
>
|
||||
<Icon src={require('@tabler/icons/download.svg')} />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Audio;
|
@ -0,0 +1,115 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { FormattedMessage } from 'react-intl';
|
||||
|
||||
import { connectHashtagStream } from 'soapbox/actions/streaming';
|
||||
import { expandHashtagTimeline, clearTimeline } from 'soapbox/actions/timelines';
|
||||
import ColumnHeader from 'soapbox/components/column_header';
|
||||
import { Column } from 'soapbox/components/ui';
|
||||
import Timeline from 'soapbox/features/ui/components/timeline';
|
||||
import { useAppDispatch, useAppSelector } from 'soapbox/hooks';
|
||||
|
||||
import type { Tag as TagEntity } from 'soapbox/types/entities';
|
||||
|
||||
type Mode = 'any' | 'all' | 'none';
|
||||
|
||||
type Tag = { value: string };
|
||||
type Tags = { [k in Mode]: Tag[] };
|
||||
|
||||
interface IHashtagTimeline {
|
||||
params?: {
|
||||
id?: string,
|
||||
tags?: Tags,
|
||||
},
|
||||
}
|
||||
|
||||
export const HashtagTimeline: React.FC<IHashtagTimeline> = ({ params }) => {
|
||||
const id = params?.id || '';
|
||||
const tags = params?.tags || { any: [], all: [], none: [] };
|
||||
|
||||
const dispatch = useAppDispatch();
|
||||
const hasUnread = useAppSelector<boolean>(state => (state.timelines.getIn([`hashtag:${id}`, 'unread']) as number) > 0);
|
||||
const disconnects = useRef<(() => void)[]>([]);
|
||||
|
||||
// Mastodon supports displaying results from multiple hashtags.
|
||||
// https://github.com/mastodon/mastodon/issues/6359
|
||||
const title = () => {
|
||||
const title: React.ReactNode[] = [`#${id}`];
|
||||
|
||||
if (additionalFor('any')) {
|
||||
title.push(' ', <FormattedMessage key='any' id='hashtag.column_header.tag_mode.any' values={{ additional: additionalFor('any') }} defaultMessage='or {additional}' />);
|
||||
}
|
||||
|
||||
if (additionalFor('all')) {
|
||||
title.push(' ', <FormattedMessage key='all' id='hashtag.column_header.tag_mode.all' values={{ additional: additionalFor('all') }} defaultMessage='and {additional}' />);
|
||||
}
|
||||
|
||||
if (additionalFor('none')) {
|
||||
title.push(' ', <FormattedMessage key='none' id='hashtag.column_header.tag_mode.none' values={{ additional: additionalFor('none') }} defaultMessage='without {additional}' />);
|
||||
}
|
||||
|
||||
return title;
|
||||
};
|
||||
|
||||
const additionalFor = (mode: Mode) => {
|
||||
if (tags && (tags[mode] || []).length > 0) {
|
||||
return tags[mode].map(tag => tag.value).join('/');
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
const subscribe = () => {
|
||||
const any = tags.any.map(tag => tag.value);
|
||||
const all = tags.all.map(tag => tag.value);
|
||||
const none = tags.none.map(tag => tag.value);
|
||||
|
||||
[id, ...any].map(tag => {
|
||||
disconnects.current.push(dispatch(connectHashtagStream(id, tag, status => {
|
||||
const tags = status.tags.map((tag: TagEntity) => tag.name);
|
||||
|
||||
return all.filter(tag => tags.includes(tag)).length === all.length &&
|
||||
none.filter(tag => tags.includes(tag)).length === 0;
|
||||
})));
|
||||
});
|
||||
};
|
||||
|
||||
const unsubscribe = () => {
|
||||
disconnects.current.map(disconnect => disconnect());
|
||||
disconnects.current = [];
|
||||
};
|
||||
|
||||
const handleLoadMore = (maxId: string) => {
|
||||
dispatch(expandHashtagTimeline(id, { maxId, tags }));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
subscribe();
|
||||
dispatch(expandHashtagTimeline(id, { tags }));
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
unsubscribe();
|
||||
subscribe();
|
||||
dispatch(clearTimeline(`hashtag:${id}`));
|
||||
dispatch(expandHashtagTimeline(id, { tags }));
|
||||
}, [id, tags]);
|
||||
|
||||
return (
|
||||
<Column label={`#${id}`} transparent withHeader={false}>
|
||||
<ColumnHeader active={hasUnread} title={title()} />
|
||||
<Timeline
|
||||
scrollKey='hashtag_timeline'
|
||||
timelineId={`hashtag:${id}`}
|
||||
onLoadMore={handleLoadMore}
|
||||
emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />}
|
||||
divideType='space'
|
||||
/>
|
||||
</Column>
|
||||
);
|
||||
};
|
||||
|
||||
export default HashtagTimeline;
|
@ -1,128 +0,0 @@
|
||||
import isEqual from 'lodash/isEqual';
|
||||
import PropTypes from 'prop-types';
|
||||
import React from 'react';
|
||||
import { FormattedMessage } from 'react-intl';
|
||||
import { connect } from 'react-redux';
|
||||
|
||||
import { connectHashtagStream } from '../../actions/streaming';
|
||||
import { expandHashtagTimeline, clearTimeline } from '../../actions/timelines';
|
||||
import ColumnHeader from '../../components/column_header';
|
||||
import { Column } from '../../components/ui';
|
||||
import Timeline from '../ui/components/timeline';
|
||||
|
||||
const mapStateToProps = (state, props) => ({
|
||||
hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}`, 'unread']) > 0,
|
||||
});
|
||||
|
||||
export default @connect(mapStateToProps)
|
||||
class HashtagTimeline extends React.PureComponent {
|
||||
|
||||
disconnects = [];
|
||||
|
||||
static propTypes = {
|
||||
params: PropTypes.object.isRequired,
|
||||
dispatch: PropTypes.func.isRequired,
|
||||
hasUnread: PropTypes.bool,
|
||||
};
|
||||
|
||||
title = () => {
|
||||
const title = [`#${this.props.params.id}`];
|
||||
|
||||
// TODO: wtf is all this?
|
||||
// It exists in Mastodon's codebase, but undocumented
|
||||
if (this.additionalFor('any')) {
|
||||
title.push(' ', <FormattedMessage key='any' id='hashtag.column_header.tag_mode.any' values={{ additional: this.additionalFor('any') }} defaultMessage='or {additional}' />);
|
||||
}
|
||||
|
||||
if (this.additionalFor('all')) {
|
||||
title.push(' ', <FormattedMessage key='all' id='hashtag.column_header.tag_mode.all' values={{ additional: this.additionalFor('all') }} defaultMessage='and {additional}' />);
|
||||
}
|
||||
|
||||
if (this.additionalFor('none')) {
|
||||
title.push(' ', <FormattedMessage key='none' id='hashtag.column_header.tag_mode.none' values={{ additional: this.additionalFor('none') }} defaultMessage='without {additional}' />);
|
||||
}
|
||||
|
||||
return title;
|
||||
}
|
||||
|
||||
// TODO: wtf is this?
|
||||
// It exists in Mastodon's codebase, but undocumented
|
||||
additionalFor = (mode) => {
|
||||
const { tags } = this.props.params;
|
||||
|
||||
if (tags && (tags[mode] || []).length > 0) {
|
||||
return tags[mode].map(tag => tag.value).join('/');
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
_subscribe(dispatch, id, tags = {}) {
|
||||
const any = (tags.any || []).map(tag => tag.value);
|
||||
const all = (tags.all || []).map(tag => tag.value);
|
||||
const none = (tags.none || []).map(tag => tag.value);
|
||||
|
||||
[id, ...any].map(tag => {
|
||||
this.disconnects.push(dispatch(connectHashtagStream(id, tag, status => {
|
||||
const tags = status.tags.map(tag => tag.name);
|
||||
|
||||
return all.filter(tag => tags.includes(tag)).length === all.length &&
|
||||
none.filter(tag => tags.includes(tag)).length === 0;
|
||||
})));
|
||||
});
|
||||
}
|
||||
|
||||
_unsubscribe() {
|
||||
this.disconnects.map(disconnect => disconnect());
|
||||
this.disconnects = [];
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
const { dispatch } = this.props;
|
||||
const { id, tags } = this.props.params;
|
||||
|
||||
this._subscribe(dispatch, id, tags);
|
||||
dispatch(expandHashtagTimeline(id, { tags }));
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
const { dispatch } = this.props;
|
||||
const { id, tags } = this.props.params;
|
||||
const { id: prevId, tags: prevTags } = prevProps.params;
|
||||
|
||||
if (id !== prevId || !isEqual(tags, prevTags)) {
|
||||
this._unsubscribe();
|
||||
this._subscribe(dispatch, id, tags);
|
||||
dispatch(clearTimeline(`hashtag:${id}`));
|
||||
dispatch(expandHashtagTimeline(id, { tags }));
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this._unsubscribe();
|
||||
}
|
||||
|
||||
handleLoadMore = maxId => {
|
||||
const { id, tags } = this.props.params;
|
||||
this.props.dispatch(expandHashtagTimeline(id, { maxId, tags }));
|
||||
}
|
||||
|
||||
render() {
|
||||
const { hasUnread } = this.props;
|
||||
const { id } = this.props.params;
|
||||
|
||||
return (
|
||||
<Column label={`#${id}`} transparent withHeader={false}>
|
||||
<ColumnHeader active={hasUnread} title={this.title()} />
|
||||
<Timeline
|
||||
scrollKey='hashtag_timeline'
|
||||
timelineId={`hashtag:${id}`}
|
||||
onLoadMore={this.handleLoadMore}
|
||||
emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />}
|
||||
divideType='space'
|
||||
/>
|
||||
</Column>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
@ -1,108 +0,0 @@
|
||||
import React from 'react';
|
||||
import ImmutablePureComponent from 'react-immutable-pure-component';
|
||||
import { injectIntl, FormattedMessage } from 'react-intl';
|
||||
import { connect } from 'react-redux';
|
||||
|
||||
import { fetchMobilePage } from 'soapbox/actions/mobile';
|
||||
import { getSettings } from 'soapbox/actions/settings';
|
||||
import { getSoapboxConfig } from 'soapbox/actions/soapbox';
|
||||
|
||||
import { languages } from '../preferences';
|
||||
|
||||
const mapStateToProps = state => ({
|
||||
locale: getSettings(state).get('locale'),
|
||||
mobilePages: getSoapboxConfig(state).get('mobilePages'),
|
||||
});
|
||||
|
||||
@connect(mapStateToProps)
|
||||
@injectIntl
|
||||
class MobilePage extends ImmutablePureComponent {
|
||||
|
||||
state = {
|
||||
pageHtml: '',
|
||||
locale: this.props.locale,
|
||||
}
|
||||
|
||||
loadPageHtml = () => {
|
||||
const { dispatch, match, mobilePages } = this.props;
|
||||
const { locale } = this.state;
|
||||
const { slug } = match.params;
|
||||
const page = mobilePages.get(slug || 'mobile');
|
||||
const fetchLocale = page && locale !== page.get('default') && page.get('locales').includes(locale);
|
||||
dispatch(fetchMobilePage(slug, fetchLocale && locale)).then(html => {
|
||||
this.setState({ pageHtml: html });
|
||||
}).catch(error => {
|
||||
// TODO: Better error handling. 404 page?
|
||||
this.setState({ pageHtml: '<h1>Page not found</h1>' });
|
||||
});
|
||||
}
|
||||
|
||||
setLocale = (locale) => () => {
|
||||
this.setState({ locale });
|
||||
};
|
||||
|
||||
componentDidMount() {
|
||||
this.loadPageHtml();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps, prevState) {
|
||||
const { locale, match, mobilePages } = this.props;
|
||||
const { locale: prevLocale, mobilePages: prevMobilePages } = prevProps;
|
||||
const { locale: stateLocale } = this.state;
|
||||
const { locale: prevStateLocale } = prevState;
|
||||
|
||||
const { slug } = match.params;
|
||||
const { slug: prevSlug } = prevProps.match.params;
|
||||
|
||||
if (locale !== prevLocale) this.setState({ locale });
|
||||
|
||||
if (
|
||||
slug !== prevSlug ||
|
||||
stateLocale !== prevStateLocale ||
|
||||
(!prevMobilePages.get(slug || 'mobile') && mobilePages.get(slug || 'mobile'))
|
||||
)
|
||||
this.loadPageHtml();
|
||||
}
|
||||
|
||||
render() {
|
||||
const { match, mobilePages } = this.props;
|
||||
const { slug } = match.params;
|
||||
|
||||
const page = mobilePages.get(slug || 'mobile');
|
||||
const defaultLocale = page && page.get('default');
|
||||
const alsoAvailable = page && (
|
||||
<div className='rich-formatting also-available'>
|
||||
<FormattedMessage id='mobile.also_available' defaultMessage='Available in:' />
|
||||
{' '}
|
||||
<ul>
|
||||
<li>
|
||||
<a href='#' onClick={this.setLocale(defaultLocale)}>
|
||||
{languages[defaultLocale] || defaultLocale}
|
||||
</a>
|
||||
</li>
|
||||
{
|
||||
page.get('locales').map(locale => (
|
||||
<li key={locale}>
|
||||
<a href='#' onClick={this.setLocale(locale)}>
|
||||
{languages[locale] || locale}
|
||||
</a>
|
||||
</li>
|
||||
))
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
dangerouslySetInnerHTML={{ __html: this.state.pageHtml }}
|
||||
/>
|
||||
{alsoAvailable}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default MobilePage;
|
@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
|
||||
import { Stack } from 'soapbox/components/ui';
|
||||
|
||||
import { randomIntFromInterval, generateText } from '../utils';
|
||||
|
||||
export default ({ limit }: { limit: number }) => {
|
||||
const trend = randomIntFromInterval(6, 3);
|
||||
const stat = randomIntFromInterval(10, 3);
|
||||
|
||||
return (
|
||||
<>
|
||||
{new Array(limit).fill(undefined).map((_, idx) => (
|
||||
<Stack key={idx} className='animate-pulse text-primary-200 dark:text-primary-700'>
|
||||
<p>{generateText(trend)}</p>
|
||||
<p>{generateText(stat)}</p>
|
||||
</Stack>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
};
|
@ -0,0 +1,300 @@
|
||||
import classNames from 'clsx';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { defineMessages, useIntl, FormattedMessage } from 'react-intl';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import ReactSwipeableViews from 'react-swipeable-views';
|
||||
|
||||
import ExtendedVideoPlayer from 'soapbox/components/extended_video_player';
|
||||
import Icon from 'soapbox/components/icon';
|
||||
import IconButton from 'soapbox/components/icon_button';
|
||||
import Audio from 'soapbox/features/audio';
|
||||
import Video from 'soapbox/features/video';
|
||||
|
||||
import ImageLoader from './image-loader';
|
||||
|
||||
import type { List as ImmutableList } from 'immutable';
|
||||
import type { Account, Attachment, Status } from 'soapbox/types/entities';
|
||||
|
||||
const messages = defineMessages({
|
||||
close: { id: 'lightbox.close', defaultMessage: 'Close' },
|
||||
previous: { id: 'lightbox.previous', defaultMessage: 'Previous' },
|
||||
next: { id: 'lightbox.next', defaultMessage: 'Next' },
|
||||
});
|
||||
|
||||
interface IMediaModal {
|
||||
media: ImmutableList<Attachment>,
|
||||
status?: Status,
|
||||
account: Account,
|
||||
index: number,
|
||||
time?: number,
|
||||
onClose: () => void,
|
||||
}
|
||||
|
||||
const MediaModal: React.FC<IMediaModal> = (props) => {
|
||||
const {
|
||||
media,
|
||||
status,
|
||||
account,
|
||||
onClose,
|
||||
time = 0,
|
||||
} = props;
|
||||
|
||||
const intl = useIntl();
|
||||
const history = useHistory();
|
||||
|
||||
const [index, setIndex] = useState<number | null>(null);
|
||||
const [navigationHidden, setNavigationHidden] = useState(false);
|
||||
|
||||
const handleSwipe = (index: number) => {
|
||||
setIndex(index % media.size);
|
||||
};
|
||||
|
||||
const handleNextClick = () => {
|
||||
setIndex((getIndex() + 1) % media.size);
|
||||
};
|
||||
|
||||
const handlePrevClick = () => {
|
||||
setIndex((media.size + getIndex() - 1) % media.size);
|
||||
};
|
||||
|
||||
const handleChangeIndex: React.MouseEventHandler<HTMLButtonElement> = (e) => {
|
||||
const index = Number(e.currentTarget.getAttribute('data-index'));
|
||||
setIndex(index % media.size);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
switch (e.key) {
|
||||
case 'ArrowLeft':
|
||||
handlePrevClick();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
handleNextClick();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener('keydown', handleKeyDown, false);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const getIndex = () => {
|
||||
return index !== null ? index : props.index;
|
||||
};
|
||||
|
||||
const toggleNavigation = () => {
|
||||
setNavigationHidden(!navigationHidden);
|
||||
};
|
||||
|
||||
const handleStatusClick: React.MouseEventHandler = e => {
|
||||
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
history.push(`/@${account.acct}/posts/${status?.id}`);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
const handleCloserClick: React.MouseEventHandler = ({ target }) => {
|
||||
const whitelist = ['zoomable-image'];
|
||||
const activeSlide = document.querySelector('.media-modal .react-swipeable-view-container > div[aria-hidden="false"]');
|
||||
|
||||
const isClickOutside = target === activeSlide || !activeSlide?.contains(target as Element);
|
||||
const isWhitelisted = whitelist.some(w => (target as Element).classList.contains(w));
|
||||
|
||||
if (isClickOutside || isWhitelisted) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
let pagination: React.ReactNode[] = [];
|
||||
|
||||
const leftNav = media.size > 1 && (
|
||||
<button
|
||||
tabIndex={0}
|
||||
className='media-modal__nav media-modal__nav--left'
|
||||
onClick={handlePrevClick}
|
||||
aria-label={intl.formatMessage(messages.previous)}
|
||||
>
|
||||
<Icon src={require('@tabler/icons/arrow-left.svg')} />
|
||||
</button>
|
||||
);
|
||||
|
||||
const rightNav = media.size > 1 && (
|
||||
<button
|
||||
tabIndex={0}
|
||||
className='media-modal__nav media-modal__nav--right'
|
||||
onClick={handleNextClick}
|
||||
aria-label={intl.formatMessage(messages.next)}
|
||||
>
|
||||
<Icon src={require('@tabler/icons/arrow-right.svg')} />
|
||||
</button>
|
||||
);
|
||||
|
||||
if (media.size > 1) {
|
||||
pagination = media.toArray().map((item, i) => {
|
||||
const classes = ['media-modal__button'];
|
||||
if (i === getIndex()) {
|
||||
classes.push('media-modal__button--active');
|
||||
}
|
||||
return (
|
||||
<li className='media-modal__page-dot' key={i}>
|
||||
<button
|
||||
tabIndex={0}
|
||||
className={classes.join(' ')}
|
||||
onClick={handleChangeIndex}
|
||||
data-index={i}
|
||||
>
|
||||
{i + 1}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const isMultiMedia = media.map((image) => {
|
||||
if (image.type !== 'image') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}).toArray();
|
||||
|
||||
const content = media.map(attachment => {
|
||||
const width = (attachment.meta.getIn(['original', 'width']) || undefined) as number | undefined;
|
||||
const height = (attachment.meta.getIn(['original', 'height']) || undefined) as number | undefined;
|
||||
|
||||
const link = (status && account && (
|
||||
<a href={status.url} onClick={handleStatusClick}>
|
||||
<FormattedMessage id='lightbox.view_context' defaultMessage='View context' />
|
||||
</a>
|
||||
));
|
||||
|
||||
if (attachment.type === 'image') {
|
||||
return (
|
||||
<ImageLoader
|
||||
previewSrc={attachment.preview_url}
|
||||
src={attachment.url}
|
||||
width={width}
|
||||
height={height}
|
||||
alt={attachment.description}
|
||||
key={attachment.url}
|
||||
onClick={toggleNavigation}
|
||||
/>
|
||||
);
|
||||
} else if (attachment.type === 'video') {
|
||||
return (
|
||||
<Video
|
||||
preview={attachment.preview_url}
|
||||
blurhash={attachment.blurhash}
|
||||
src={attachment.url}
|
||||
width={width}
|
||||
height={height}
|
||||
startTime={time}
|
||||
onCloseVideo={onClose}
|
||||
detailed
|
||||
link={link}
|
||||
alt={attachment.description}
|
||||
key={attachment.url}
|
||||
/>
|
||||
);
|
||||
} else if (attachment.type === 'audio') {
|
||||
return (
|
||||
<Audio
|
||||
src={attachment.url}
|
||||
alt={attachment.description}
|
||||
poster={attachment.preview_url !== attachment.url ? attachment.preview_url : (status?.getIn(['account', 'avatar_static'])) as string | undefined}
|
||||
backgroundColor={attachment.meta.getIn(['colors', 'background']) as string | undefined}
|
||||
foregroundColor={attachment.meta.getIn(['colors', 'foreground']) as string | undefined}
|
||||
accentColor={attachment.meta.getIn(['colors', 'accent']) as string | undefined}
|
||||
duration={attachment.meta.getIn(['original', 'duration'], 0) as number | undefined}
|
||||
key={attachment.url}
|
||||
/>
|
||||
);
|
||||
} else if (attachment.type === 'gifv') {
|
||||
return (
|
||||
<ExtendedVideoPlayer
|
||||
src={attachment.url}
|
||||
muted
|
||||
controls={false}
|
||||
width={width}
|
||||
link={link}
|
||||
height={height}
|
||||
key={attachment.preview_url}
|
||||
alt={attachment.description}
|
||||
onClick={toggleNavigation}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}).toArray();
|
||||
|
||||
// you can't use 100vh, because the viewport height is taller
|
||||
// than the visible part of the document in some mobile
|
||||
// browsers when it's address bar is visible.
|
||||
// https://developers.google.com/web/updates/2016/12/url-bar-resizing
|
||||
const swipeableViewsStyle: React.CSSProperties = {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
};
|
||||
|
||||
const containerStyle: React.CSSProperties = {
|
||||
alignItems: 'center', // center vertically
|
||||
};
|
||||
|
||||
const navigationClassName = classNames('media-modal__navigation', {
|
||||
'media-modal__navigation--hidden': navigationHidden,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className='modal-root__modal media-modal'>
|
||||
<div
|
||||
className='media-modal__closer'
|
||||
role='presentation'
|
||||
onClick={handleCloserClick}
|
||||
>
|
||||
<ReactSwipeableViews
|
||||
style={swipeableViewsStyle}
|
||||
containerStyle={containerStyle}
|
||||
onChangeIndex={handleSwipe}
|
||||
index={getIndex()}
|
||||
>
|
||||
{content}
|
||||
</ReactSwipeableViews>
|
||||
</div>
|
||||
|
||||
<div className={navigationClassName}>
|
||||
<IconButton
|
||||
className='media-modal__close'
|
||||
title={intl.formatMessage(messages.close)}
|
||||
src={require('@tabler/icons/x.svg')}
|
||||
onClick={onClose}
|
||||
/>
|
||||
|
||||
{leftNav}
|
||||
{rightNav}
|
||||
|
||||
{(status && !isMultiMedia[getIndex()]) && (
|
||||
<div className={classNames('media-modal__meta', { 'media-modal__meta--shifted': media.size > 1 })}>
|
||||
<a href={status.url} onClick={handleStatusClick}>
|
||||
<FormattedMessage id='lightbox.view_context' defaultMessage='View context' />
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ul className='media-modal__pagination'>
|
||||
{pagination}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MediaModal;
|
@ -1,274 +0,0 @@
|
||||
import classNames from 'clsx';
|
||||
import PropTypes from 'prop-types';
|
||||
import React from 'react';
|
||||
import ImmutablePropTypes from 'react-immutable-proptypes';
|
||||
import ImmutablePureComponent from 'react-immutable-pure-component';
|
||||
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
|
||||
import { withRouter } from 'react-router-dom';
|
||||
import ReactSwipeableViews from 'react-swipeable-views';
|
||||
|
||||
import ExtendedVideoPlayer from 'soapbox/components/extended_video_player';
|
||||
import Icon from 'soapbox/components/icon';
|
||||
import IconButton from 'soapbox/components/icon_button';
|
||||
import Audio from 'soapbox/features/audio';
|
||||
import Video from 'soapbox/features/video';
|
||||
|
||||
import ImageLoader from './image_loader';
|
||||
|
||||
const messages = defineMessages({
|
||||
close: { id: 'lightbox.close', defaultMessage: 'Close' },
|
||||
previous: { id: 'lightbox.previous', defaultMessage: 'Previous' },
|
||||
next: { id: 'lightbox.next', defaultMessage: 'Next' },
|
||||
});
|
||||
|
||||
export default @injectIntl @withRouter
|
||||
class MediaModal extends ImmutablePureComponent {
|
||||
|
||||
static propTypes = {
|
||||
media: ImmutablePropTypes.list.isRequired,
|
||||
status: ImmutablePropTypes.record,
|
||||
account: ImmutablePropTypes.record,
|
||||
index: PropTypes.number.isRequired,
|
||||
onClose: PropTypes.func.isRequired,
|
||||
intl: PropTypes.object.isRequired,
|
||||
history: PropTypes.object,
|
||||
};
|
||||
|
||||
state = {
|
||||
index: null,
|
||||
navigationHidden: false,
|
||||
};
|
||||
|
||||
handleSwipe = (index) => {
|
||||
this.setState({ index: index % this.props.media.size });
|
||||
}
|
||||
|
||||
handleNextClick = () => {
|
||||
this.setState({ index: (this.getIndex() + 1) % this.props.media.size });
|
||||
}
|
||||
|
||||
handlePrevClick = () => {
|
||||
this.setState({ index: (this.props.media.size + this.getIndex() - 1) % this.props.media.size });
|
||||
}
|
||||
|
||||
handleChangeIndex = (e) => {
|
||||
const index = Number(e.currentTarget.getAttribute('data-index'));
|
||||
this.setState({ index: index % this.props.media.size });
|
||||
}
|
||||
|
||||
handleKeyDown = (e) => {
|
||||
switch (e.key) {
|
||||
case 'ArrowLeft':
|
||||
this.handlePrevClick();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
this.handleNextClick();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
window.addEventListener('keydown', this.handleKeyDown, false);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
window.removeEventListener('keydown', this.handleKeyDown);
|
||||
}
|
||||
|
||||
getIndex() {
|
||||
return this.state.index !== null ? this.state.index : this.props.index;
|
||||
}
|
||||
|
||||
toggleNavigation = () => {
|
||||
this.setState(prevState => ({
|
||||
navigationHidden: !prevState.navigationHidden,
|
||||
}));
|
||||
};
|
||||
|
||||
handleStatusClick = e => {
|
||||
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
const { status, account } = this.props;
|
||||
const acct = account.get('acct');
|
||||
const statusId = status.get('id');
|
||||
this.props.history.push(`/@${acct}/posts/${statusId}`);
|
||||
this.props.onClose(null, true);
|
||||
}
|
||||
}
|
||||
|
||||
handleCloserClick = ({ target }) => {
|
||||
const whitelist = ['zoomable-image'];
|
||||
const activeSlide = document.querySelector('.media-modal .react-swipeable-view-container > div[aria-hidden="false"]');
|
||||
|
||||
const isClickOutside = target === activeSlide || !activeSlide.contains(target);
|
||||
const isWhitelisted = whitelist.some(w => target.classList.contains(w));
|
||||
|
||||
if (isClickOutside || isWhitelisted) {
|
||||
this.props.onClose();
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const { media, status, account, intl, onClose } = this.props;
|
||||
const { navigationHidden } = this.state;
|
||||
|
||||
const index = this.getIndex();
|
||||
let pagination = [];
|
||||
|
||||
const leftNav = media.size > 1 && (
|
||||
<button tabIndex='0' className='media-modal__nav media-modal__nav--left' onClick={this.handlePrevClick} aria-label={intl.formatMessage(messages.previous)}>
|
||||
<Icon src={require('@tabler/icons/arrow-left.svg')} />
|
||||
</button>
|
||||
);
|
||||
|
||||
const rightNav = media.size > 1 && (
|
||||
<button tabIndex='0' className='media-modal__nav media-modal__nav--right' onClick={this.handleNextClick} aria-label={intl.formatMessage(messages.next)}>
|
||||
<Icon src={require('@tabler/icons/arrow-right.svg')} />
|
||||
</button>
|
||||
);
|
||||
|
||||
if (media.size > 1) {
|
||||
pagination = media.map((item, i) => {
|
||||
const classes = ['media-modal__button'];
|
||||
if (i === index) {
|
||||
classes.push('media-modal__button--active');
|
||||
}
|
||||
return (<li className='media-modal__page-dot' key={i}><button tabIndex='0' className={classes.join(' ')} onClick={this.handleChangeIndex} data-index={i}>{i + 1}</button></li>);
|
||||
});
|
||||
}
|
||||
|
||||
const isMultiMedia = media.map((image) => {
|
||||
if (image.get('type') !== 'image') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}).toArray();
|
||||
|
||||
const content = media.map(attachment => {
|
||||
const width = attachment.getIn(['meta', 'original', 'width']) || null;
|
||||
const height = attachment.getIn(['meta', 'original', 'height']) || null;
|
||||
const link = (status && account && <a href={status.get('url')} onClick={this.handleStatusClick}><FormattedMessage id='lightbox.view_context' defaultMessage='View context' /></a>);
|
||||
|
||||
if (attachment.get('type') === 'image') {
|
||||
return (
|
||||
<ImageLoader
|
||||
previewSrc={attachment.get('preview_url')}
|
||||
src={attachment.get('url')}
|
||||
width={width}
|
||||
height={height}
|
||||
alt={attachment.get('description')}
|
||||
key={attachment.get('url')}
|
||||
onClick={this.toggleNavigation}
|
||||
/>
|
||||
);
|
||||
} else if (attachment.get('type') === 'video') {
|
||||
const { time } = this.props;
|
||||
|
||||
return (
|
||||
<Video
|
||||
preview={attachment.get('preview_url')}
|
||||
blurhash={attachment.get('blurhash')}
|
||||
src={attachment.get('url')}
|
||||
width={attachment.get('width')}
|
||||
height={attachment.get('height')}
|
||||
startTime={time || 0}
|
||||
onCloseVideo={onClose}
|
||||
detailed
|
||||
link={link}
|
||||
alt={attachment.get('description')}
|
||||
key={attachment.get('url')}
|
||||
/>
|
||||
);
|
||||
} else if (attachment.get('type') === 'audio') {
|
||||
return (
|
||||
<Audio
|
||||
src={attachment.get('url')}
|
||||
alt={attachment.get('description')}
|
||||
poster={attachment.get('preview_url') !== attachment.get('url') ? attachment.get('preview_url') : (status && status.getIn(['account', 'avatar_static']))}
|
||||
backgroundColor={attachment.getIn(['meta', 'colors', 'background'])}
|
||||
foregroundColor={attachment.getIn(['meta', 'colors', 'foreground'])}
|
||||
accentColor={attachment.getIn(['meta', 'colors', 'accent'])}
|
||||
duration={attachment.getIn(['meta', 'original', 'duration'], 0)}
|
||||
key={attachment.get('url')}
|
||||
/>
|
||||
);
|
||||
} else if (attachment.get('type') === 'gifv') {
|
||||
return (
|
||||
<ExtendedVideoPlayer
|
||||
src={attachment.get('url')}
|
||||
muted
|
||||
controls={false}
|
||||
width={width}
|
||||
link={link}
|
||||
height={height}
|
||||
key={attachment.get('preview_url')}
|
||||
alt={attachment.get('description')}
|
||||
onClick={this.toggleNavigation}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}).toArray();
|
||||
|
||||
// you can't use 100vh, because the viewport height is taller
|
||||
// than the visible part of the document in some mobile
|
||||
// browsers when it's address bar is visible.
|
||||
// https://developers.google.com/web/updates/2016/12/url-bar-resizing
|
||||
const swipeableViewsStyle = {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
};
|
||||
|
||||
const containerStyle = {
|
||||
alignItems: 'center', // center vertically
|
||||
};
|
||||
|
||||
const navigationClassName = classNames('media-modal__navigation', {
|
||||
'media-modal__navigation--hidden': navigationHidden,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className='modal-root__modal media-modal'>
|
||||
<div
|
||||
className='media-modal__closer'
|
||||
role='presentation'
|
||||
onClick={this.handleCloserClick}
|
||||
>
|
||||
<ReactSwipeableViews
|
||||
style={swipeableViewsStyle}
|
||||
containerStyle={containerStyle}
|
||||
onChangeIndex={this.handleSwipe}
|
||||
onSwitching={this.handleSwitching}
|
||||
index={index}
|
||||
>
|
||||
{content}
|
||||
</ReactSwipeableViews>
|
||||
</div>
|
||||
|
||||
<div className={navigationClassName}>
|
||||
<IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} src={require('@tabler/icons/x.svg')} onClick={onClose} />
|
||||
|
||||
{leftNav}
|
||||
{rightNav}
|
||||
|
||||
{(status && !isMultiMedia[index]) && (
|
||||
<div className={classNames('media-modal__meta', { 'media-modal__meta--shifted': media.size > 1 })}>
|
||||
<a href={status.get('url')} onClick={this.handleStatusClick}><FormattedMessage id='lightbox.view_context' defaultMessage='View context' /></a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ul className='media-modal__pagination'>
|
||||
{pagination}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
@ -1,13 +1,22 @@
|
||||
require('dotenv').config();
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
import type { Configuration } from 'webpack';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const { NODE_ENV } = process.env;
|
||||
|
||||
let configuration: Configuration = {};
|
||||
|
||||
switch (NODE_ENV) {
|
||||
case 'development':
|
||||
case 'production':
|
||||
case 'test':
|
||||
module.exports = require(`./webpack/${NODE_ENV}`); break;
|
||||
configuration = require(`./webpack/${NODE_ENV}`).default;
|
||||
break;
|
||||
default:
|
||||
console.error('ERROR: NODE_ENV must be set to either `development`, `test`, or `production`.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
export default configuration;
|
@ -1,8 +0,0 @@
|
||||
const { resolve } = require('path');
|
||||
|
||||
// Forces recompile whenever the current commit changes
|
||||
// Useful for generating the version hash in the UI
|
||||
module.exports = function(source, map) {
|
||||
this.addDependency(resolve(__dirname, '../../.git/logs/HEAD'));
|
||||
this.callback(null, source, map);
|
||||
};
|
@ -0,0 +1,14 @@
|
||||
import { resolve } from 'path';
|
||||
|
||||
import type { LoaderContext } from 'webpack';
|
||||
|
||||
/**
|
||||
* Forces recompile whenever the current commit changes.
|
||||
* Useful for generating the version hash in the UI.
|
||||
*/
|
||||
function loader(this: LoaderContext<{}>, content: string) {
|
||||
this.addDependency(resolve(__dirname, '../../.git/logs/HEAD'));
|
||||
this.callback(undefined, content);
|
||||
}
|
||||
|
||||
export default loader;
|
@ -1,9 +0,0 @@
|
||||
const { resolve } = require('path');
|
||||
|
||||
// Recompile code.js whenever git changes
|
||||
module.exports = {
|
||||
test: resolve(__dirname, '../../app/soapbox/utils/code.js'),
|
||||
use: {
|
||||
loader: resolve(__dirname, '../loaders/git-loader.js'),
|
||||
},
|
||||
};
|
@ -0,0 +1,13 @@
|
||||
import { resolve } from 'path';
|
||||
|
||||
import type { RuleSetRule } from 'webpack';
|
||||
|
||||
/** Recompile code.js whenever git changes. */
|
||||
const rule: RuleSetRule = {
|
||||
test: resolve(__dirname, '../../app/soapbox/utils/code.js'),
|
||||
use: {
|
||||
loader: resolve(__dirname, '../loaders/git-loader.ts'),
|
||||
},
|
||||
};
|
||||
|
||||
export default rule;
|
@ -1,19 +0,0 @@
|
||||
const assets = require('./assets');
|
||||
const babel = require('./babel');
|
||||
const buildConfig = require('./babel-build-config');
|
||||
const git = require('./babel-git');
|
||||
const css = require('./css');
|
||||
const gitRefresh = require('./git-refresh');
|
||||
const nodeModules = require('./node_modules');
|
||||
|
||||
// Webpack loaders are processed in reverse order
|
||||
// https://webpack.js.org/concepts/loaders/#loader-features
|
||||
module.exports = [
|
||||
...assets,
|
||||
css,
|
||||
nodeModules,
|
||||
babel,
|
||||
git,
|
||||
gitRefresh,
|
||||
buildConfig,
|
||||
];
|
@ -0,0 +1,23 @@
|
||||
import assets from './assets';
|
||||
import babel from './babel';
|
||||
import buildConfig from './babel-build-config';
|
||||
import git from './babel-git';
|
||||
import css from './css';
|
||||
import gitRefresh from './git-refresh';
|
||||
import nodeModules from './node-modules';
|
||||
|
||||
import type { RuleSetRule } from 'webpack';
|
||||
|
||||
// Webpack loaders are processed in reverse order
|
||||
// https://webpack.js.org/concepts/loaders/#loader-features
|
||||
const rules: RuleSetRule[] = [
|
||||
...assets,
|
||||
css,
|
||||
nodeModules,
|
||||
babel,
|
||||
git,
|
||||
gitRefresh,
|
||||
buildConfig,
|
||||
];
|
||||
|
||||
export default rules;
|
@ -1,8 +0,0 @@
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = {};
|
||||
} else {
|
||||
module.exports = {
|
||||
test: /\.js$/,
|
||||
loader: 'mark-loader',
|
||||
};
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
import { env } from 'process';
|
||||
|
||||
import type { RuleSetRule } from 'webpack';
|
||||
|
||||
let rule: RuleSetRule = {};
|
||||
|
||||
if (env.NODE_ENV !== 'production') {
|
||||
rule = {
|
||||
test: /\.js$/,
|
||||
loader: 'mark-loader',
|
||||
};
|
||||
}
|
||||
|
||||
export default rule;
|
@ -1,10 +0,0 @@
|
||||
// Note: You must restart bin/webpack-dev-server for changes to take effect
|
||||
console.log('Running in test mode'); // eslint-disable-line no-console
|
||||
|
||||
const { merge } = require('webpack-merge');
|
||||
|
||||
const sharedConfig = require('./shared');
|
||||
|
||||
module.exports = merge(sharedConfig, {
|
||||
mode: 'development',
|
||||
});
|
@ -0,0 +1,14 @@
|
||||
// Note: You must restart bin/webpack-dev-server for changes to take effect
|
||||
console.log('Running in test mode'); // eslint-disable-line no-console
|
||||
|
||||
import { merge } from 'webpack-merge';
|
||||
|
||||
import sharedConfig from './shared';
|
||||
|
||||
import type { Configuration } from 'webpack';
|
||||
|
||||
const configuration: Configuration = {
|
||||
mode: 'development',
|
||||
};
|
||||
|
||||
export default merge<Configuration>(sharedConfig, configuration);
|
Loading…
Reference in new issue