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

89 lines
1.8 KiB
TypeScript
Raw Normal View History

import React from "react";
import { translate } from "react-i18next";
import { apiClient, SyntaxHighlighter } from "@scm-manager/ui-components";
import { File } from "@scm-manager/ui-types";
import { ErrorNotification, Loading } from "@scm-manager/ui-components";
2018-10-15 16:45:54 +02:00
type Props = {
t: (p: string) => string;
file: File;
language: string;
2018-10-15 16:45:54 +02:00
};
type State = {
content: string;
error?: Error;
loaded: boolean;
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
2018-10-15 16:45:54 +02:00
};
}
2018-10-29 11:50:55 +01:00
componentDidMount() {
const { file } = this.props;
getContent(file._links.self.href)
.then(result => {
if (result.error) {
this.setState({
...this.state,
error: result.error,
loaded: true
2018-10-29 11:50:55 +01:00
});
} else {
this.setState({
...this.state,
content: result,
loaded: true
2018-10-29 11:50:55 +01:00
});
}
})
.catch(err => {});
}
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-29 14:53:24 +01:00
.then(response => {
return response;
2018-10-29 11:50:55 +01:00
})
2018-10-15 16:45:54 +02:00
.catch(err => {
return {
error: err
};
2018-10-15 16:45:54 +02:00
});
}
export default translate("repos")(SourcecodeViewer);