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

90 lines
2.1 KiB
React
Raw Normal View History

// @flow
import React from 'react';
import LoadingScreen from 'component/common/loading-screen';
2018-07-27 02:24:00 +02:00
import CodeViewer from 'component/viewers/codeViewer';
import MarkdownPreview from 'component/common/markdown-preview';
type Props = {
2018-07-28 03:42:35 +02:00
theme: string,
source: {
stream: string => any,
fileType: string,
contentType: string,
},
};
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 (source && source.stream) {
const stream = source.stream('utf8');
let data = '';
stream.on('data', chunk => {
data += chunk;
});
stream.on('end', () => {
this.setState({ content: data, loading: false });
});
stream.on('error', () => {
this.setState({ error: true, loading: false });
});
}
}
renderDocument() {
2018-07-27 02:24:00 +02:00
let viewer = null;
const { content } = this.state;
2018-07-28 03:42:35 +02:00
const { source, theme } = this.props;
const { fileType, contentType } = source;
2018-07-27 02:24:00 +02:00
const markdownType = ['md', 'markdown'];
if (markdownType.includes(fileType)) {
2018-07-27 02:24:00 +02:00
// Render markdown
viewer = <MarkdownPreview content={content} promptLinks />;
} else {
2018-07-27 02:24:00 +02:00
// Render plain text
2018-07-28 03:42:35 +02:00
viewer = <CodeViewer value={content} contentType={contentType} theme={theme} />;
}
2018-07-27 02:24:00 +02:00
return viewer;
}
render() {
const { error, loading, content } = this.state;
const isReady = content && !error;
const loadingMessage = __('Rendering document.');
2018-07-28 03:54:06 +02:00
const errorMessage = __("Sorry, looks like we can't load the document.");
return (
2018-07-27 02:24:00 +02:00
<div className="file-render__viewer document-viewer">
{loading && !error && <LoadingScreen status={loadingMessage} spinner />}
{error && <LoadingScreen status={errorMessage} spinner={!error} />}
{isReady && this.renderDocument()}
</div>
);
}
}
export default DocumentViewer;