bigbuffet-rw/app/soapbox/features/compose/components/upload-button.tsx

88 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-05-30 11:26:24 -07:00
import React, { useRef } from 'react';
import { defineMessages, IntlShape, useIntl } from 'react-intl';
2022-05-30 11:26:24 -07:00
import { IconButton } from 'soapbox/components/ui';
2022-11-26 08:38:16 -08:00
import { useInstance } from 'soapbox/hooks';
2022-05-30 11:26:24 -07:00
import type { List as ImmutableList } from 'immutable';
const messages = defineMessages({
upload: { id: 'upload_button.label', defaultMessage: 'Add media attachment' },
});
const onlyImages = (types: ImmutableList<string>) => {
return Boolean(types && types.every(type => type.startsWith('image/')));
};
export interface IUploadButton {
2022-06-17 11:45:52 -07:00
disabled?: boolean,
unavailable?: boolean,
onSelectFile: (files: FileList, intl: IntlShape) => void,
2022-06-17 11:45:52 -07:00
style?: React.CSSProperties,
resetFileKey: number | null,
2022-12-06 14:33:53 -08:00
className?: string,
iconClassName?: string,
2022-05-30 11:26:24 -07:00
}
const UploadButton: React.FC<IUploadButton> = ({
2022-06-17 11:45:52 -07:00
disabled = false,
unavailable = false,
2022-05-30 11:26:24 -07:00
onSelectFile,
resetFileKey,
2022-12-06 14:33:53 -08:00
className = 'text-gray-600 hover:text-gray-700 dark:hover:text-gray-500',
iconClassName,
2022-05-30 11:26:24 -07:00
}) => {
const intl = useIntl();
2022-11-26 08:38:16 -08:00
const { configuration } = useInstance();
2022-05-30 11:26:24 -07:00
const fileElement = useRef<HTMLInputElement>(null);
2022-11-26 08:38:16 -08:00
const attachmentTypes = configuration.getIn(['media_attachments', 'supported_mime_types']) as ImmutableList<string>;
2022-05-30 11:26:24 -07:00
const handleChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
if (e.target.files?.length) {
onSelectFile(e.target.files, intl);
2022-05-30 11:26:24 -07:00
}
};
const handleClick = () => {
fileElement.current?.click();
};
if (unavailable) {
return null;
}
const src = onlyImages(attachmentTypes)
? require('@tabler/icons/photo.svg')
: require('@tabler/icons/paperclip.svg');
2022-05-30 11:26:24 -07:00
return (
<div>
<IconButton
src={src}
2022-12-06 14:33:53 -08:00
className={className}
iconClassName={iconClassName}
2022-05-30 11:26:24 -07:00
title={intl.formatMessage(messages.upload)}
disabled={disabled}
onClick={handleClick}
/>
<label>
<span className='sr-only'>{intl.formatMessage(messages.upload)}</span>
<input
key={resetFileKey}
ref={fileElement}
type='file'
multiple
accept={attachmentTypes && attachmentTypes.toArray().join(',')}
onChange={handleChange}
disabled={disabled}
className='hidden'
/>
</label>
</div>
);
};
export default UploadButton;