lbry-desktop/ui/component/viewers/documentViewer.jsx

105 lines
2.6 KiB
React
Raw Permalink Normal View History

// @flow
import React from 'react';
import LoadingScreen from 'component/common/loading-screen';
import MarkdownPreview from 'component/common/markdown-preview';
2019-11-07 20:39:22 +01:00
import CodeViewer from 'component/viewers/codeViewer';
import * as RENDER_MODES from 'constants/file_render_modes';
import * as https from 'https';
2019-03-27 05:40:02 +01:00
type Props = {
2018-07-28 03:42:35 +02:00
theme: string,
renderMode: string,
source: {
file: (?string) => any,
stream: string,
contentType: string,
},
stakedLevel?: number,
};
type State = {
error: boolean,
loading: boolean,
content: ?string,
};
class DocumentViewer extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
error: false,
loading: true,
content: null,
};
}
componentDidMount() {
const { source } = this.props;
// @if TARGET='app'
if (source && source.file) {
const stream = source.file('utf8');
let data = '';
2021-03-11 18:08:11 +01:00
stream.on('data', (chunk) => {
data += chunk;
});
stream.on('end', () => {
this.setState({ content: data, loading: false });
});
stream.on('error', () => {
this.setState({ error: true, loading: false });
});
}
// @endif
// @if TARGET='web'
if (source && source.stream) {
2021-03-11 18:08:11 +01:00
https.get(source.stream, (response) => {
if (response.statusCode === 200) {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
this.setState({ content: data, loading: false });
});
} else {
this.setState({ error: true, loading: false });
}
});
}
// @endif
}
renderDocument() {
const { content } = this.state;
const { source, theme, renderMode, stakedLevel } = this.props;
const { contentType } = source;
2018-07-27 02:24:00 +02:00
return renderMode === RENDER_MODES.MARKDOWN ? (
<MarkdownPreview content={content} isMarkdownPost promptLinks stakedLevel={stakedLevel} />
) : (
<CodeViewer value={content} contentType={contentType} theme={theme} />
);
}
render() {
const { error, loading, content } = this.state;
const isReady = content && !error;
2018-07-28 03:54:06 +02:00
const errorMessage = __("Sorry, looks like we can't load the document.");
return (
2020-04-14 01:48:11 +02:00
<div className="file-viewer file-viewer--document">
2020-01-06 19:32:35 +01:00
{loading && !error && <div className="placeholder--text-document" />}
{error && <LoadingScreen status={errorMessage} spinner={!error} />}
2019-11-07 20:39:22 +01:00
{isReady && this.renderDocument()}
</div>
);
}
}
export default DocumentViewer;