lbry-desktop/src/renderer/component/viewers/docxViewer.jsx

75 lines
2.1 KiB
React
Raw Normal View History

2018-07-27 04:06:39 +02:00
// @flow
import React from 'react';
import mammoth from 'mammoth';
import Breakdance from 'breakdance';
import LoadingScreen from 'component/common/loading-screen';
import MarkdownPreview from 'component/common/markdown-preview';
type Props = {
source: string,
2018-07-27 04:06:39 +02:00
};
class DocxViewer extends React.PureComponent<Props> {
constructor(props) {
super(props);
this.state = {
error: null,
content: null,
loading: true,
};
}
componentDidMount() {
const { source } = this.props;
// Overwrite element and styles
2018-07-27 04:06:39 +02:00
const options = {
styleMap: [
2018-07-28 03:54:06 +02:00
"p[style-name='Title'] => h1:fresh",
2018-07-27 04:06:39 +02:00
"p[style-name='Heading 1'] => h1:fresh",
"p[style-name='Heading 2'] => h2:fresh",
"p[style-name='Heading 3'] => h3:fresh",
"p[style-name='Section Title'] => h1:fresh",
"p[style-name='Subsection Title'] => h2:fresh",
"p[style-name='Aside Heading'] => div.aside > h2:fresh",
"p[style-name='Aside Text'] => div.aside > p:fresh",
],
};
// Parse docx to html
2018-07-27 04:06:39 +02:00
mammoth
.convertToHtml({ path: source }, options)
2018-07-27 04:06:39 +02:00
.then(result => {
// Remove images and tables
2018-07-27 04:06:39 +02:00
const breakdance = new Breakdance({ omit: ['table', 'img'] });
// Convert html to markdown
2018-07-27 04:06:39 +02:00
const markdown = breakdance.render(result.value);
this.setState({ content: markdown, loading: false });
})
.catch(error => {
this.setState({ error: true, loading: false });
2018-07-27 04:06:39 +02:00
})
.done();
}
render() {
const { content, error, loading } = this.state;
const loadingMessage = __('Rendering document.');
const errorMessage = __("Sorry, looks like we can't load the document.");
2018-07-27 04:06:39 +02:00
return (
<div className="document-viewer file-render__viewer">
{loading && <LoadingScreen status={loadingMessage} spinner />}
{error && <LoadingScreen status={errorMessage} spinner={false} />}
2018-07-27 04:06:39 +02:00
{content && (
<div className="document-viewer__content">
<MarkdownPreview content={content} promptLinks />
</div>
)}
</div>
);
}
}
export default DocxViewer;