Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
First pass at Comparisons (#2650)
Vini Brasil5159e683cc5b
diff --git a/assets/js/dashboard/api.js b/assets/js/dashboard/api.jsindex cdc624176d..ae808aba8d 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.jsnew file mode 100644index 0000000000..2a1bb7f176--- /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 (+ <div className="flex-none mx-3">+ <input id="comparison-input" type="checkbox" onChange={update} checked={query.comparison} className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500" />+ <label htmlFor="comparison-input" className="ml-1.5 font-medium text-xs md:text-sm text-gray-700 dark:text-white">Compare</label>+ </div>+ )+}++export default withRouter(ComparisonInput)diff --git a/assets/js/dashboard/historical.js b/assets/js/dashboard/historical.jsindex 486a5ecf48..524bcbab5d 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) {<Filters className="flex" site={props.site} query={props.query} history={props.history} /></div><Datepicker site={props.site} query={props.query} />+ <ComparisonInput site={props.site} query={props.query} /></div></div><VisitorGraph site={props.site} query={props.query} />diff --git a/assets/js/dashboard/query.js b/assets/js/dashboard/query.jsindex 45fc982744..6d338cf805 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.jsindex 543618d032..da747f30b3 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 Bodyif (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 = `<div class='text-gray-100 flex flex-col'><div class='flex justify-between items-center'><span class='font-semibold mr-4 text-lg'>${METRIC_LABELS[metric]}</span>+ ${tooltipData.comparisonDifference ? `<span class='font-semibold text-sm'>${tooltipData.comparisonDifference}%</span>` : ''}</div><div class='flex flex-col'><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>${renderBucketLabel(label)}</span>+ <span>${tooltipData.label}</span></span>- <span class='text-base font-bold'>${METRIC_FORMATTER[metric](point)}</span>+ <span class='text-base font-bold'>${tooltipData.formattedValue}</span>+ </div>++ ${tooltipData.comparisonLabel ? `<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 bg-gray-500'></div>+ <span>${tooltipData.comparisonLabel}</span>+ </span>+ <span class='text-base font-bold'>${tooltipData.formattedComparisonValue}</span></div></div><span class='font-semibold italic'>${graphData.interval === 'month' ? 'Click to view month' : graphData.interval === 'date' ? 'Click to view day' : ''}</span>- </div>+ </div>` : ''}`;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.jsindex 72efd06f80..902b5ccb58 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.propsconst 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.exindex 4eab322655..e8adff12d5 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 doselected_metric =if !params["metric"] || params["metric"] == "conversions" do- "visitors"+ :visitorselse- params["metric"]+ String.to_existing_atom(params["metric"])endtimeseries_query =@@ -109,21 +109,22 @@ defmodule PlausibleWeb.Api.StatsController doqueryend- 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 doendend+ 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) dofor label <- labels, into: %{} dointerval_start = Timex.beginning_of_week(label)diff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.exindex bb35bdb8be..a4403ea394 100644--- a/lib/plausible_web/controllers/stats_controller.ex+++ b/lib/plausible_web/controllers/stats_controller.ex@@ -311,7 +311,8 @@ defmodule PlausibleWeb.StatsController dodefp 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