Add support for intervals (#1574)

Co-authored-by: Vini Brasil <vini@hey.com>
Co-authored-by: Vignesh Joglekar <hey@vigneshjoglekar.com>
pull/2463/head r2022.11.22-20
Vignesh Joglekar 4 years ago committed by GitHub
parent ed9e03ae14
commit 497a52c10a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -17,7 +17,8 @@ if (container) {
embedded: container.dataset.embedded,
background: container.dataset.background,
isDbip: container.dataset.isDbip === 'true',
flags: JSON.parse(container.dataset.flags)
flags: JSON.parse(container.dataset.flags),
validIntervalsByPeriod: JSON.parse(container.dataset.validIntervalsByPeriod)
}
const loggedIn = container.dataset.loggedIn === 'true'

@ -0,0 +1,127 @@
import {parseUTCDate, formatMonthYYYY, formatDay, formatDayShort} from '../../util/date'
const browserDateFormat = Intl.DateTimeFormat(navigator.language, { hour: 'numeric' })
const is12HourClock = function() {
return browserDateFormat.resolvedOptions().hour12
}
const parseISODate = function(isoDate) {
const date = parseUTCDate(isoDate)
const minutes = date.getMinutes();
return { date, minutes }
}
const formatHours = function(isoDate) {
const monthIndex = 1
const dateParts = isoDate.split(/[^0-9]/);
dateParts[monthIndex] = dateParts[monthIndex] - 1
const localDate = new Date(...dateParts)
return browserDateFormat.format(localDate)
}
const monthIntervalFormatter = {
long(isoDate, options) {
const formatted = this.short(isoDate, options)
return options.isBucketPartial ? `Partial of ${formatted}` : formatted
},
short(isoDate, _options) {
const { date } = parseISODate(isoDate)
return formatMonthYYYY(date)
}
}
const weekIntervalFormatter = {
long(isoDate, options) {
const formatted = this.short(isoDate, options)
return options.isBucketPartial ? `Partial week of ${formatted}` : `Week of ${formatted}`
},
short(isoDate, _options) {
const { date } = parseISODate(isoDate)
return formatDayShort(date)
}
}
const dateIntervalFormatter = {
long(isoDate, _options) {
const { date } = parseISODate(isoDate)
return formatDay(date)
},
short(isoDate, _options) {
const { date } = parseISODate(isoDate)
return formatDayShort(date)
}
}
const hourIntervalFormatter = {
long(isoDate, options) {
return this.short(isoDate, options)
},
short(isoDate, _options) {
const formatted = formatHours(isoDate)
if (is12HourClock()) {
return formatted.replace(' ', '').toLowerCase()
} else {
return formatted.replace(/[^0-9]/g, '').concat(":00")
}
}
}
const minuteIntervalFormatter = {
long(isoDate, options) {
if (options.period == 'realtime') {
const minutesAgo = Math.abs(isoDate)
return minutesAgo === 1 ? '1 minute ago' : minutesAgo + ' minutes ago'
} else {
return this.short(isoDate, options)
}
},
short(isoDate, options) {
if (options.period === 'realtime') return isoDate + 'm'
const { minutes } = parseISODate(isoDate)
const formatted = formatHours(isoDate)
if (is12HourClock()) {
return formatted.replace(' ', ':' + (minutes < 10 ? `0${minutes}` : minutes)).toLowerCase()
} else {
return formatted.replace(/[^0-9]/g, '').concat(":" + (minutes < 10 ? `0${minutes}` : minutes))
}
}
}
// Each interval has a different date and time format. This object maps each
// interval with two functions: `long` and `short`, that formats date and time
// accordingly.
const factory = {
month: monthIntervalFormatter,
week: weekIntervalFormatter,
date: dateIntervalFormatter,
hour: hourIntervalFormatter,
minute: minuteIntervalFormatter
}
/**
* Returns a function that formats a ISO 8601 timestamp based on the given
* arguments.
*
* The preferred date and time format in the dashboard depends on the selected
* interval and period. For example, in real-time view only the time is necessary,
* while other intervals require dates to be displayed.
*
* @param {string} interval - The interval of the query, e.g. `minute`, `hour`
* @param {boolean} longForm - Whether the formatted result should be in long or
* short form.
* @param {string} period - The period of the query, e.g. `12mo`, `day`
* @param {boolean} isPeriodFull - Indicates whether the interval has been cut
* off by the requested date range or not. If false, the returned formatted date
* indicates this cut off, e.g. `Partial week of November 8`.
*/
export default function dateFormatter(interval, longForm, period, isPeriodFull) {
const displayMode = longForm ? 'long' : 'short'
const options = { period: period, interval: interval, isBucketPartial: !isPeriodFull }
return function(isoDate, _index, _ticks) {
return factory[interval][displayMode](isoDate, options)
}
}

@ -1,5 +1,7 @@
import { parseUTCDate, formatMonthYYYY, formatDay } from '../../util/date'
import numberFormatter, {durationFormatter} from '../../util/number-formatter'
import dateFormatter from './date-formatter.js'
export const INTERVALS = ["month", "week", "date", "hour", "minute"]
export const METRIC_MAPPING = {
'Unique visitors (last 30 min)': 'visitors',
@ -27,39 +29,7 @@ export const METRIC_FORMATTER = {
'conversions': numberFormatter,
}
export const dateFormatter = (interval, longForm) => {
return function(isoDate, _index, _ticks) {
let date = parseUTCDate(isoDate)
if (interval === 'month') {
return formatMonthYYYY(date);
} else if (interval === 'date') {
return formatDay(date);
} else if (interval === 'hour') {
const parts = isoDate.split(/[^0-9]/);
date = new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5])
const dateFormat = Intl.DateTimeFormat(navigator.language, { hour: 'numeric' })
const twelveHourClock = dateFormat.resolvedOptions().hour12
const formattedHours = dateFormat.format(date)
if (twelveHourClock) {
return formattedHours.replace(' ', '').toLowerCase()
} else {
return formattedHours.replace(/[^0-9]/g, '').concat(":00")
}
} else if (interval === 'minute') {
if (longForm) {
const minutesAgo = Math.abs(isoDate)
return minutesAgo === 1 ? '1 minute ago' : minutesAgo + ' minutes ago'
} else {
return isoDate + 'm'
}
}
}
}
export const GraphTooltip = (graphData, metric) => {
export const GraphTooltip = (graphData, metric, query) => {
return (context) => {
const tooltipModel = context.tooltip;
const offset = document.getElementById("main-graph-canvas").getBoundingClientRect()
@ -93,23 +63,22 @@ export const GraphTooltip = (graphData, metric) => {
return bodyItem.lines;
}
function renderLabel(label, prev_label) {
const formattedLabel = dateFormatter(graphData.interval, true)(label)
const prev_formattedLabel = prev_label && dateFormatter(graphData.interval, true)(prev_label)
if (graphData.interval === 'month') {
return !prev_label ? formattedLabel : prev_formattedLabel
}
// Returns a string describing the bucket. Used when hovering the graph to
// show time buckets.
function renderBucketLabel(label) {
const isPeriodFull = graphData.full_intervals?.[label]
const formattedLabel = dateFormatter(graphData.interval, true, query.period, isPeriodFull)(label)
if (graphData.interval === 'date') {
return !prev_label ? formattedLabel : prev_formattedLabel
if (query.period === 'realtime') {
return dateFormatter(graphData.interval, true, query.period)(label)
}
if (graphData.interval === 'hour') {
return !prev_label ? `${dateFormatter("date", true)(label)}, ${formattedLabel}` : `${dateFormatter("date", true)(prev_label)}, ${dateFormatter(graphData.interval, true)(prev_label)}`
if (graphData.interval === 'hour' || graphData.interval == 'minute') {
const date = dateFormatter("date", true, query.period)(label)
return `${date}, ${formattedLabel}`
}
return !prev_label ? formattedLabel : prev_formattedLabel
return formattedLabel
}
// Set Tooltip Body
@ -134,7 +103,7 @@ export const GraphTooltip = (graphData, metric) => {
<div class='flex flex-row justify-between items-center'>
<span class='flex items-center mr-4'>
<div class='w-3 h-3 mr-1 rounded-full' style='background-color: rgba(101,116,205)'></div>
<span>${renderLabel(label)}</span>
<span>${renderBucketLabel(label)}</span>
</span>
<span class='text-base font-bold'>${METRIC_FORMATTER[metric](point)}</span>
</div>

@ -0,0 +1,67 @@
import { Menu, Transition } from '@headlessui/react';
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import React, { Fragment } from 'react';
import classNames from 'classnames'
import * as storage from '../../util/storage'
export const INTERVAL_LABELS = {
'minute': 'Minutes',
'hour': 'Hours',
'date': 'Days',
'week': 'Weeks',
'month': 'Months'
}
export const getStoredInterval = function(period, domain) {
return storage.getItem(`interval__${period}__${domain}`)
}
export const storeInterval = function(period, domain, interval) {
storage.setItem(`interval__${period}__${domain}`, interval)
}
function DropdownItem({ option, currentInterval, updateInterval }) {
return (
<Menu.Item onClick={() => updateInterval(option)} key={option} disabled={option == currentInterval}>
{({ active }) => (
<span className={classNames({
'bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 cursor-pointer': active,
'text-gray-700 dark:text-gray-200': !active,
'font-bold cursor-none select-none': option == currentInterval,
}, 'block px-4 py-2 text-sm')}>
{ INTERVAL_LABELS[option] }
</span>
)}
</Menu.Item>
)
}
export function IntervalPicker({ graphData, query, site, updateInterval }) {
if (query.period == 'realtime') return null
const currentInterval = graphData?.interval
const options = site.validIntervalsByPeriod[query.period]
return (
<Menu as="div" className="relative inline-block pl-2">
<Menu.Button className="text-sm inline-flex focus:outline-none text-gray-700 dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600 items-center">
{ INTERVAL_LABELS[currentInterval] }
<ChevronDownIcon className="w-4 h-4" aria-hidden="true" />
</Menu.Button>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items className="py-1 text-left origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none z-10">
{ options.map((option) => DropdownItem({ option, currentInterval, updateInterval })) }
</Menu.Items>
</Transition>
</Menu>
)
}

@ -1,6 +1,6 @@
import React from "react";
import classNames from "classnames";
import { Tooltip } from '../../util/tooltip'
import classNames from "classnames";
import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import { METRIC_MAPPING } from './graph-util'
@ -113,10 +113,10 @@ export default class TopStats extends React.Component {
)
})
if (query && query.period === 'realtime') {
if (stats && query && query.period === 'realtime') {
stats.push(<div key="dot" className="block pulsating-circle" style={{ left: '125px', top: '52px' }}></div>)
}
return stats
return stats || null;
}
}

@ -5,9 +5,19 @@ import { navigateToQuery } from '../../query'
import * as api from '../../api'
import * as storage from '../../util/storage'
import LazyLoader from '../../components/lazy-loader'
import {GraphTooltip, buildDataSet, dateFormatter, METRIC_MAPPING, METRIC_LABELS, METRIC_FORMATTER} from './graph-util';
import {GraphTooltip, buildDataSet, INTERVALS, METRIC_MAPPING, METRIC_LABELS, METRIC_FORMATTER} from './graph-util';
import dateFormatter from './date-formatter';
import TopStats from './top-stats';
import { IntervalPicker, getStoredInterval, storeInterval } from './interval-picker';
import FadeIn from '../../fade-in';
import * as url from '../../util/url'
import classNames from "classnames";
const LOADING_STATE = {
loading: 'loading',
refreshing: 'refreshing',
loaded: 'loaded'
}
class LineGraph extends React.Component {
constructor(props) {
@ -21,7 +31,7 @@ class LineGraph extends React.Component {
}
regenerateChart() {
const { graphData, metric } = this.props
const { graphData, metric, query } = this.props
const graphEl = document.getElementById("main-graph-canvas")
this.ctx = graphEl.getContext('2d');
const dataSet = buildDataSet(graphData.plot, graphData.present_index, this.ctx, METRIC_LABELS[metric])
@ -43,7 +53,7 @@ class LineGraph extends React.Component {
mode: 'index',
intersect: false,
position: 'average',
external: GraphTooltip(graphData, metric)
external: GraphTooltip(graphData, metric, query)
},
},
responsive: true,
@ -67,7 +77,23 @@ class LineGraph extends React.Component {
grid: { display: false },
ticks: {
maxTicksLimit: 8,
callback: function(val, _index, _ticks) { return dateFormatter(graphData.interval)(this.getLabelForValue(val)) },
callback: function (val, _index, _ticks) {
if (graphData.interval === 'hour' && query.period !== 'day') {
const date = dateFormatter("date", false, query.period)(this.getLabelForValue(val))
const hour = dateFormatter(graphData.interval, false, query.period)(this.getLabelForValue(val))
// Returns a combination of date and hour. This is because
// small intervals like hour may return multiple days
// depending on the query period.
return `${date}, ${hour}`
}
if (graphData.interval === 'minute' && query.period !== 'realtime') {
return dateFormatter("hour", false, query.period)(this.getLabelForValue(val))
}
return dateFormatter(graphData.interval, false, query.period)(this.getLabelForValue(val))
},
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
}
}
@ -106,15 +132,18 @@ class LineGraph extends React.Component {
const { graphData, metric, darkTheme } = this.props;
const tooltip = document.getElementById('chartjs-tooltip');
if (metric && graphData && (
if (
graphData !== prevProps.graphData ||
darkTheme !== prevProps.darkTheme
)) {
if (this.chart) {
this.chart.destroy();
) {
if (metric && graphData) {
if (this.chart) {
this.chart.destroy();
}
this.chart = this.regenerateChart();
this.chart.update();
}
this.chart = this.regenerateChart();
this.chart.update();
if (tooltip) {
tooltip.style.display = 'none';
@ -208,7 +237,7 @@ class LineGraph extends React.Component {
return (
<a className="w-4 h-4 mx-2" href={endpoint} download onClick={this.downloadSpinner.bind(this)}>
<svg className="absolute text-gray-700 feather dark:text-gray-300" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
<svg className="absolute text-gray-700 feather dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
</a>
)
}
@ -230,7 +259,7 @@ class LineGraph extends React.Component {
}
importedNotice() {
const source = this.props.topStatData.imported_source;
const source = this.props.topStatData && this.props.topStatData.imported_source;
if (source) {
const withImported = this.props.topStatData.with_imported;
@ -251,21 +280,25 @@ class LineGraph extends React.Component {
}
render() {
const { updateMetric, metric, topStatData, query } = this.props
const { updateMetric, metric, topStatData, query, site, graphData } = this.props
const extraClass = this.props.graphData && this.props.graphData.interval === 'hour' ? '' : 'cursor-pointer'
return (
<div className="graph-inner">
<div className="flex flex-wrap" ref={this.boundary}>
<TopStats query={query} metric={metric} updateMetric={updateMetric} topStatData={topStatData} tooltipBoundary={this.boundary.current} />
<TopStats query={query} metric={metric} updateMetric={updateMetric} topStatData={topStatData} tooltipBoundary={this.boundary.current}/>
</div>
<div className="relative px-2">
<div className="absolute right-4 -top-10 flex">
{this.downloadLink()}
{this.samplingNotice()}
<div className="absolute right-4 -top-10 py-2 md:py-0 flex items-center">
{ this.downloadLink() }
{ this.samplingNotice() }
{ this.importedNotice() }
{ site.flags && site.flags.intervals &&
<IntervalPicker site={site} query={query} graphData={graphData} metric={metric} updateInterval={this.props.updateInterval}/> }
</div>
<canvas id="main-graph-canvas" className={'mt-4 select-none ' + extraClass} width="1054" height="342"></canvas>
<FadeIn show={graphData}>
<canvas id="main-graph-canvas" className={'mt-4 select-none ' + extraClass} width="1054" height="342"></canvas>
</FadeIn>
</div>
</div>
)
@ -278,36 +311,76 @@ export default class VisitorGraph extends React.Component {
constructor(props) {
super(props)
this.state = {
loading: 2,
metric: storage.getItem(`metric__${this.props.site.domain}`) || 'visitors'
topStatsLoadingState: LOADING_STATE.loading,
mainGraphLoadingState: LOADING_STATE.loading,
metric: storage.getItem(`metric__${this.props.site.domain}`) || 'visitors',
interval: getStoredInterval(this.props.query.period, this.props.site.domain)
}
this.onVisible = this.onVisible.bind(this)
this.updateMetric = this.updateMetric.bind(this)
this.fetchTopStatData = this.fetchTopStatData.bind(this)
this.fetchGraphData = this.fetchGraphData.bind(this)
this.maybeRollbackInterval = this.maybeRollbackInterval.bind(this)
this.updateInterval = this.updateInterval.bind(this)
}
isIntervalValid({ query, site }) {
const period = query?.period
const validIntervalsForPeriod = site.validIntervalsByPeriod[period] || []
const storedInterval = getStoredInterval(period, site.domain)
return validIntervalsForPeriod.includes(storedInterval)
}
maybeRollbackInterval() {
if (this.isIntervalValid(this.props)) {
const interval = getStoredInterval(this.props.query.period, this.props.site.domain)
this.setState({interval}, () => {
this.fetchGraphData()
})
} else {
this.setState({interval: undefined}, () => {
this.setState({graphData: null})
this.fetchGraphData()
})
}
}
updateInterval(interval) {
if (INTERVALS.includes(interval)) {
this.setState({interval, mainGraphLoadingState: LOADING_STATE.refreshing}, this.maybeRollbackInterval)
storeInterval(this.props.query.period, this.props.site.domain, interval)
}
}
onVisible() {
this.fetchGraphData()
this.setState({mainGraphLoadingState: LOADING_STATE.loading}, this.maybeRollbackInterval)
this.fetchTopStatData()
if (this.props.timer) {
this.props.timer.onTick(this.fetchGraphData)
this.props.timer.onTick(this.maybeRollbackInterval)
this.props.timer.onTick(this.fetchTopStatData)
}
}
componentDidUpdate(prevProps, prevState) {
const { metric, topStatData } = this.state;
const { metric, topStatData, interval } = this.state;
if (this.props.query !== prevProps.query) {
this.setState({ loading: 3, graphData: null, topStatData: null })
this.fetchGraphData()
if (metric) {
this.setState({ mainGraphLoadingState: LOADING_STATE.loading, topStatsLoadingState: LOADING_STATE.loading, graphData: null, topStatData: null }, this.maybeRollbackInterval)
} else {
this.setState({ topStatsLoadingState: LOADING_STATE.loading, topStatData: null })
}
this.fetchTopStatData()
}
if (metric !== prevState.metric) {
this.setState({loading: 1, graphData: null})
this.fetchGraphData()
this.setState({mainGraphLoadingState: LOADING_STATE.refreshing}, this.maybeRollbackInterval)
}
if (interval !== prevState.interval && interval) {
this.setState({mainGraphLoadingState: LOADING_STATE.refreshing}, this.maybeRollbackInterval)
}
const savedMetric = storage.getItem(`metric__${this.props.site.domain}`)
@ -335,45 +408,75 @@ export default class VisitorGraph extends React.Component {
}
fetchGraphData() {
if (this.state.metric) {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/main-graph`, this.props.query, {metric: this.state.metric || 'none'})
if (!this.state.metric) {
this.setState({ mainGraphLoadingState: LOADING_STATE.ready, graphData: null })
return
}
const url = `/api/stats/${encodeURIComponent(this.props.site.domain)}/main-graph`
let params = {metric: this.state.metric || 'none'}
if (this.state.interval) { params.interval = this.state.interval }
api.get(url, this.props.query, params)
.then((res) => {
this.setState((state) => ({ loading: state.loading-2, graphData: res }))
this.setState({ mainGraphLoadingState: LOADING_STATE.ready, graphData: res })
return res
})
} else {
this.setState((state) => ({ loading: state.loading-2, graphData: null }))
}
.catch((err) => {
console.log(err)
this.setState({ mainGraphLoadingState: LOADING_STATE.ready, graphData: false })
})
}
fetchTopStatData() {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/top-stats`, this.props.query)
.then((res) => {
this.setState((state) => ({ loading: state.loading-1, topStatData: res }))
this.setState({ topStatsLoadingState: LOADING_STATE.ready, topStatData: res })
return res
})
}
}
renderInner() {
const { query, site } = this.props;
const { graphData, metric, topStatData, loading } = this.state;
const { graphData, metric, topStatData, topStatsLoadingState, mainGraphLoadingState } = this.state;
const theme = document.querySelector('html').classList.contains('dark') || false
if ((loading <= 1 && topStatData) || (topStatData && graphData)) {
return (
<LineGraphWithRouter graphData={graphData} topStatData={topStatData} site={site} query={query} darkTheme={theme} metric={metric} updateMetric={this.updateMetric} />
)
}
const topStatsReadyOrRefreshing = (topStatsLoadingState === LOADING_STATE.ready || topStatsLoadingState === LOADING_STATE.refreshing)
const mainGraphReadyOrRefreshing = (mainGraphLoadingState === LOADING_STATE.ready || mainGraphLoadingState === LOADING_STATE.refreshing)
const noMetricOrRefreshing = (!metric || mainGraphLoadingState === LOADING_STATE.refreshing)
const topStatAndGraphLoaded = !!(topStatData && graphData)
const showGraph =
topStatsReadyOrRefreshing &&
mainGraphReadyOrRefreshing &&
(topStatData && noMetricOrRefreshing || topStatAndGraphLoaded)
return (
<FadeIn show={showGraph}>
<LineGraphWithRouter graphData={graphData} topStatData={topStatData} site={site} query={query} darkTheme={theme} metric={metric} updateMetric={this.updateMetric} updateInterval={this.updateInterval}/>
</FadeIn>
)
}
render() {
const {metric, topStatData, graphData} = this.state
const {metric, mainGraphLoadingState, topStatsLoadingState} = this.state
const loaderClassName = classNames('mx-auto loading', {
'pt-52 sm:pt-56 md:pt-60': mainGraphLoadingState == LOADING_STATE.refreshing,
'pt-32 sm:pt-36 md:pt-48': mainGraphLoadingState !== LOADING_STATE.refreshing && metric,
'pt-16 sm:pt-14 md:pt-18 lg:pt-5': mainGraphLoadingState !== LOADING_STATE.refreshing && !metric
})
const loadingOrRefreshing =
mainGraphLoadingState == LOADING_STATE.refreshing ||
mainGraphLoadingState == LOADING_STATE.loading ||
topStatsLoadingState == LOADING_STATE.refreshing ||
topStatsLoadingState == LOADING_STATE.loading
return (
<LazyLoader onVisible={this.onVisible}>
<div className={`relative w-full mt-2 bg-white rounded shadow-xl dark:bg-gray-825 transition-padding ease-in-out duration-150 ${metric ? 'main-graph' : 'top-stats-only'}`}>
{this.state.loading > 0 && <div className="graph-inner"><div className={`${topStatData && !graphData ? 'pt-52 sm:pt-56 md:pt-60' : metric ? 'pt-32 sm:pt-36 md:pt-48' : 'pt-16 sm:pt-14 md:pt-18 lg:pt-5'} mx-auto loading`}><div></div></div></div>}
{loadingOrRefreshing && <div className="graph-inner"><div className={loaderClassName}><div></div></div></div>}
{this.renderInner()}
</div>
</LazyLoader>

@ -38,20 +38,21 @@ defmodule Plausible.Stats.Interval do
end
end
@allowed_intervals_for_period %{
@valid_by_period %{
"realtime" => ["minute"],
"day" => ["minute", "hour"],
"7d" => ["minute", "hour", "date"],
"month" => ["minute", "hour", "date", "week"],
"30d" => ["minute", "hour", "date", "week"],
"6mo" => ["minute", "hour", "date", "week", "month"],
"12mo" => ["minute", "hour", "date", "week", "month"],
"year" => ["minute", "hour", "date", "week", "month"],
"custom" => ["minute", "hour", "date", "week", "month"],
"all" => ["minute", "hour", "date", "week", "month"]
"7d" => ["hour", "date"],
"month" => ["date", "week"],
"30d" => ["date", "week"],
"6mo" => ["date", "week", "month"],
"12mo" => ["date", "week", "month"],
"year" => ["date", "week", "month"],
"custom" => ["date", "week", "month"],
"all" => ["date", "week", "month"]
}
def valid_by_period, do: @valid_by_period
@spec allowed_for_period?(period(), t()) :: boolean()
@spec valid_for_period?(period(), t()) :: boolean()
@doc """
Returns whether the given interval is valid for a time period.
@ -61,18 +62,18 @@ defmodule Plausible.Stats.Interval do
## Examples
iex> Plausible.Stats.Interval.allowed_for_period?("month", "date")
iex> Plausible.Stats.Interval.valid_for_period?("month", "date")
true
iex> Plausible.Stats.Interval.allowed_for_period?("30d", "month")
iex> Plausible.Stats.Interval.valid_for_period?("30d", "month")
false
iex> Plausible.Stats.Interval.allowed_for_period?("realtime", "week")
iex> Plausible.Stats.Interval.valid_for_period?("realtime", "week")
false
"""
def allowed_for_period?(period, interval) do
allowed = Map.get(@allowed_intervals_for_period, period, [])
def valid_for_period?(period, interval) do
allowed = Map.get(@valid_by_period, period, [])
interval in allowed
end
end

@ -1211,7 +1211,7 @@ defmodule PlausibleWeb.Api.StatsController do
defp validate_interval_granularity(params) do
with %{"interval" => interval, "period" => period} <- params,
true <- Plausible.Stats.Interval.allowed_for_period?(period, interval) do
true <- Plausible.Stats.Interval.valid_for_period?(period, interval) do
:ok
else
%{} ->

@ -308,7 +308,8 @@ defmodule PlausibleWeb.StatsController do
defp get_flags(user) do
%{
custom_dimension_filter: FunWithFlags.enabled?(:custom_dimension_filter, for: user)
custom_dimension_filter: FunWithFlags.enabled?(:custom_dimension_filter, for: user),
intervals: FunWithFlags.enabled?(:intervals, for: user)
}
end

@ -12,7 +12,22 @@
<% end %>
<div class="pt-6"></div>
<div id="stats-react-container" style="overflow-anchor: none;" data-domain="<%= @site.domain %>" data-offset="<%= Timex.Timezone.total_offset(Timex.Timezone.get(@site.timezone)) %>" data-has-goals="<%= @has_goals %>" data-logged-in="<%= !!@conn.assigns[:current_user] %>" data-stats-begin="<%= @stats_start_date %>" data-shared-link-auth="<%= assigns[:shared_link_auth] %>" data-embedded="<%= @conn.assigns[:embedded] %>" data-background="<%= @conn.assigns[:background] %>" data-is-dbip="<%= @is_dbip %>" data-current-user-role="<%= @conn.assigns[:current_user_role] %>" data-flags="<%= Jason.encode!(@flags) %>"></div>
<div
id="stats-react-container"
style="overflow-anchor: none;"
data-domain="<%= @site.domain %>"
data-offset="<%= Timex.Timezone.total_offset(Timex.Timezone.get(@site.timezone)) %>"
data-has-goals="<%= @has_goals %>"
data-logged-in="<%= !!@conn.assigns[:current_user] %>"
data-stats-begin="<%= @stats_start_date %>"
data-shared-link-auth="<%= assigns[:shared_link_auth] %>"
data-embedded="<%= @conn.assigns[:embedded] %>"
data-background="<%= @conn.assigns[:background] %>"
data-is-dbip="<%= @is_dbip %>"
data-current-user-role="<%= @conn.assigns[:current_user_role] %>"
data-flags="<%= Jason.encode!(@flags) %>"
data-valid-intervals-by-period="<%= Plausible.Stats.Interval.valid_by_period() |> Jason.encode!() %>"
/>
<div id="modal_root"></div>
<%= if !@conn.assigns[:current_user] && @conn.assigns[:demo] do %>
<div class="bg-gray-50 dark:bg-gray-850">

@ -387,72 +387,6 @@ defmodule PlausibleWeb.Api.StatsController.MainGraphTest do
describe "GET /api/stats/main-graph - varying intervals" do
setup [:create_user, :log_in, :create_new_site]
test "displays visitors for a month on an hourly scale", %{conn: conn, site: site} do
populate_stats(site, [
build(:pageview, timestamp: ~N[2021-01-01 00:00:00]),
build(:pageview, timestamp: ~N[2021-01-01 01:01:00])
])
conn =
get(
conn,
"/api/stats/#{site.domain}/main-graph?period=month&date=2021-01-01&metric=visitors&interval=hour"
)
assert %{"plot" => plot} = json_response(conn, 200)
assert Enum.count(plot) == 721
assert List.first(plot) == 1
assert Enum.at(plot, 1) == 1
end
test "displays visitors for a day on a minute scale", %{conn: conn, site: site} do
populate_stats(site, [
build(:pageview, timestamp: ~N[2021-01-01 00:00:00]),
build(:pageview, timestamp: ~N[2021-01-01 00:15:01]),
build(:pageview, timestamp: ~N[2021-01-01 00:15:02])
])
conn =
get(
conn,
"/api/stats/#{site.domain}/main-graph?period=day&date=2021-01-01&metric=visitors&interval=minute"
)
assert %{"plot" => plot} = json_response(conn, 200)
assert Enum.count(plot) == 1440
assert List.first(plot) == 1
assert Enum.at(plot, 15) == 2
end
test "displays visitors for date range on a minute scale", %{conn: conn, site: site} do
populate_stats(site, [
build(:pageview, timestamp: ~N[2021-01-01 00:00:00]),
build(:pageview, timestamp: ~N[2021-01-01 00:15:01]),
build(:pageview, timestamp: ~N[2021-01-01 00:15:02]),
build(:pageview, timestamp: ~N[2021-01-02 00:10:00]),
build(:pageview, timestamp: ~N[2021-01-02 00:11:01]),
build(:pageview, timestamp: ~N[2021-01-02 01:00:02]),
build(:pageview, timestamp: ~N[2021-01-04 03:10:00]),
build(:pageview, timestamp: ~N[2021-01-04 04:11:01]),
build(:pageview, timestamp: ~N[2021-01-04 05:00:02])
])
conn =
get(
conn,
"/api/stats/#{site.domain}/main-graph?period=custom&from=2021-01-01&to=2021-01-04&metric=visitors&interval=minute"
)
assert %{"plot" => plot} = json_response(conn, 200)
assert Enum.count(plot) == 4321
assert List.first(plot) == 1
assert Enum.at(plot, 15) == 2
assert Enum.at(plot, 1450) == 1
end
test "displays visitors for 6mo on a day scale", %{conn: conn, site: site} do
populate_stats(site, [
build(:pageview, timestamp: ~N[2021-01-01 00:00:00]),

Loading…
Cancel
Save