libre
Version:
World's lightest CMS
102 lines (79 loc) • 2.6 kB
JavaScript
import React, {Component} from 'react';
import { Router, Route, Redirect, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import ReactDOM from 'react-dom';
import Libre from './Libre';
import Dealer from './Dealer';
export default class Client extends Component {
constructor(props) {
super(props);
this.state = {
refreshing: false,
libre: null
};
this.globals = {
refresh: () => this.refresh(),
og: (tags) => this.og(tags)
// push: (tab, row, success) => this.push(tab, row, success)
}
}
componentWillMount() {
Libre.load( (libre) => this.setState({libre}) );
}
//to make content production easier, the client app can expose a refresh button
//pushing content to app state on load also causes components to re-render live
//(whether they use it or not)
//because App state is passed to all child components as props
refresh() {
this.setState({refreshing: true});
Libre.refresh((libre) => this.setState({refreshing: false, libre}));
}
og(tags) {
if (typeof(document) === 'object') {
if (tags.title) document.title = tags.title;
if (tags.description) {
const meta = document.querySelector('meta[name="description"]');
if (meta != null) meta.setAttribute('content', tags.description);
}
}
}
render() {
const {App, routes} = this.props;
if (!this.state.libre) return null;
return (
<Route render={(r) => (
<App {...r} {...this.state} {...this.globals}>
<Switch>
{Object.keys(routes).map((key) => this.renderRoute(key, routes[key]))}
</Switch>
</App>
)} />
)
}
renderRoute(key, route) {
const routeProps = {exact: key === '/', key, path: key};
const Component = route.component;
return (
<Route {...routeProps} render={(r) =>
<Component {...r} {...this.state} {...this.globals} />
} />
)
}
static run(App, routes, config, typeMap, plugins) {
if (config.GA_ID) Dealer.init(config.GA_ID);
Libre.setup({typeMap, plugins});
//pass other config data into app instance via route props
const renderProps = {config, typeMap, App, routes};
const history = createBrowserHistory();
//track current (first) page, and listen for subsequent updates
Dealer.page();
history.listen((location) => {
Dealer.page();
});
ReactDOM.render((
<Router history={history}>
<Client {...renderProps} />
</Router>
), document.querySelector('#app'));
}
}