Farmbot-Web-App/frontend/demo/demo_iframe.tsx

86 lines
2.3 KiB
TypeScript
Raw Normal View History

2019-06-21 07:09:14 -06:00
import { connect, MqttClient } from "mqtt";
import React from "react";
import { uuid } from "farmbot";
import axios from "axios";
2020-02-15 11:30:23 -07:00
import { ExternalUrl } from "../external_urls";
2020-02-28 09:34:28 -07:00
import { t } from "../i18next_wrapper";
2019-06-21 07:09:14 -06:00
interface State {
error: Error | undefined;
stage: string;
}
const WS_CONFIG = {
username: "farmbot_demo",
password: "required, but not used.",
};
const SECRET = uuid().split("-").join("");
2019-07-07 14:40:54 -06:00
export const MQTT_CHAN = "demos/" + SECRET;
2019-06-21 07:09:14 -06:00
const HTTP_URL = "/api/demo_account";
2019-07-06 22:32:37 -06:00
export const EASTER_EGG = "BIRDS AREN'T REAL";
2019-06-21 07:09:14 -06:00
export const WAITING_ON_API = "Planting your demo garden...";
// APPLICATION CODE ==============================
export class DemoIframe extends React.Component<{}, State> {
2019-07-07 14:40:54 -06:00
state: State =
2020-02-28 09:34:28 -07:00
{ error: undefined, stage: t("DEMO THE APP") };
2019-06-21 07:09:14 -06:00
setError = (error?: Error) => this.setState({ error });
2019-07-04 14:49:51 -06:00
connectMqtt = (): Promise<MqttClient> => {
const client = connect(globalConfig.MQTT_WS, WS_CONFIG);
return new Promise(resolve => {
2019-07-07 14:40:54 -06:00
client.on("message", this.handleMessage);
client.subscribe(MQTT_CHAN, this.setError);
client.on("connect", resolve);
2019-07-04 14:49:51 -06:00
});
}
connectApi = () => {
const is51 = (Math.round(Math.random() * 100) == 51);
is51 && this.setState({ stage: EASTER_EGG });
2019-07-06 22:32:37 -06:00
2019-07-04 14:49:51 -06:00
return axios
.post<string>(HTTP_URL, { secret: SECRET })
.then(() => this.setState({ stage: WAITING_ON_API }))
.catch(this.setError);
2019-06-21 07:09:14 -06:00
}
handleMessage =
(_chan: string, _buffer: Buffer) => {
localStorage.setItem("session", _buffer.toString());
location.assign("/app/designer/plants");
}
requestAccount = () => {
2019-07-04 14:49:51 -06:00
return this.connectMqtt().then(this.connectApi);
2019-06-21 07:09:14 -06:00
};
ok = () => {
return <div className="demo-container">
<video muted={true} autoPlay={true} loop={true} className="demo-video">
2020-02-18 12:21:09 -07:00
<source src={ExternalUrl.Video.desktop} type="video/mp4" />
2019-06-21 07:09:14 -06:00
</video>
2020-02-18 12:21:09 -07:00
<img className="demo-phone" src={ExternalUrl.Video.mobile} />
2020-02-28 09:34:28 -07:00
<button className="demo-button"
title={t("demo the app")}
onClick={this.requestAccount}>
2019-06-21 07:09:14 -06:00
{this.state.stage}
</button>
</div>;
};
no = () => {
// tslint:disable-next-line:no-null-keyword
const message = JSON.stringify(this.state.error, null, 2);
return <pre> {message} </pre>;
}
render() {
return this.state.error ?
this.no() : this.ok();
}
}