bigbuffet-rw/app/soapbox/features/ui/components/embed_modal.tsx

83 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-08-21 08:21:25 -07:00
import React, { useState, useEffect, useRef } from 'react';
2022-05-03 14:43:04 -07:00
import { FormattedMessage } from 'react-intl';
2022-08-21 08:21:25 -07:00
import api from 'soapbox/api';
2022-05-03 14:43:04 -07:00
import { Modal, Stack, Text, Input } from 'soapbox/components/ui';
2022-08-21 08:21:25 -07:00
import { useAppDispatch } from 'soapbox/hooks';
2022-05-03 14:43:04 -07:00
2022-08-21 08:21:25 -07:00
import type { RootState } from 'soapbox/store';
const fetchEmbed = (url: string) => {
return (dispatch: any, getState: () => RootState) => {
return api(getState).get('/api/oembed', { params: { url } });
};
};
2022-05-03 14:43:04 -07:00
interface IEmbedModal {
2022-08-21 08:21:25 -07:00
url: string,
onError: (error: any) => void,
2022-05-03 14:43:04 -07:00
}
2022-08-21 08:21:25 -07:00
const EmbedModal: React.FC<IEmbedModal> = ({ url, onError }) => {
const dispatch = useAppDispatch();
const iframe = useRef<HTMLIFrameElement>(null);
const [oembed, setOembed] = useState<any>(null);
useEffect(() => {
dispatch(fetchEmbed(url)).then(({ data }) => {
if (!iframe.current?.contentWindow) return;
setOembed(data);
const iframeDocument = iframe.current.contentWindow.document;
iframeDocument.open();
iframeDocument.write(data.html);
iframeDocument.close();
const innerFrame = iframeDocument.querySelector('iframe');
iframeDocument.body.style.margin = '0';
if (innerFrame) {
innerFrame.width = '100%';
}
}).catch(error => {
onError(error);
});
}, [!!iframe.current]);
2022-05-03 14:43:04 -07:00
const handleInputClick: React.MouseEventHandler<HTMLInputElement> = (e) => {
e.currentTarget.select();
};
return (
<Modal title={<FormattedMessage id='status.embed' defaultMessage='Embed' />}>
<Stack space={4}>
<Stack>
<Text theme='muted' size='sm'>
<FormattedMessage id='embed.instructions' defaultMessage='Embed this post on your website by copying the code below.' />
</Text>
<Input
type='text'
readOnly
2022-08-21 08:21:25 -07:00
value={oembed?.html || ''}
2022-05-03 14:43:04 -07:00
onClick={handleInputClick}
/>
</Stack>
2022-08-21 08:21:25 -07:00
<iframe
className='inline-flex rounded-xl overflow-hidden max-w-full'
frameBorder='0'
ref={iframe}
sandbox='allow-same-origin'
title='preview'
/>
2022-05-03 14:43:04 -07:00
</Stack>
</Modal>
);
};
2022-08-21 08:21:25 -07:00
export default EmbedModal;