Move metric state into localStorage

This commit gets rid of the internal `metric` state in the VisitorGraph
component and starts using localStorage for that instead.

This commit also chains the main-graph request into the top-stats request
callback - meaning that we'll always fetch new graph data after top stats
are updated. And we do it all in a single function.

Doing so simplifies the loading state significantly, and also helps to
make it clear, that at all times, existing top stats are required before
we can fetch the graph. That's because the metric is determined by which
Top stats are returned (for example, we can't be sure whether revenue
metrics will be returned or not).
top-report-refactor
Robert Joonas 3 years ago committed by Uku Taht
parent 2054d50d29
commit 1aace861fe

@ -1,21 +1,5 @@
import numberFormatter, {durationFormatter} from '../../util/number-formatter'
export const METRIC_MAPPING = {
'Unique visitors (last 30 min)': 'visitors',
'Pageviews (last 30 min)': 'pageviews',
'Unique visitors': 'visitors',
'Visit duration': 'visit_duration',
'Total pageviews': 'pageviews',
'Views per visit': 'views_per_visit',
'Total visits': 'visits',
'Bounce rate': 'bounce_rate',
'Unique conversions': 'conversions',
'Total conversions': 'events',
'Conversion rate': 'conversion_rate',
'Average revenue': 'average_revenue',
'Total revenue': 'total_revenue',
}
export const METRIC_LABELS = {
'visitors': 'Visitors',
'pageviews': 'Pageviews',
@ -45,11 +29,9 @@ export const METRIC_FORMATTER = {
}
export const LoadingState = {
loading: 'loading',
refreshing: 'refreshing',
loaded: 'loaded',
isLoadingOrRefreshing: function (state) { return [this.loading, this.refreshing].includes(state) },
isLoadedOrRefreshing: function (state) { return [this.loaded, this.refreshing].includes(state) }
loading: 0,
updatingGraph: 1,
loaded: 2
}
const buildComparisonDataset = function(comparisonPlot) {

@ -28,7 +28,8 @@ class LineGraph extends React.Component {
}
regenerateChart() {
const { graphData, metric, query } = this.props
const { graphData, query } = this.props
const metric = graphData.metric
const graphEl = document.getElementById("main-graph-canvas")
this.ctx = graphEl.getContext('2d');
const dataSet = buildDataSet(graphData.plot, graphData.comparison_plot, graphData.present_index, this.ctx, METRIC_LABELS[metric])

@ -3,7 +3,7 @@ import { Tooltip } from '../../util/tooltip'
import { SecondsSinceLastLoad } from '../../util/seconds-since-last-load'
import classNames from "classnames";
import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import { METRIC_MAPPING } from './graph-util'
import * as storage from '../../util/storage'
import { formatDateRange } from '../../util/date.js'
function Maybe({condition, children}) {
@ -86,15 +86,13 @@ export default class TopStats extends React.Component {
}
canMetricBeGraphed(stat) {
const isTotalUniqueVisitors = this.props.query.filters.goal && stat.name === 'Unique visitors'
const isKnownMetric = Object.keys(METRIC_MAPPING).includes(stat.name)
return isKnownMetric && !isTotalUniqueVisitors
return !!stat.graph_metric
}
maybeUpdateMetric(stat) {
if (this.canMetricBeGraphed(stat)) {
this.props.updateMetric(METRIC_MAPPING[stat.name])
storage.setItem(`metric__${this.props.site.domain}`, stat.graph_metric)
this.props.onMetricUpdate(stat.graph_metric)
}
}
@ -104,9 +102,12 @@ export default class TopStats extends React.Component {
)
}
getStoredMetric() {
return storage.getItem(`metric__${this.props.site.domain}`)
}
renderStatName(stat) {
const { metric } = this.props
const isSelected = metric === METRIC_MAPPING[stat.name]
const isSelected = stat.graph_metric === this.getStoredMetric()
const [statDisplayName, statExtraName] = stat.name.split(/(\(.+\))/g)
@ -140,7 +141,7 @@ export default class TopStats extends React.Component {
<div className="my-1 space-y-2">
<div>
<span className="flex items-center justify-between whitespace-nowrap">
<p className="font-bold text-xl dark:text-gray-100" id={METRIC_MAPPING[stat.name]}>{this.topStatNumberShort(stat.name, stat.value)}</p>
<p className="font-bold text-xl dark:text-gray-100" id={stat.graph_metric}>{this.topStatNumberShort(stat.name, stat.value)}</p>
<Maybe condition={!query.comparison}>
{ this.renderPercentageComparison(stat.name, stat.change) }
</Maybe>

@ -3,7 +3,7 @@ import { Link } from 'react-router-dom'
import * as api from '../../api'
import * as storage from '../../util/storage'
import LazyLoader from '../../components/lazy-loader'
import { METRIC_MAPPING, LoadingState } from './graph-util'
import { LoadingState } from './graph-util'
import TopStats from './top-stats';
import { IntervalPicker, getCurrentInterval } from './interval-picker';
import FadeIn from '../../fade-in';
@ -31,106 +31,90 @@ export default class VisitorGraph extends React.Component {
constructor(props) {
super(props)
this.state = {
topStatsLoadingState: LoadingState.loading,
mainGraphLoadingState: LoadingState.loading,
metric: storage.getItem(`metric__${this.props.site.domain}`) || 'visitors',
loading: LoadingState.loading,
topStatData: null,
graphData: null,
exported: false
}
this.onVisible = this.onVisible.bind(this)
this.updateMetric = this.updateMetric.bind(this)
this.fetchTopStatData = this.fetchTopStatData.bind(this)
this.fetchTopStatsAndGraphData = this.fetchTopStatsAndGraphData.bind(this)
this.fetchGraphData = this.fetchGraphData.bind(this)
this.onIntervalUpdate = this.onIntervalUpdate.bind(this)
this.onMetricUpdate = this.onMetricUpdate.bind(this)
this.boundary = React.createRef()
}
onIntervalUpdate(interval) {
this.setState({ mainGraphLoadingState: LoadingState.refreshing, graphData: null }, () => this.fetchGraphData(interval))
}
fetchTopStatsAndGraphData() {
const { site, query } = this.props
this.setState({loading: LoadingState.loading, topStatData: null, graphData: null})
onVisible() {
this.setState({ mainGraphLoadingState: LoadingState.loading }, this.fetchGraphData)
this.fetchTopStatData()
if (this.props.query.period === 'realtime') {
document.addEventListener('tick', this.fetchGraphData)
document.addEventListener('tick', this.fetchTopStatData)
}
fetchTopStats(site, query)
.then((res) => {
this.setState({ topStatData: res, loading: LoadingState.updatingGraph }, () => {
this.storeTopStatsContainerHeight()
})
let metric = this.getStoredMetric()
const availableMetrics = res.top_stats.filter(stat => !!stat.graph_metric).map(stat => stat.graph_metric)
if (!availableMetrics.includes(metric)) {
metric = availableMetrics[0]
storage.setItem(`metric__${this.props.site.domain}`, metric)
}
const interval = getCurrentInterval(site, query)
return fetchMainGraph(site, query, metric, interval)
})
.then((res) => {
this.setState({ graphData: res, loading: LoadingState.loaded })
})
}
componentDidUpdate(prevProps, prevState) {
const { metric } = this.state;
const { query } = this.props
if (query !== prevProps.query) {
this.setState({ mainGraphLoadingState: LoadingState.loading, topStatsLoadingState: LoadingState.loading, graphData: null, topStatData: null }, this.fetchGraphData)
this.fetchTopStatData()
}
fetchGraphData(metric, interval) {
const { site, query } = this.props
this.setState({loading: LoadingState.updatingGraph, graphData: null})
if (metric !== prevState.metric) {
this.setState({ mainGraphLoadingState: LoadingState.refreshing }, this.fetchGraphData)
}
fetchMainGraph(site, query, metric, interval)
.then((res) => {
this.setState({graphData: res, loading: LoadingState.loaded})
})
}
resetMetric() {
const { topStatData } = this.state
const { query, site } = this.props
const savedMetric = storage.getItem(`metric__${site.domain}`)
const selectableMetrics = topStatData && topStatData.top_stats.map(({ name }) => METRIC_MAPPING[name]).filter(name => name)
const canSelectSavedMetric = selectableMetrics && selectableMetrics.includes(savedMetric)
if (query.filters.goal && !['conversion_rate', 'events'].includes(savedMetric)) {
this.setState({ metric: 'conversions' })
} else if (canSelectSavedMetric) {
this.setState({ metric: savedMetric })
} else {
this.setState({ metric: 'visitors' })
}
getStoredMetric() {
return storage.getItem(`metric__${this.props.site.domain}`)
}
componentWillUnmount() {
document.removeEventListener('tick', this.fetchGraphData)
document.removeEventListener('tick', this.fetchTopStatData)
onIntervalUpdate(newInterval) {
this.fetchGraphData(this.getStoredMetric(), newInterval)
}
storeTopStatsContainerHeight() {
storage.setItem(`topStatsHeight__${this.props.site.domain}`, document.getElementById('top-stats-container').clientHeight)
onMetricUpdate(newMetric) {
this.fetchGraphData(newMetric, getCurrentInterval(this.props.site, this.props.query))
}
updateMetric(clickedMetric) {
if (this.state.metric == clickedMetric) return
onVisible() {
this.fetchTopStatsAndGraphData()
storage.setItem(`metric__${this.props.site.domain}`, clickedMetric)
this.setState({ metric: clickedMetric, graphData: null })
if (this.props.query.period === 'realtime') {
document.addEventListener('tick', this.fetchTopStatsAndGraphData)
}
}
fetchGraphData(interval) {
const { site, query } = this.props
const graphInterval = interval || getCurrentInterval(site, query)
const metric = this.state.metric
fetchMainGraph(site, query, metric, graphInterval)
.then((res) => {
this.setState({ mainGraphLoadingState: LoadingState.loaded, graphData: res })
return res
})
.catch((err) => {
console.log(err)
this.setState({ mainGraphLoadingState: LoadingState.loaded, graphData: false })
})
componentDidUpdate(prevProps, prevState) {
if (this.props.query !== prevProps.query) {
this.fetchTopStatsAndGraphData()
}
}
fetchTopStatData() {
const { site, query } = this.props
componentWillUnmount() {
document.removeEventListener('tick', this.fetchTopStatsAndGraphData)
}
fetchTopStats(site, query)
.then((res) => {
this.setState({ topStatsLoadingState: LoadingState.loaded, topStatData: res }, () => {
this.storeTopStatsContainerHeight()
this.resetMetric()
})
return res
})
storeTopStatsContainerHeight() {
storage.setItem(`topStatsHeight__${this.props.site.domain}`, document.getElementById('top-stats-container').clientHeight)
}
pollExportReady() {
@ -235,51 +219,31 @@ export default class VisitorGraph extends React.Component {
}
}
renderInner() {
render() {
const { query, site } = this.props;
const { graphData, metric, topStatData, topStatsLoadingState, mainGraphLoadingState } = this.state;
const { graphData, topStatData, loading } = this.state;
const isDarkTheme = document.querySelector('html').classList.contains('dark') || false
const mainGraphRefreshing = (mainGraphLoadingState === LoadingState.refreshing)
const topStatAndGraphLoaded = !!(topStatData && graphData)
const shouldShow =
topStatsLoadingState === LoadingState.loaded &&
LoadingState.isLoadedOrRefreshing(mainGraphLoadingState) &&
(topStatData && mainGraphRefreshing || topStatAndGraphLoaded)
return (
<FadeIn show={shouldShow}>
<div id="top-stats-container" className="flex flex-wrap" ref={this.boundary} style={{ height: this.getTopStatsHeight() }}>
<TopStats site={site} query={query} metric={metric} updateMetric={this.updateMetric} topStatData={topStatData} tooltipBoundary={this.boundary.current} lastLoadTimestamp={this.props.lastLoadTimestamp} />
</div>
<div className="relative px-2">
{mainGraphRefreshing && renderLoader()}
<div className="absolute right-4 -top-8 py-1 flex items-center">
{this.downloadLink()}
{this.samplingNotice()}
{this.importedNotice()}
<IntervalPicker site={site} query={query} onIntervalUpdate={this.onIntervalUpdate} />
</div>
<LineGraphWithRouter graphData={graphData} darkTheme={isDarkTheme} query={query} metric={metric}/>
</div>
</FadeIn>
)
}
render() {
const { mainGraphLoadingState, topStatsLoadingState } = this.state
const showLoader =
[mainGraphLoadingState, topStatsLoadingState].includes(LoadingState.loading) &&
mainGraphLoadingState !== LoadingState.refreshing
return (
<LazyLoader onVisible={this.onVisible}>
<div className={"relative w-full mt-2 bg-white rounded shadow-xl dark:bg-gray-825"}>
{showLoader && renderLoader()}
{this.renderInner()}
{loading === LoadingState.loading && renderLoader()}
<FadeIn show={loading !== LoadingState.loading}>
<div id="top-stats-container" className="flex flex-wrap" ref={this.boundary} style={{ height: this.getTopStatsHeight() }}>
<TopStats site={site} query={query} onMetricUpdate={this.onMetricUpdate} topStatData={topStatData} tooltipBoundary={this.boundary.current} lastLoadTimestamp={this.props.lastLoadTimestamp} />
</div>
<div className="relative px-2">
{loading === LoadingState.updatingGraph && renderLoader()}
<div className="absolute right-4 -top-8 py-1 flex items-center">
{this.downloadLink()}
{this.samplingNotice()}
{this.importedNotice()}
<IntervalPicker site={site} query={query} onIntervalUpdate={this.onIntervalUpdate} />
</div>
<LineGraphWithRouter graphData={graphData} darkTheme={isDarkTheme} query={query} />
</div>
</FadeIn>
</div>
</LazyLoader>
)

@ -129,6 +129,7 @@ defmodule PlausibleWeb.Api.StatsController do
full_intervals = build_full_intervals(query, labels)
json(conn, %{
metric: metric,
plot: plot_timeseries(timeseries_result, metric),
labels: labels,
comparison_plot: comparison_result && plot_timeseries(comparison_result, metric),

Loading…
Cancel
Save