import { h, Component } from 'preact'; import PropTypes from 'prop-types'; import marked from 'marked'; import { getJSONContents } from './actions'; export default class GithubRepo extends Component { constructor(props) { super(props); this.state = { root: true, directories: [], files: [], readme: null, content: null, token: props.githubToken, path: null, }; } componentDidMount() { if (this.state.token) { getJSONContents( `https://api.github.com/repos/${ this.props.resource.args }/contents?access_token=${this.state.token}`, this.loadContent, this.loadFailure, ); getJSONContents( `https://api.github.com/repos/${ this.props.resource.args }/readme?access_token=${this.state.token}`, this.loadContent, this.loadFailure, ); } this.setState({ path: this.props.resource.args }); } handleItemClick = e => { e.preventDefault(); getJSONContents( `${e.target.dataset.apiUrl}&access_token=${this.state.token}`, this.loadContent, this.loadFailure, ); this.setState({ root: false, path: e.target.dataset.path, }); }; loadContent = response => { const files = []; const directories = []; if (response.message === 'Not Found') { this.setState({ path: 'Repo not found (misspelled or private?)' }); } else if (Array.isArray(response)) { response.forEach(item => { if (item.type === 'file') { files.push(item); } else { directories.push(item); } }); this.setState({ files, directories, response, }); } else if (response.path === 'README.md') { this.setState({ readme: window.atob(response.content), }); } else if (response.content) { this.setState({ content: window.atob(response.content), response, }); } }; loadFailure = response => { this.setState({ path: response.message }); }; render() { if (!this.state.token || this.state.token.length === 0) { return (
Authentication required

This feature is in internal alpha testing mode.

); } if (this.state.content) { return (
{this.state.path}
{this.state.content}
); } const directories = this.state.directories.map(item => (
📁 {' '} {item.name}
)); const files = this.state.files.map(item => (
{item.name}
)); let readme = ''; if (this.state.readme) { readme = (
); } if (this.state.root) { return (
{this.state.path}
{directories} {files}
{readme}
); } return (
{this.state.path}
{directories} {files}
); } }