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 = {
|
2018-08-02 02:53:38 +02:00
|
|
|
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;
|
|
|
|
|
2018-08-02 02:53:38 +02:00
|
|
|
// 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",
|
|
|
|
],
|
|
|
|
};
|
2018-08-02 02:53:38 +02:00
|
|
|
|
|
|
|
// Parse docx to html
|
2018-07-27 04:06:39 +02:00
|
|
|
mammoth
|
2018-08-02 02:53:38 +02:00
|
|
|
.convertToHtml({ path: source }, options)
|
2018-07-27 04:06:39 +02:00
|
|
|
.then(result => {
|
2018-08-02 02:53:38 +02:00
|
|
|
// Remove images and tables
|
2018-07-27 04:06:39 +02:00
|
|
|
const breakdance = new Breakdance({ omit: ['table', 'img'] });
|
2018-08-02 02:53:38 +02:00
|
|
|
// 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 => {
|
2018-08-02 02:53:38 +02:00
|
|
|
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.');
|
2018-08-02 02:53:38 +02:00
|
|
|
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 />}
|
2018-08-02 02:53:38 +02:00
|
|
|
{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;
|