Files
SCM-Manager/scm-ui/ui-webapp/src/repos/sources/components/content/SourcecodeViewer.tsx

92 lines
2.0 KiB
TypeScript
Raw Normal View History

import React from "react";
import { WithTranslation, withTranslation } from "react-i18next";
import { apiClient, ErrorNotification, Loading, SyntaxHighlighter } from "@scm-manager/ui-components";
import { File } from "@scm-manager/ui-types";
2018-10-15 16:45:54 +02:00
type Props = WithTranslation & {
file: File;
language: string;
2018-10-15 16:45:54 +02:00
};
type State = {
content: string;
error?: Error;
loaded: boolean;
currentFileRevision: string;
2018-10-15 16:45:54 +02:00
};
class SourcecodeViewer extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
content: "",
loaded: false,
currentFileRevision: ""
2018-10-15 16:45:54 +02:00
};
}
2018-10-29 11:50:55 +01:00
componentDidMount() {
const { file } = this.props;
const { currentFileRevision } = this.state;
if (file.revision !== currentFileRevision) {
this.fetchContent();
}
}
componentDidUpdate() {
const { file } = this.props;
const { currentFileRevision } = this.state;
if (file.revision !== currentFileRevision) {
this.fetchContent();
}
}
fetchContent = () => {
2018-10-29 11:50:55 +01:00
const { file } = this.props;
getContent(file._links.self.href)
.then(content => {
this.setState({
content,
loaded: true,
currentFileRevision: file.revision
});
2018-10-29 11:50:55 +01:00
})
.catch(error => {
this.setState({
error,
loaded: true
});
});
};
2018-10-15 16:45:54 +02:00
render() {
2018-11-01 10:59:04 +01:00
const { content, error, loaded } = this.state;
const language = this.props.language;
2018-10-29 11:50:55 +01:00
2018-11-01 10:59:04 +01:00
if (error) {
2018-10-29 11:50:55 +01:00
return <ErrorNotification error={error} />;
}
if (!loaded) {
return <Loading />;
}
if (!content) {
return null;
}
2019-10-21 10:57:56 +02:00
return <SyntaxHighlighter language={getLanguage(language)} value={content} />;
2018-10-15 16:45:54 +02:00
}
}
2018-10-29 14:53:24 +01:00
export function getLanguage(language: string) {
return language.toLowerCase();
}
2018-10-15 16:45:54 +02:00
export function getContent(url: string) {
return apiClient.get(url).then(response => response.text());
2018-10-15 16:45:54 +02:00
}
export default withTranslation("repos")(SourcecodeViewer);