session-desktop/ts/components/LightboxGallery.tsx

108 lines
2.5 KiB
TypeScript
Raw Normal View History

/**
* @prettier
*/
import React from 'react';
import * as MIME from '../types/MIME';
import { Lightbox } from './Lightbox';
2018-04-26 22:48:08 +02:00
import { Message } from './conversation/media-gallery/types/Message';
2019-01-14 22:49:58 +01:00
import { AttachmentType } from '../types/Attachment';
export interface MediaItemType {
2018-04-26 22:48:08 +02:00
objectURL?: string;
thumbnailObjectUrl?: string;
contentType?: MIME.MIMEType;
index: number;
attachment: AttachmentType;
message: Message;
}
interface Props {
close: () => void;
media: Array<MediaItemType>;
2020-05-29 08:25:15 +02:00
onSave?: (options: {
attachment: AttachmentType;
message: Message;
index: number;
}) => void;
selectedIndex: number;
}
interface State {
selectedIndex: number;
}
export class LightboxGallery extends React.Component<Props, State> {
public static defaultProps: Partial<Props> = {
selectedIndex: 0,
};
constructor(props: Props) {
super(props);
this.state = {
selectedIndex: this.props.selectedIndex,
};
}
public render() {
2020-10-19 06:23:35 +02:00
const { close, media, onSave } = this.props;
const { selectedIndex } = this.state;
const selectedMedia = media[selectedIndex];
const firstIndex = 0;
const lastIndex = media.length - 1;
const onPrevious =
selectedIndex > firstIndex ? this.handlePrevious : undefined;
const onNext = selectedIndex < lastIndex ? this.handleNext : undefined;
const objectURL = selectedMedia.objectURL || 'images/alert-outline.svg';
const { attachment } = selectedMedia;
2018-04-26 22:48:08 +02:00
2019-01-14 22:49:58 +01:00
const saveCallback = onSave ? this.handleSave : undefined;
const captionCallback = attachment ? attachment.caption : undefined;
return (
<Lightbox
close={close}
onPrevious={onPrevious}
onNext={onNext}
2019-01-14 22:49:58 +01:00
onSave={saveCallback}
2018-04-26 22:48:08 +02:00
objectURL={objectURL}
2019-01-14 22:49:58 +01:00
caption={captionCallback}
contentType={selectedMedia.contentType}
/>
);
}
2019-01-14 22:49:58 +01:00
private readonly handlePrevious = () => {
this.setState(prevState => ({
selectedIndex: Math.max(prevState.selectedIndex - 1, 0),
}));
};
2019-01-14 22:49:58 +01:00
private readonly handleNext = () => {
this.setState((prevState, props) => ({
selectedIndex: Math.min(
prevState.selectedIndex + 1,
props.media.length - 1
),
}));
};
2018-04-26 22:48:08 +02:00
2019-01-14 22:49:58 +01:00
private readonly handleSave = () => {
const { media, onSave } = this.props;
2018-04-26 22:48:08 +02:00
if (!onSave) {
return;
}
const { selectedIndex } = this.state;
const mediaItem = media[selectedIndex];
const { attachment, message, index } = mediaItem;
onSave({ attachment, message, index });
2018-04-26 22:48:08 +02:00
};
}