Commit 9e4c6a25 authored by Hanadi's avatar Hanadi
Browse files

Initial Commit

parents
import React from "react";
import {Button, Checkbox, Divider, FormControlLabel, FormGroup, Grid, Switch, TextField, Typography} from "@material-ui/core";
import {DateTimePicker, DatePicker, MuiPickersUtilsProvider} from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";
import {DateFilter, TrafficVisibilityMode} from "../Map";
import {getPMGeoJsonWithAverages, getTrafficGeoJsonWithAverages} from "../../common/FrostApiProxy";
import {FeatureCollection} from "geojson";
import {Color as AlertSeverity} from "@material-ui/lab/Alert/Alert";
import {endOfDay, startOfDay, subWeeks} from "date-fns";
type TrafficLayerProps = {
onTrafficLayerAdded: (geoJson: FeatureCollection, mode: TrafficVisibilityMode, dateFilter: DateFilter, isFiltered: boolean) => void;
onPMLayerAdded: (geoJson: FeatureCollection, mode: TrafficVisibilityMode, dateFilter: DateFilter, isFiltered: boolean) => void;
onTrafficLayerRemoved: () => void;
onColorByStrategyChanged: (value: boolean) => void;
onColorByAqiChanged: (value: boolean) => void;
addLoadingId: (id: string) => void;
removeLoadingId: (id: string) => void;
showSnackbar: (message: string, severity: AlertSeverity) => void;
}
type TrafficLayerState = {
minSpeed?: number;
maxSpeed?: number;
minJamFactor?: number;
maxJamFactor?: number;
minPMValue?: number;
maxPMValue?: number;
minDate: Date | null;
maxDate: Date | null;
day: Date | null;
visibleLayer?: TrafficVisibilityMode,
isLoadingTraffic: boolean;
isLoadingPM: boolean;
colorSpeedByStrategy: boolean;
colorPMByAqi: boolean;
}
function stringToNumberOrUndefined(value?: string): number | undefined {
return value !== undefined && value.length ? +value : undefined;
}
function numberOrEmptyString(value?: number): number | string {
return value !== undefined ? value : "";
}
export class STALayer extends React.Component<TrafficLayerProps, TrafficLayerState> {
constructor(props: TrafficLayerProps) {
super(props);
this.state = {
minDate: null,
maxDate: null,
day: null,
isLoadingTraffic: false,
isLoadingPM: false,
colorSpeedByStrategy: false,
colorPMByAqi: false,
};
}
get isLoading() {
return this.state.isLoadingPM || this.state.isLoadingTraffic;
}
private getSTADates(mode: TrafficVisibilityMode) {
if (mode === "co2" || mode === "pm") {
const maxDate = endOfDay(this.state.day || new Date());
const minDate = startOfDay(this.state.day || new Date());
return {
minDate: minDate,
maxDate: maxDate,
};
}
return {
minDate: this.state.minDate || undefined,
maxDate: this.state.maxDate || undefined,
};
}
private async handleSubmitClick(mode?: TrafficVisibilityMode): Promise<void> {
mode = mode || this.state.visibleLayer;
if (!mode)
return;
if (mode !== this.state.visibleLayer) {
this.props.onTrafficLayerRemoved();
}
const {minDate, maxDate} = this.getSTADates(mode);
if (!!minDate !== !!maxDate) {
this.props.showSnackbar("Either both dates or no date should be chosen!", "info");
return;
}
const trafficLayerFetchId = "traffic-layer-fetch";
this.props.addLoadingId(trafficLayerFetchId);
this.setState({isLoadingTraffic: true});
const promises: Promise<void>[] = [];
promises.push(
getTrafficGeoJsonWithAverages(
minDate,
maxDate,
mode === "speed" ? this.state.minSpeed : undefined,
mode === "speed" ? this.state.maxSpeed : undefined,
mode === "jam" ? this.state.minJamFactor : undefined,
mode === "jam" ? this.state.maxJamFactor : undefined,
).then(({geoJson, isFiltered}) => {
if (this.state.visibleLayer === mode) { // if removed by then
this.props.onTrafficLayerAdded(
geoJson,
mode!,
{fromDate: minDate, toDate: maxDate},
isFiltered);
}
}).catch((err: Error) => {
this.props.showSnackbar(`Traffic Error: ${err.message}`, "error");
console.error(err);
}).then(() => {
if (!this.state.visibleLayer || this.state.visibleLayer === mode) { // if removed by then
this.props.removeLoadingId(trafficLayerFetchId);
this.setState({isLoadingTraffic: false});
}
})
);
if (mode === "pm") {
const pmDataFetchId = "pm-data-fetch";
this.props.addLoadingId(pmDataFetchId);
this.setState({isLoadingPM: true});
promises.push(
getPMGeoJsonWithAverages(
minDate,
maxDate,
mode === "pm" ? this.state.minPMValue : undefined,
mode === "pm" ? this.state.maxPMValue : undefined,
).then(({geoJson, isFiltered}) => {
if (this.state.visibleLayer) { // if removed by then
this.props.onPMLayerAdded(
geoJson,
mode!,
{fromDate: minDate, toDate: maxDate},
isFiltered
);
}
}).catch((err: Error) => {
this.props.showSnackbar(`PM Error: ${err.message}`, "error");
console.error(err);
}).then(() => {
this.props.removeLoadingId(pmDataFetchId);
this.setState({isLoadingPM: false});
})
);
}
return Promise.all(promises).then(() => {});
}
private isVisible(mode: TrafficVisibilityMode): boolean {
return this.state.visibleLayer === mode;
}
private getSwitchChangedEventHandler(mode: TrafficVisibilityMode) {
return (event: React.ChangeEvent<HTMLInputElement>) => {
const checked = event.target.checked;
this.setState({visibleLayer: checked ? mode : undefined});
if (!mode || !checked) {
this.props.onTrafficLayerRemoved();
} else {
this.handleSubmitClick(mode);
}
};
}
private shouldShowMinMaxValues() {
return this.state.visibleLayer && ["speed", "jam"].includes(this.state.visibleLayer);
}
private shouldShowDayPicker() {
return this.state.visibleLayer && ["co2", "pm"].includes(this.state.visibleLayer);
}
private getMinValue(): number | string {
switch (this.state.visibleLayer) {
case "speed":
return numberOrEmptyString((this.state.minSpeed));
case "jam":
return numberOrEmptyString((this.state.minJamFactor));
}
return "";
}
private getMaxValue(): number | string {
switch (this.state.visibleLayer) {
case "speed":
return numberOrEmptyString(this.state.maxSpeed);
case "jam":
return numberOrEmptyString(this.state.maxJamFactor);
}
return "";
}
private setMinValue(value?: string) {
const val = stringToNumberOrUndefined(value);
switch (this.state.visibleLayer) {
case "speed":
return this.setState({minSpeed: val});
case "jam":
return this.setState({minJamFactor: val});
}
}
private setMaxValue(value?: string) {
const val = stringToNumberOrUndefined(value);
switch (this.state.visibleLayer) {
case "speed":
return this.setState({maxSpeed: val});
case "jam":
return this.setState({maxJamFactor: val});
}
}
private handleColorByStrategyCheckbox(event: React.ChangeEvent<HTMLInputElement>) {
const checked = event.target.checked;
if (checked && !this.state.minDate && !this.state.maxDate) {
const now = new Date();
this.setState({
maxDate: now,
minDate: subWeeks(now, 1),
colorSpeedByStrategy: checked,
});
setTimeout(() => {
this.handleSubmitClick()
.then(() => this.props.onColorByStrategyChanged(checked));
}, 50);
} else {
this.props.onColorByStrategyChanged(checked);
this.setState({colorSpeedByStrategy: checked});
}
};
private handleColorByAqiCheckbox(event: React.ChangeEvent<HTMLInputElement>) {
const checked = event.target.checked;
this.props.onColorByAqiChanged(checked);
this.setState({colorPMByAqi: checked});
};
render() {
return (<div>
<FormGroup>
<FormControlLabel
style={{padding: 10}}
control={<Switch
checked={this.isVisible("speed")}
onChange={this.getSwitchChangedEventHandler("speed")}
color={"primary"}
/>}
label="Traffic Speed"
/>
<Divider/>
<FormControlLabel
style={{padding: 10}}
control={<Switch
checked={this.isVisible("jam")}
onChange={this.getSwitchChangedEventHandler("jam")}
color={"primary"}
/>}
label="Traffic Jam"
/>
<Divider/>
<FormControlLabel
style={{padding: 10}}
control={<Switch
checked={this.isVisible("co2")}
onChange={this.getSwitchChangedEventHandler("co2")}
color={"primary"}
/>}
label="CO2 Measurements"
/>
<Divider/>
<FormControlLabel
style={{padding: 10}}
control={<Switch
checked={this.isVisible("pm")}
onChange={this.getSwitchChangedEventHandler("pm")}
color={"primary"}
/>}
label="PM Measurements"
/>
<Divider/>
</FormGroup>,
<Grid container style={{padding: 0, display: this.state.visibleLayer ? "unset" : "none"}}>
<Grid item xs={12} style={{margin: 10, display: this.state.visibleLayer === "speed" ? "unset" : "none"}}>
<FormControlLabel
style={{paddingTop: 10}}
control={<Checkbox
checked={this.state.colorSpeedByStrategy}
disabled={this.isLoading}
onChange={this.handleColorByStrategyCheckbox.bind(this)}
color={"primary"}
/>}
label="Speed Classifications"
/>
</Grid>
<Grid item xs={12} style={{margin: 10, display: this.state.visibleLayer === "pm" ? "unset" : "none"}}>
<FormControlLabel
style={{paddingTop: 10}}
control={<Checkbox
checked={this.state.colorPMByAqi}
disabled={this.state.isLoadingPM}
onChange={this.handleColorByAqiCheckbox.bind(this)}
color={"primary"}
/>}
label="Air Quality Index"
/>
</Grid>
<Grid item xs={12} style={{margin: 10}}>
<Typography variant={"h6"}>Filters</Typography>
</Grid>
<Grid item container xs={12} spacing={2} style={{padding: 8, margin: 0}}>
<Grid item xs={12} style={{display: this.shouldShowMinMaxValues() ? "unset" : "none"}}>
<TextField
type={"number"}
fullWidth
value={this.getMinValue()}
onChange={e => this.setMinValue(e.target.value)}
label={"Min"}
/>
</Grid>
<Grid item xs={12} style={{display: this.shouldShowMinMaxValues() ? "unset" : "none"}}>
<TextField
type={"number"}
fullWidth
value={this.getMaxValue()}
onChange={e => this.setMaxValue(e.target.value)}
label={"Max"}
/>
</Grid>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid item xs={12} style={{display: !this.shouldShowDayPicker() ? "unset" : "none"}}>
<DateTimePicker
value={this.state.minDate}
onChange={(date) => this.setState({minDate: date})}
label="Min Date"
showTodayButton
todayLabel={"Now"}
clearable
autoOk
fullWidth
/>
</Grid>
<Grid item xs={12} style={{display: !this.shouldShowDayPicker() ? "unset" : "none"}}>
<DateTimePicker
value={this.state.maxDate}
onChange={(date) => this.setState({maxDate: date})}
label="Max Date"
showTodayButton
todayLabel={"Now"}
clearable
autoOk
fullWidth
/>
</Grid>
<Grid item xs={12} style={{display: this.shouldShowDayPicker() ? "unset" : "none"}}>
<DatePicker
value={this.state.day}
onChange={(date) => this.setState({day: date})}
label="Day"
showTodayButton
todayLabel={"Today"}
clearable
autoOk
fullWidth
/>
</Grid>
</MuiPickersUtilsProvider>
<Grid item xs={12} style={{
textAlign: "center",
margin: 3
}}>
<Button
color={"primary"}
variant={"contained"}
disabled={this.isLoading}
onClick={() => this.handleSubmitClick()}
>
Submit
</Button>
</Grid>
</Grid>
</Grid>
</div>);
}
}
import React from "react";
import {heatingColorGradient} from "../../common/ColorGradient";
import {BLACK_CSS, numberWithCommas} from "../../common/Helpers";
import {PopupDataInfo} from "./Popup";
import {PopupGrid, PopupGridItem} from "./PopupGrid";
type BuildingPopupState = {}
type BuildingPopupProps = {
info: PopupDataInfo;
}
export class BuildingPopupContent extends React.Component<BuildingPopupProps, BuildingPopupState> {
private getGridItems(): PopupGridItem[] {
const {buildingInfo, trafficVisibilityMode} = this.props.info;
if (!buildingInfo)
return [];
const {heatingInfo} = buildingInfo || {};
const generalItems: PopupGridItem[] = [
{key: "Id", value: buildingInfo?.id},
{key: "Name", value: buildingInfo?.properties["name"]},
{key: "Parent Id", value: buildingInfo?.properties["gml_parent_id"]},
{key: "Description", value: buildingInfo?.properties["description"]},
{key: "Longitude", value: buildingInfo?.properties["longitude"] || buildingInfo?.properties["longtitude"]},
{key: "Latitude", value: buildingInfo?.properties["latitude"]},
];
let heatingItems: PopupGridItem[] = [];
if (trafficVisibilityMode === "co2" && heatingInfo) {
const {spaceHeating, electricalAppliancesHeating, domesticWaterHeating} = heatingInfo;
const totalHeating = spaceHeating + electricalAppliancesHeating + domesticWaterHeating;
const textColor = heatingColorGradient.getColorAtAsCssHex(
totalHeating,
BLACK_CSS,
true);
const unit = "kgCO2eq/day";
heatingItems = [
{key: "Space Heating", value: numberWithCommas(spaceHeating), unit},
{key: "Electrical Appliances Heating", value: numberWithCommas(electricalAppliancesHeating), unit},
{key: "Domestic Water Heating", value: numberWithCommas(domesticWaterHeating), unit},
{
key: "Total Heating",
value: numberWithCommas(totalHeating),
textColor,
unit
},
];
}
return generalItems.concat(heatingItems);
}
render() {
return <div>
<PopupGrid items={this.getGridItems()}/>
</div>;
}
}
import React from "react";
import {addHours, subHours} from "date-fns";
import {aqiSensorColorGradient, pmSensorColorGradient} from "../../common/ColorGradient";
import {BLACK_CSS, formatTimestamp, range, roundTo} from "../../common/Helpers";
import {getPMHistory} from "../../common/FrostApiProxy";
import {Typography} from "@material-ui/core";
import {CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis} from "recharts";
import {PopupDataInfo} from "./Popup";
import {PopupGrid, PopupGridItem} from "./PopupGrid";
type DateValue = {
timestamp: number;
value: number;
}
type PMPopupState = {
chartData?: DateValue[];
isLoading: boolean;
fromDate: Date,
toDate: Date,
}
type PMPopupProps = {
info: PopupDataInfo;
}
export class PMPopupContent extends React.Component<PMPopupProps, PMPopupState> {
constructor(props: PMPopupProps) {
super(props);
let {fromDate, toDate} = this.props.info.dateFilter;
if (!fromDate && !toDate) {
toDate = new Date();
fromDate = subHours(toDate, 24);
} else if (!fromDate && toDate) {
fromDate = subHours(toDate, 24);
} else if (fromDate && !toDate) {
toDate = addHours(fromDate, 24);
}
this.state = {
isLoading: false,
fromDate: fromDate!,
toDate: toDate!,
};
}
componentDidMount() {
if (!this.state.isLoading && !this.state.chartData) {
this.loadHistoryData();
}
}
private getGridItems(): PopupGridItem[] {
const {pmInfo} = this.props.info;
const textColor = pmSensorColorGradient.getColorAtAsCssHex(
pmInfo?.pm,
BLACK_CSS,
true
);
const aqiTextColor = aqiSensorColorGradient.getColorAtAsCssHex(
pmInfo?.aqiValue,
BLACK_CSS,
true
);
const averageStr = this.props.info.isFiltered ? " Average" : "";
return [
{key: "Sensor Type", value: "SDS 011"},
{key: "Description", value: pmInfo?.description},
{key: "Longitude", value: pmInfo?.longitude},
{key: "Latitude", value: pmInfo?.latitude},
{key: "PM2.5" + averageStr, value: roundTo(pmInfo?.pm), textColor, unit: "µg/m³"},
{key: "AQI", value: `${roundTo(pmInfo?.aqiValue)} (${pmInfo?.aqiRange?.name})`, textColor: aqiTextColor},
];
}
private getChartTitle(): string {
const {fromDate, toDate} = this.props.info.dateFilter;
const parts = [];
if (fromDate || toDate) {
const dateTimeFormat = "dd.MM.yyyy HH:mm";
const dayFormat = "dd.MM.yyyy";
if (fromDate && toDate && fromDate.getHours() === 0 && toDate.getHours() === 23) {
parts.push(`for ${formatTimestamp(this.state.fromDate.getTime(), dayFormat)}`);
} else {
parts.push(`from ${formatTimestamp(this.state.fromDate.getTime(), dateTimeFormat)}`);
parts.push(`to ${formatTimestamp(this.state.toDate.getTime(), dateTimeFormat)}`);
}
}
const period = parts.length ? parts.join(" ") : "for the last 24 hours";
return `Emission rates ${period}`;
}
private loadHistoryData() {
this.setState({isLoading: true});
setTimeout(() => {
const {id} = this.props.info.pmInfo!;
const {fromDate, toDate} = this.state;
getPMHistory(+id, fromDate!, toDate!)
.then(data => {
this.setState({
chartData: data.map(it => ({timestamp: it.phenomenonTime.getTime(), value: it.result})),
isLoading: false
});
});
}, 100);
}
private getMinMaxValues() {
const minValue = this.state.chartData ? Math.min(...this.state.chartData.map(d => d.value)) : 0;
const maxValue = this.state.chartData ? Math.max(...this.state.chartData.map(d => d.value)) : 0;
return {minValue, maxValue};
}
render() {
const {minValue, maxValue} = this.getMinMaxValues();
return <div>
<PopupGrid items={this.getGridItems()}/>
<div style={{marginTop: 10}}>
<Typography variant={"h6"}>{this.getChartTitle()}</Typography>
<div style={{textAlign: "center"}}>
{this.state.isLoading ? "Loading..." :
<ResponsiveContainer className={"area-chart-container"} height={300}>
<LineChart data={this.state.chartData}>
<defs>
<linearGradient id="chartGradient" x1="0" y1="0" x2="0" y2="1">
{range(0, 1, 10).map(v =>
<stop key={`range-${v}`} offset={v}
stopColor={pmSensorColorGradient?.getColorAtAsCssHex(
(1 - v) * (maxValue - minValue) + minValue, undefined, true
)}
stopOpacity={1}/>
)}
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3"/>
<XAxis dataKey="timestamp" type={"number"}
allowDataOverflow
domain={["dataMin", "dataMax"]}
tickFormatter={timestamp => formatTimestamp(timestamp)}/>
<YAxis domain={[0, (dataMax: number) => Math.max(dataMax, 100)]}
tickCount={5}
tickFormatter={pm => roundTo(pm)?.toString() || ""}/>
<Legend/>
<Tooltip
labelFormatter={(timestamp) => formatTimestamp(timestamp, "dd.MM.yyyy HH:mm")}
formatter={(pm: number) => pm + " µg/m³"}
/>
<Line
dataKey={"value"}
dot={false}
name={"PM2.5"}
strokeWidth={2}
stroke={"url(#chartGradient)"}
// @ts-ignore
activeDot={({cx, cy, payload}) =>
(<circle cx={cx}
cy={cy}
r={5}
stroke={"white"}
strokeWidth={1}
fill={pmSensorColorGradient.getColorAtAsCssHex(payload.value, "black", true)}
/>)
}
/>
</LineChart>
</ResponsiveContainer>
}
</div>
</div>
</div>;
}
}
.area-chart-container {
display: flex;
align-items: center;
flex: 1;
}
import React from "react";
import {TrafficCacheInfo} from "../../common/TrafficCacheManager";
import {AQIRange, Dictionary} from "../../common/Helpers";
import {DateFilter, HeatingInfo, TrafficVisibilityMode} from "../Map";
import {Button, Dialog, DialogActions, DialogContent, DialogTitle} from "@material-ui/core";
import "./Popup.css";
import {TrafficPopupContent} from "./TrafficPopupContent";
import {PMPopupContent} from "./PMPopupContent";
import {BuildingPopupContent} from "./BuildingPopupContent";
type Id = { id: string };
export type PopupDataInfo = {
trafficVisibilityMode?: TrafficVisibilityMode,
type: "traffic" | "pm" | "building";
trafficInfo?: TrafficCacheInfo & Id;
buildingInfo?: Id & { heatingInfo?: HeatingInfo; properties: Dictionary<any> };
pmInfo?: Id & { pm: number; aqiValue: number; aqiRange: AQIRange; description: string; longitude: number, latitude: number };
dateFilter: DateFilter;
isFiltered: boolean;
}
type PopupState = {}
type PopupProps = {
info: PopupDataInfo;
handleClose: () => void;
}
export class Popup extends React.Component<PopupProps, PopupState> {
getTitle(): string {
switch (this.props.info.type) {
case "traffic":
return `Traffic Info ${this.props.info.trafficInfo?.id}`;
case "pm":
return `PM2.5 Info ${this.props.info.pmInfo?.id}`;
case "building":
return `Feature Info ${this.props.info.buildingInfo?.id}`;
}
return "Info";
}
render() {
return (<Dialog
open={true}
onClose={this.props.handleClose}
maxWidth={"md"}
fullWidth={true}
>
<DialogTitle>{this.getTitle()}</DialogTitle>
<DialogContent>
{(() => {
switch (this.props.info.type) {
case "traffic":
return <TrafficPopupContent info={this.props.info}/>;
case "building":
return <BuildingPopupContent info={this.props.info}/>;
case "pm":
return <PMPopupContent info={this.props.info}/>;
}
})()}
</DialogContent>
<DialogActions>
<Button onClick={this.props.handleClose} color="primary">
Close
</Button>
</DialogActions>
</Dialog>);
}
}
import React from "react";
import {Grid} from "@material-ui/core";
export type PopupGridItem = {
key: string;
value?: string | number;
unit?: string;
textColor?: string;
fullWidth?: boolean;
};
type PopupGridProps = {
items: PopupGridItem[];
}
type PopupGridState = {}
export class PopupGrid extends React.Component<PopupGridProps, PopupGridState> {
render() {
return (
<Grid container spacing={3}>
{this.props.items.map(({key, value, unit, textColor, fullWidth}) => {
if (value === undefined || value === null)
return null;
return ([
<Grid item key={`key-${key}`} xs={2} style={{
color: textColor || "unset",
textAlign: "right",
fontWeight: "bold"
}}>
{key}
</Grid>,
<Grid item key={`value-${value}`} xs={fullWidth ? 10 : 4} style={{
color: textColor || "unset",
}}>
<span>{value}</span>
{unit ? <span style={{marginLeft: 4}}>{unit}</span> : null}
</Grid>
]);
}
)}
</Grid>
);
}
}
import React from "react";
import {PopupDataInfo} from "./Popup";
import {PopupGrid, PopupGridItem} from "./PopupGrid";
import {
trafficCo2ColorGradient,
jamFactorColorGradient,
pmTrafficColorGradient,
speedColorGradient,
ColorGradient
} from "../../common/ColorGradient";
import {
BLACK_CSS,
kgCo2PerDayFactorFromSpeed,
formatTimestamp,
getLabelAtValue,
numberWithCommas,
pmFactorFromSpeed,
range,
roundTo
} from "../../common/Helpers";
import {Typography} from "@material-ui/core";
import {addHours, endOfDay, startOfDay, subDays, subHours} from "date-fns";
import {getAveragesForFeatureOfInterest, getTrafficHistory} from "../../common/FrostApiProxy";
import {Bar, BarChart, CartesianGrid, Cell, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis} from "recharts";
import {AxisDomain} from "recharts/types/util/types";
import {TrafficVisibilityMode} from "../Map";
type DateValue = {
timestamp: number;
value: number;
}
type Charts = {
speedChart?: ChartData;
jamChart?: ChartData;
pmChart?: ChartData;
co2Chart?: ChartData;
selectedChart?: TrafficVisibilityMode;
}
type ChartData = {
data: DateValue[];
unit: string;
axisTitle: string;
yAxisDomain: AxisDomain;
yAxisTickCount?: number;
yAxisTicks?: (string | number)[];
}
type TrafficPopupState = {
charts?: Charts;
isLoading: boolean;
fromDate: Date;
toDate: Date;
}
type TrafficPopupProps = {
info: PopupDataInfo;
}
export class TrafficPopupContent extends React.Component<TrafficPopupProps, TrafficPopupState> {
constructor(props: TrafficPopupProps) {
super(props);
let {fromDate, toDate} = this.props.info.dateFilter;
if (!fromDate && !toDate) {
toDate = new Date();
fromDate = subHours(toDate, 24);
} else if (!fromDate && toDate) {
fromDate = subHours(toDate, 24);
} else if (fromDate && !toDate) {
toDate = addHours(fromDate, 24);
}
this.state = {
isLoading: false,
fromDate: fromDate!,
toDate: toDate!,
};
}
componentDidMount() {
if (!this.state.isLoading && !this.state.charts) {
this.loadHistoryData();
}
}
private loadHistoryData() {
this.setState({isLoading: true});
const {id} = this.props.info.trafficInfo!;
const {fromDate, toDate} = this.state;
const mode = this.props.info.trafficVisibilityMode!;
if (mode === "speed" || mode === "jam") {
getTrafficHistory(id, fromDate!, toDate!)
.then(data => {
const speedChart: ChartData = {
axisTitle: "Speed",
unit: "km/h",
data: data.map(it => ({
timestamp: it.phenomenonTime.getTime(),
value: it.speed
})),
yAxisDomain: [0, (dataMax: number) => Math.max(dataMax, 100)],
yAxisTicks: [0, 20, 40, 60, 80, 100],
};
const jamChart: ChartData = {
axisTitle: "Jam Factor",
unit: "/10",
data: data.map(it => ({
timestamp: it.phenomenonTime.getTime(),
value: it.jam
})),
yAxisDomain: [0, 10],
yAxisTickCount: 6, // even numbers
};
this.setState({
charts: {
speedChart,
jamChart,
selectedChart: this.props.info.trafficVisibilityMode!
},
isLoading: false
});
});
} else {
const last7Days = [6, 5, 4, 3, 2, 1, 0].map(d => ({
startTime: subDays(startOfDay(fromDate), d),
endTime: subDays(endOfDay(fromDate), d),
}));
const promises = last7Days.map(day =>
getAveragesForFeatureOfInterest(
id,
1000,
day.startTime,
day.endTime,
).then(data => ({...data, ...day}))
);
Promise.all(promises).then(data => {
const co2Chart: ChartData = {
axisTitle: "CO2 Emission",
unit: "kgCO2eq/day",
data: data.map(it => ({
timestamp: it.startTime.getTime(),
value: kgCo2PerDayFactorFromSpeed(
it.speed!,
this.props.info.trafficInfo?.segmentLength!
)
})),
yAxisDomain: [0, (dataMax: number) => Math.max(dataMax, 3000)],
yAxisTickCount: 7,
};
const pmChart: ChartData = {
axisTitle: "PM2.5",
unit: "kg/day",
data: data.map(it => ({
timestamp: it.startTime.getTime(),
value: pmFactorFromSpeed(it.speed!,
this.props.info.trafficInfo?.segmentLength!
)
})),
yAxisDomain: [0, (dataMax: number) => Math.max(dataMax, 300)],
yAxisTickCount: 6
};
this.setState({
charts: {
co2Chart,
pmChart,
selectedChart: this.props.info.trafficVisibilityMode!
},
isLoading: false
});
});
}
}
private getGridItems(): PopupGridItem[] {
const {trafficInfo, trafficVisibilityMode} = this.props.info;
let items: PopupGridItem[] = [
{key: "Id", value: trafficInfo?.id},
{key: "Description", value: trafficInfo?.description},
];
const averageStr = this.props.info.isFiltered ? " Average" : "";
let textColor;
switch (trafficVisibilityMode) {
case "speed":
textColor = speedColorGradient.getColorAtAsCssHex(trafficInfo?.speed, BLACK_CSS, true);
items.push({key: "Speed" + averageStr, value: numberWithCommas(trafficInfo?.speed), textColor, unit: "km/h"});
break;
case "pm":
textColor = pmTrafficColorGradient.getColorAtAsCssHex(trafficInfo?.pmFactor, BLACK_CSS, true);
items.push({key: "PM2.5" + averageStr, value: numberWithCommas(trafficInfo?.pmFactor), textColor, unit: "kg/day"});
break;
case "co2":
textColor = trafficCo2ColorGradient.getColorAtAsCssHex(trafficInfo?.co2Factor, BLACK_CSS, true);
items.push({key: "CO2" + averageStr, value: numberWithCommas(trafficInfo?.co2Factor), textColor, unit: "kgCO2eq/day"});
break;
case "jam":
textColor = jamFactorColorGradient.getColorAtAsCssHex(trafficInfo?.jamFactor, BLACK_CSS, true);
items.push({key: "Jam" + averageStr, value: `${roundTo(trafficInfo?.jamFactor)}/10`, textColor});
break;
}
if (trafficInfo?.quality) {
items.push({key: "Result Quality", value: `${roundTo(trafficInfo.quality * 100)}%`});
}
return items;
}
private getChartTitle(): string {
const {fromDate, toDate} = this.props.info.dateFilter;
const parts = [];
const dateTimeFormat = "dd.MM.yyyy HH:mm";
const dayFormat = "dd.MM.yyyy";
if (fromDate || toDate) {
parts.push(`from ${formatTimestamp(this.state.fromDate.getTime(), dateTimeFormat)}`);
parts.push(`to ${formatTimestamp(this.state.toDate.getTime(), dateTimeFormat)}`);
}
const period = parts.length ? parts.join(" ") : "from the last 24 hours";
switch (this.props.info.trafficVisibilityMode) {
case "speed":
return `Speed data ${period}`;
case "jam":
return `Jam Factor data ${period}`;
case "pm":
case "co2":
return `Daily emission rate a week from ${formatTimestamp(
this.state.fromDate.getTime(),
dayFormat
)}`;
}
return `Data ${period}`;
}
private getSelectedChart(): ChartData | undefined {
switch (this.state.charts?.selectedChart) {
case "speed":
return this.state.charts?.speedChart;
case "jam":
return this.state.charts?.jamChart;
case "co2":
return this.state.charts?.co2Chart;
case "pm":
return this.state.charts?.pmChart;
}
return undefined;
}
private getSelectedColorGradient(): ColorGradient | undefined {
switch (this.state.charts?.selectedChart) {
case "speed":
return speedColorGradient;
case "jam":
return jamFactorColorGradient;
case "co2":
return trafficCo2ColorGradient;
case "pm":
return pmTrafficColorGradient;
}
return undefined;
}
private getMinMaxGradientValues() {
const chartData = this.getSelectedChart();
const minValue = chartData ? Math.min(...chartData.data.map(d => d.value)) : 0;
const maxValue = chartData ? Math.max(...chartData.data.map(d => d.value)) : 0;
const colorGradient = this.getSelectedColorGradient();
return {minValue, maxValue, colorGradient};
}
render() {
const selectedChart = this.getSelectedChart();
const {minValue, maxValue, colorGradient} = this.getMinMaxGradientValues();
return <div>
<PopupGrid items={this.getGridItems()}/>
<div style={{marginTop: 10}}>
<Typography variant={"h6"}>{this.getChartTitle()}</Typography>
{this.state.isLoading ? "Loading..." :
(() => {
const mode = this.props.info.trafficVisibilityMode;
if (mode === "speed" || mode === "jam")
return <ResponsiveContainer className={"area-chart-container"} height={350}>
<LineChart data={selectedChart?.data}>
<defs>
<linearGradient id="chartGradient" x1="0" y1="0" x2="0" y2="1">
{range(0, 1, 10).map(v =>
<stop key={`range-${v}`} offset={v}
stopColor={colorGradient?.getColorAtAsCssHex(
(1 - v) * (maxValue - minValue) + minValue, undefined, true
)}
stopOpacity={1}/>
)}
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3"/>
<XAxis dataKey="timestamp" type={"number"}
allowDataOverflow
domain={["dataMin", "dataMax"]}
tickFormatter={timestamp => formatTimestamp(timestamp)}/>
<YAxis domain={selectedChart?.yAxisDomain}
tickCount={selectedChart?.yAxisTickCount || 10}
ticks={selectedChart?.yAxisTicks}
tickFormatter={result => getLabelAtValue(roundTo(result))?.toString() || ""}/>
<Legend/>
<Tooltip
labelFormatter={(timestamp) => formatTimestamp(timestamp, "dd.MM.yyyy HH:mm")}
formatter={(result: number) => `${numberWithCommas(result)} ${selectedChart?.unit || ""}`}
/>
<Line
dataKey={"value"}
dot={false}
name={selectedChart?.axisTitle}
strokeWidth={2}
stroke={"url(#chartGradient)"}
// @ts-ignore
activeDot={({cx, cy, payload}) =>
(<circle cx={cx}
cy={cy}
r={5}
stroke={"white"}
strokeWidth={1}
fill={colorGradient?.getColorAtAsCssHex(payload.value, "black", true)}
/>)
}
/>
</LineChart>
</ResponsiveContainer>;
const data = selectedChart?.data;
const dayFormat = "E do. MMM";
return <ResponsiveContainer className={"area-chart-container"} height={350}>
<BarChart data={data}>
<defs>
<linearGradient id="chartGradient" x1="0" y1="0" x2="0" y2="1">
{range(0, 1, 10).map(v =>
<stop key={`range-${v}`} offset={v}
stopColor={colorGradient?.getColorAtAsCssHex(
(1 - v) * (maxValue - minValue) + minValue, undefined, true
)}
stopOpacity={1}/>
)}
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3"/>
<XAxis dataKey="timestamp"
tickFormatter={timestamp => formatTimestamp(timestamp, dayFormat)}/>
<YAxis
domain={selectedChart?.yAxisDomain}
tickCount={selectedChart?.yAxisTickCount || 10}
ticks={selectedChart?.yAxisTicks}
tickFormatter={result => getLabelAtValue(roundTo(result))?.toString() || ""}/>
<Legend/>
<Tooltip
labelFormatter={(timestamp) => formatTimestamp(timestamp, dayFormat)}
formatter={(result: number) => `${numberWithCommas(result)} ${selectedChart?.unit || ""}`}
/>
<Bar
dataKey={"value"}
name={selectedChart?.axisTitle}
fill={"url(#chartGradient)"}
>
{data?.map((dateValue, index) =>
<Cell key={`cell-${index}`}
fill={colorGradient?.getColorAtAsCssHex(dateValue.value)}
/>
)}
</Bar>
</BarChart>
</ResponsiveContainer>;
})()
}
</div>
</div>;
}
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
ReactDOM.render(
// <React.StrictMode>
<App/>,
// </React.StrictMode>,
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
\ No newline at end of file
/// <reference types="react-scripts" />
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="main" level="application" />
</component>
</module>
\ No newline at end of file
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment