diff --git a/assets/js/dashboard/api.js b/assets/js/dashboard/api.js index cdc624176..ae808aba8 100644 --- a/assets/js/dashboard/api.js +++ b/assets/js/dashboard/api.js @@ -45,6 +45,7 @@ export function serializeQuery(query, extraQuery=[]) { if (query.filters) { queryObj.filters = serializeFilters(query.filters) } if (query.with_imported) { queryObj.with_imported = query.with_imported } if (SHARED_LINK_AUTH) { queryObj.auth = SHARED_LINK_AUTH } + if (query.comparison) { queryObj.comparison = true } Object.assign(queryObj, ...extraQuery) return '?' + serialize(queryObj) diff --git a/assets/js/dashboard/comparison-input.js b/assets/js/dashboard/comparison-input.js new file mode 100644 index 000000000..2a1bb7f17 --- /dev/null +++ b/assets/js/dashboard/comparison-input.js @@ -0,0 +1,23 @@ +import React from 'react' +import { withRouter } from "react-router-dom"; +import { navigateToQuery } from './query' + +export const COMPARISON_DISABLED_PERIODS = ['realtime', 'all'] + +const ComparisonInput = function({ site, query, history }) { + if (!site.flags.comparisons) return null + if (COMPARISON_DISABLED_PERIODS.includes(query.period)) return null + + function update(event) { + navigateToQuery(history, query, { comparison: event.target.checked }) + } + + return ( +
+ + +
+ ) +} + +export default withRouter(ComparisonInput) diff --git a/assets/js/dashboard/historical.js b/assets/js/dashboard/historical.js index 486a5ecf4..524bcbab5 100644 --- a/assets/js/dashboard/historical.js +++ b/assets/js/dashboard/historical.js @@ -10,6 +10,7 @@ import Pages from './stats/pages' import Locations from './stats/locations'; import Devices from './stats/devices' import Conversions from './stats/conversions' +import ComparisonInput from './comparison-input' import { withPinnedHeader } from './pinned-header-hoc'; function Historical(props) { @@ -38,6 +39,7 @@ function Historical(props) { + diff --git a/assets/js/dashboard/query.js b/assets/js/dashboard/query.js index 45fc98274..6d338cf80 100644 --- a/assets/js/dashboard/query.js +++ b/assets/js/dashboard/query.js @@ -2,6 +2,7 @@ import React from 'react' import { Link, withRouter } from 'react-router-dom' import {formatDay, formatMonthYYYY, nowForSite, parseUTCDate} from './util/date' import * as storage from './util/storage' +import { COMPARISON_DISABLED_PERIODS } from './comparison-input' const PERIODS = ['realtime', 'day', 'month', '7d', '30d', '6mo', '12mo', 'year', 'all', 'custom'] @@ -18,12 +19,16 @@ export function parseQuery(querystring, site) { period = '30d' } + let comparison = !!q.get('comparison') + if (COMPARISON_DISABLED_PERIODS.includes(period)) comparison = null + return { period, date: q.get('date') ? parseUTCDate(q.get('date')) : nowForSite(site), from: q.get('from') ? parseUTCDate(q.get('from')) : undefined, to: q.get('to') ? parseUTCDate(q.get('to')) : undefined, with_imported: q.get('with_imported') ? q.get('with_imported') === 'true' : true, + comparison: comparison, filters: { 'goal': q.get('goal'), 'props': JSON.parse(q.get('props')), diff --git a/assets/js/dashboard/stats/graph/graph-util.js b/assets/js/dashboard/stats/graph/graph-util.js index 543618d03..da747f30b 100644 --- a/assets/js/dashboard/stats/graph/graph-util.js +++ b/assets/js/dashboard/stats/graph/graph-util.js @@ -35,6 +35,52 @@ export const LoadingState = { isLoadedOrRefreshing: function (state) { return [this.loaded, this.refreshing].includes(state) } } +const renderBucketLabel = function(query, graphData, label, comparison = false) { + let isPeriodFull = graphData.full_intervals?.[label] + if (comparison) isPeriodFull = true + + const formattedLabel = dateFormatter(graphData.interval, true, query.period, isPeriodFull)(label) + + if (query.period === 'realtime') { + return dateFormatter(graphData.interval, true, query.period)(label) + } + + if (graphData.interval === 'hour' || graphData.interval == 'minute') { + const date = dateFormatter("date", true, query.period)(label) + return `${date}, ${formattedLabel}` + } + + return formattedLabel +} + +const calculatePercentageDifference = function(oldValue, newValue) { + if (oldValue == 0 && newValue > 0) { + return 100 + } else if (oldValue == 0 && newValue == 0) { + return 0 + } else { + return Math.round((newValue - oldValue) / oldValue * 100) + } +} + +const buildTooltipData = function(query, graphData, metric, tooltipModel) { + const data = tooltipModel.dataPoints.find((dataPoint) => dataPoint.dataset.yAxisID == "y") + const comparisonData = tooltipModel.dataPoints.find((dataPoint) => dataPoint.dataset.yAxisID == "yComparison") + + const label = renderBucketLabel(query, graphData, graphData.labels[data.dataIndex]) + const comparisonLabel = comparisonData && renderBucketLabel(query, graphData, graphData.comparison_labels[data.dataIndex], true) + + const value = data?.raw || 0 + const comparisonValue = comparisonData?.raw || 0 + const comparisonDifference = comparisonData && calculatePercentageDifference(comparisonValue, value) + + const metricFormatter = METRIC_FORMATTER[metric] + const formattedValue = metricFormatter(value) + const formattedComparisonValue = comparisonData && metricFormatter(comparisonValue) + + return { label, formattedValue, comparisonLabel, formattedComparisonValue, comparisonDifference } +} + export const GraphTooltip = (graphData, metric, query) => { return (context) => { const tooltipModel = context.tooltip; @@ -65,57 +111,35 @@ export const GraphTooltip = (graphData, metric, query) => { return; } - function getBody(bodyItem) { - return bodyItem.lines; - } - - // 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 (query.period === 'realtime') { - return dateFormatter(graphData.interval, true, query.period)(label) - } - - if (graphData.interval === 'hour' || graphData.interval == 'minute') { - const date = dateFormatter("date", true, query.period)(label) - return `${date}, ${formattedLabel}` - } - - return formattedLabel - } - // Set Tooltip Body if (tooltipModel.body) { - var bodyLines = tooltipModel.body.map(getBody); - - // Remove duplicated line on overlap between dashed and normal - if (bodyLines.length == 3) { - bodyLines[1] = false - } - - const data = tooltipModel.dataPoints[0] - const label = graphData.labels[data.dataIndex] - const point = data.raw || 0 + const tooltipData = buildTooltipData(query, graphData, metric, tooltipModel) let innerHtml = `
${METRIC_LABELS[metric]} + ${tooltipData.comparisonDifference ? `${tooltipData.comparisonDifference}%` : ''}
- ${renderBucketLabel(label)} + ${tooltipData.label}
- ${METRIC_FORMATTER[metric](point)} + ${tooltipData.formattedValue} +
+ + ${tooltipData.comparisonLabel ? `
+ +
+ ${tooltipData.comparisonLabel} +
+ ${tooltipData.formattedComparisonValue}
${graphData.interval === 'month' ? 'Click to view month' : graphData.interval === 'date' ? 'Click to view day' : ''} -
+ ` : ''} `; tooltipEl.innerHTML = innerHtml; @@ -124,7 +148,11 @@ export const GraphTooltip = (graphData, metric, query) => { } } -export const buildDataSet = (plot, present_index, ctx, label, isPrevious) => { +const truncateToPresentIndex = function(array, presentIndex) { + return array.slice(0, presentIndex) +} + +export const buildDataSet = (plot, comparisonPlot, present_index, ctx, label) => { var gradient = ctx.createLinearGradient(0, 0, 0, 300); var prev_gradient = ctx.createLinearGradient(0, 0, 0, 300); gradient.addColorStop(0, 'rgba(101,116,205, 0.2)'); @@ -132,16 +160,32 @@ export const buildDataSet = (plot, present_index, ctx, label, isPrevious) => { prev_gradient.addColorStop(0, 'rgba(101,116,205, 0.075)'); prev_gradient.addColorStop(1, 'rgba(101,116,205, 0)'); - if (!isPrevious) { - if (present_index) { - var dashedPart = plot.slice(present_index - 1, present_index + 1); - var dashedPlot = (new Array(present_index - 1)).concat(dashedPart) - const _plot = [...plot] - for (var i = present_index; i < _plot.length; i++) { - _plot[i] = undefined + let comparisonDataSet = [] + if (comparisonPlot) { + comparisonDataSet = [ + { + label, + data: truncateToPresentIndex(comparisonPlot, present_index), + borderWidth: 3, + borderColor: 'rgba(60,70,110,0.2)', + pointBackgroundColor: 'rgba(60,70,110,0.2)', + pointHoverBackgroundColor: 'rgba(60, 70, 110)', + pointBorderColor: 'transparent', + pointHoverRadius: 4, + backgroundColor: gradient, + fill: true, + yAxisID: 'yComparison', } + ] + } + + if (present_index) { + var dashedPart = plot.slice(present_index - 1, present_index + 1); + var dashedPlot = (new Array(present_index - 1)).concat(dashedPart) + const _plot = truncateToPresentIndex([...plot], present_index) - return [{ + return [ + { label, data: _plot, borderWidth: 3, @@ -152,6 +196,7 @@ export const buildDataSet = (plot, present_index, ctx, label, isPrevious) => { pointHoverRadius: 4, backgroundColor: gradient, fill: true, + yAxisID: 'y', }, { label, @@ -164,9 +209,12 @@ export const buildDataSet = (plot, present_index, ctx, label, isPrevious) => { pointHoverRadius: 4, backgroundColor: gradient, fill: true, - }] - } else { - return [{ + yAxisID: 'y', + } + ].concat(comparisonDataSet) + } else { + return [ + { label, data: plot, borderWidth: 3, @@ -176,20 +224,8 @@ export const buildDataSet = (plot, present_index, ctx, label, isPrevious) => { pointHoverRadius: 4, backgroundColor: gradient, fill: true, - }] - } - } else { - return [{ - label, - data: plot, - borderWidth: 2, - borderColor: 'rgba(166,187,210,0.5)', - pointHoverBackgroundColor: 'rgba(166,187,210,0.8)', - pointBorderColor: 'transparent', - pointHoverBorderColor: 'transparent', - pointHoverRadius: 4, - backgroundColor: prev_gradient, - fill: true, - }] + yAxisID: 'y', + } + ].concat(comparisonDataSet) } } diff --git a/assets/js/dashboard/stats/graph/visitor-graph.js b/assets/js/dashboard/stats/graph/visitor-graph.js index 72efd06f8..902b5ccb5 100644 --- a/assets/js/dashboard/stats/graph/visitor-graph.js +++ b/assets/js/dashboard/stats/graph/visitor-graph.js @@ -13,6 +13,18 @@ import FadeIn from '../../fade-in'; import * as url from '../../util/url' import classNames from "classnames"; +const calculateMaximumY = function(dataset) { + const yAxisValues = dataset + .flatMap((item) => item.data) + .map((item) => item || 0) + + if (yAxisValues) { + return Math.max(...yAxisValues) + } else { + return 1 + } +} + class LineGraph extends React.Component { constructor(props) { super(props); @@ -28,7 +40,7 @@ class LineGraph extends React.Component { 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]) + const dataSet = buildDataSet(graphData.plot, graphData.comparison_plot, graphData.present_index, this.ctx, METRIC_LABELS[metric]) return new Chart(this.ctx, { type: 'line', @@ -54,7 +66,8 @@ class LineGraph extends React.Component { onClick: this.onClick.bind(this), scales: { y: { - beginAtZero: true, + min: 0, + suggestedMax: calculateMaximumY(dataSet), ticks: { callback: METRIC_FORMATTER[metric], maxTicksLimit: 8, @@ -65,6 +78,12 @@ class LineGraph extends React.Component { drawBorder: false, } }, + yComparison: { + min: 0, + suggestedMax: calculateMaximumY(dataSet), + display: false, + grid: { display: false }, + }, x: { grid: { display: false }, ticks: { diff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.ex index 4eab32265..e8adff12d 100644 --- a/lib/plausible_web/controllers/api/stats_controller.ex +++ b/lib/plausible_web/controllers/api/stats_controller.ex @@ -97,9 +97,9 @@ defmodule PlausibleWeb.Api.StatsController do selected_metric = if !params["metric"] || params["metric"] == "conversions" do - "visitors" + :visitors else - params["metric"] + String.to_existing_atom(params["metric"]) end timeseries_query = @@ -109,21 +109,22 @@ defmodule PlausibleWeb.Api.StatsController do query end - timeseries_result = - Stats.timeseries(site, timeseries_query, [String.to_existing_atom(selected_metric)]) - - plot = - Enum.map(timeseries_result, fn row -> - row[String.to_existing_atom(selected_metric)] || 0 - end) - - labels = Enum.map(timeseries_result, fn row -> row[:date] end) + timeseries_result = Stats.timeseries(site, timeseries_query, [selected_metric]) + labels = label_timeseries(timeseries_result) present_index = present_index_for(site, query, labels) full_intervals = build_full_intervals(query, labels) + comparison_result = + if params["comparison"] do + comparison_query = Query.shift_back(query, site) + Stats.timeseries(site, comparison_query, [selected_metric]) + end + json(conn, %{ - plot: plot, + plot: plot_timeseries(timeseries_result, selected_metric), labels: labels, + comparison_plot: comparison_result && plot_timeseries(comparison_result, selected_metric), + comparison_labels: comparison_result && label_timeseries(comparison_result), present_index: present_index, interval: query.interval, with_imported: query.include_imported, @@ -135,6 +136,14 @@ defmodule PlausibleWeb.Api.StatsController do end end + defp plot_timeseries(timeseries, metric) do + Enum.map(timeseries, fn row -> row[metric] || 0 end) + end + + defp label_timeseries(timeseries) do + Enum.map(timeseries, & &1.date) + end + defp build_full_intervals(%{interval: "week", date_range: range}, labels) do for label <- labels, into: %{} do interval_start = Timex.beginning_of_week(label) diff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.ex index bb35bdb8b..a4403ea39 100644 --- a/lib/plausible_web/controllers/stats_controller.ex +++ b/lib/plausible_web/controllers/stats_controller.ex @@ -311,7 +311,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), + comparisons: FunWithFlags.enabled?(:comparisons, for: user) } end