Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Breakdown comparisons: Tooltip UX, arrows (#4719)

Karl-Aksel Puulmannb5d48a7347fd
diff --git a/assets/js/dashboard/query.ts b/assets/js/dashboard/query.ts
index c93e2b03dd..c9d3452201 100644
--- a/assets/js/dashboard/query.ts
+++ b/assets/js/dashboard/query.ts
@@ -55,6 +55,11 @@ export const queryDefaultValue = {
export type DashboardQuery = typeof queryDefaultValue
+export type BreakdownResultMeta = {
+ date_range_label: string
+ comparison_date_range_label?: string
+}
+
export function addFilter(
query: DashboardQuery,
filter: Filter
diff --git a/assets/js/dashboard/stats/graph/graph-tooltip.js b/assets/js/dashboard/stats/graph/graph-tooltip.js
index fffeec828c..046e6b651d 100644
--- a/assets/js/dashboard/stats/graph/graph-tooltip.js
+++ b/assets/js/dashboard/stats/graph/graph-tooltip.js
@@ -1,6 +1,9 @@
+import React from 'react'
+import { createRoot } from 'react-dom/client'
import dateFormatter from './date-formatter'
import { METRIC_LABELS } from './graph-util'
import { MetricFormatterShort } from '../reports/metric-formatter'
+import { ChangeArrow } from '../reports/change-arrow'
const renderBucketLabel = function(query, graphData, label, comparison = false) {
let isPeriodFull = graphData.full_intervals?.[label]
@@ -52,6 +55,9 @@ const buildTooltipData = function(query, graphData, metric, tooltipModel) {
return { label, formattedValue, comparisonLabel, formattedComparisonValue, comparisonDifference }
}
+
+let tooltipRoot
+
export default function GraphTooltip(graphData, metric, query) {
return (context) => {
const tooltipModel = context.tooltip
@@ -64,6 +70,7 @@ export default function GraphTooltip(graphData, metric, query) {
tooltipEl.style.display = 'none'
tooltipEl.style.opacity = 0
document.body.appendChild(tooltipEl)
+ tooltipRoot = createRoot(tooltipEl)
}
if (tooltipEl && offset && window.innerWidth < 768) {
@@ -81,42 +88,41 @@ export default function GraphTooltip(graphData, metric, query) {
if (tooltipModel.body) {
const tooltipData = buildTooltipData(query, graphData, metric, tooltipModel)
- tooltipEl.innerHTML = `
- <aside 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 ?
- `<div class="inline-flex items-center space-x-1">
- ${tooltipData.comparisonDifference > 0 ? `<span class="font-semibold text-sm text-green-500">&uarr;</span><span>${tooltipData.comparisonDifference}%</span>` : ""}
- ${tooltipData.comparisonDifference < 0 ? `<span class="font-semibold text-sm text-red-400">&darr;</span><span>${tooltipData.comparisonDifference * -1}%</span>` : ""}
- ${tooltipData.comparisonDifference == 0 ? `<span class="font-semibold text-sm">〰 0%</span>` : ""}
- </div>` : ''}
+ tooltipRoot.render(
+ <aside className="text-gray-100 flex flex-col">
+ <div className="flex justify-between items-center">
+ <span className="font-semibold mr-4 text-lg">{METRIC_LABELS[metric]}</span>
+ {tooltipData.comparisonDifference ? (
+ <div className="inline-flex items-center space-x-1">
+ <ChangeArrow metric={metric} change={tooltipData.comparisonDifference} />
+ </div>) : null}
</div>
- ${tooltipData.label ?
- `<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>${tooltipData.label}</span>
+ {tooltipData.label ? (
+ <div className="flex flex-col">
+ <div className="flex flex-row justify-between items-center">
+ <span className="flex items-center mr-4">
+ <div className="w-3 h-3 mr-1 rounded-full" style={{ backgroundColor: "rgba(101,116,205)" }}></div>
+ <span>{tooltipData.label}</span>
</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 className="text-base font-bold">{tooltipData.formattedValue}</span>
+ </div>
+
+ {tooltipData.comparisonLabel ? (
+ <div className="flex flex-row justify-between items-center">
+ <span className="flex items-center mr-4">
+ <div className="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>` : ""}
+ <span className="text-base font-bold">{tooltipData.formattedComparisonValue}</span>
+ </div>) : null}
</div>
+ ) : null}
- ${graphData.interval === "month" ? `<span class="font-semibold italic">Click to view month</span>` : ""}
- ${graphData.interval === "day" ? `<span class="font-semibold italic">Click to view day</span>` : ""}
+ {graphData.interval === "month" ? (<span className="font-semibold italic">Click to view month</span>) : null}
+ {graphData.interval === "day" ? (<span className="font-semibold italic">Click to view day</span>) : null}
</aside>
- `
+ )
}
tooltipEl.style.display = null
}
diff --git a/assets/js/dashboard/stats/modals/breakdown-modal.tsx b/assets/js/dashboard/stats/modals/breakdown-modal.tsx
index 1d56df1d82..ef7206831e 100644
--- a/assets/js/dashboard/stats/modals/breakdown-modal.tsx
+++ b/assets/js/dashboard/stats/modals/breakdown-modal.tsx
@@ -14,7 +14,7 @@ import {
useRememberOrderBy
} from '../../hooks/use-order-by'
import { Metric } from '../reports/metrics'
-import { DashboardQuery } from '../../query'
+import { BreakdownResultMeta, DashboardQuery } from '../../query'
import { ColumnConfiguraton } from '../../components/table'
import { BreakdownTable } from './breakdown-table'
import { useSiteContext } from '../../site-context'
@@ -30,7 +30,7 @@ export type ReportInfo = {
defaultOrder?: Order
}
-/**
+/**
BreakdownModal is for rendering the "Details" reports on the dashboard,
i.e. a breakdown by a single (non-time) dimension, with a given set of metrics.
@@ -79,6 +79,7 @@ export default function BreakdownModal<TListItem extends { name: string }>({
}) {
const site = useSiteContext()
const { query } = useQueryContext()
+ const [meta, setMeta] = useState<BreakdownResultMeta | undefined>(undefined)
const [search, setSearch] = useState('')
const defaultOrderBy = getStoredOrderBy({
@@ -97,7 +98,7 @@ export default function BreakdownModal<TListItem extends { name: string }>({
reportInfo
})
const apiState = usePaginatedGetAPI<
- { results: Array<TListItem> },
+ { results: Array<TListItem>; meta: BreakdownResultMeta },
[string, { query: DashboardQuery; search: string; orderBy: OrderBy }]
>({
key: [reportInfo.endpoint, { query, search, orderBy }],
@@ -122,7 +123,10 @@ export default function BreakdownModal<TListItem extends { name: string }>({
}
]
},
- afterFetchData,
+ afterFetchData: (response) => {
+ setMeta(response.meta)
+ afterFetchData?.(response)
+ },
afterFetchNextPage
})
@@ -148,7 +152,7 @@ export default function BreakdownModal<TListItem extends { name: string }>({
key: m.key,
width: m.width,
align: 'right',
- renderValue: m.renderValue,
+ renderValue: (item) => m.renderValue(item, meta),
onSort: m.sortable ? () => toggleSortByMetric(m) : undefined,
sortDirection: orderByDictionary[m.key]
})
diff --git a/assets/js/dashboard/stats/reports/change-arrow.test.tsx b/assets/js/dashboard/stats/reports/change-arrow.test.tsx
index eff8b7239b..eae2abeed2 100644
--- a/assets/js/dashboard/stats/reports/change-arrow.test.tsx
+++ b/assets/js/dashboard/stats/reports/change-arrow.test.tsx
@@ -4,6 +4,15 @@ import React from 'react'
import { render, screen } from '@testing-library/react'
import { ChangeArrow } from './change-arrow'
+jest.mock('@heroicons/react/24/solid', () => ({
+ ArrowUpRightIcon: ({ className }: { className: string }) => (
+ <span className={className}>↑</span>
+ ),
+ ArrowDownRightIcon: ({ className }: { className: string }) => (
+ <span className={className}>↓</span>
+ )
+}))
+
it('renders green for positive change', () => {
render(<ChangeArrow change={1} className="text-xs" metric="visitors" />)
@@ -58,3 +67,12 @@ it('renders with text hidden', () => {
expect(arrowElement).toHaveTextContent('↓')
expect(arrowElement.children[0]).toHaveClass('text-red-400')
})
+
+it('renders no content with text hidden and 0 change', () => {
+ render(
+ <ChangeArrow change={0} className="text-xs" metric="visitors" hideNumber />
+ )
+
+ const arrowElement = screen.getByTestId('change-arrow')
+ expect(arrowElement).toHaveTextContent('')
+})
diff --git a/assets/js/dashboard/stats/reports/change-arrow.tsx b/assets/js/dashboard/stats/reports/change-arrow.tsx
index 3f77e10558..959a5f33ff 100644
--- a/assets/js/dashboard/stats/reports/change-arrow.tsx
+++ b/assets/js/dashboard/stats/reports/change-arrow.tsx
@@ -3,6 +3,8 @@
import React from 'react'
import { Metric } from '../../../types/query-api'
import { numberShortFormatter } from '../../util/number-formatter'
+import { ArrowDownRightIcon, ArrowUpRightIcon } from '@heroicons/react/24/solid'
+import classNames from 'classnames'
export function ChangeArrow({
change,
@@ -19,31 +21,30 @@ export function ChangeArrow({
? null
: ` ${numberShortFormatter(Math.abs(change))}%`
- let content = null
+ let icon = null
+ const arrowClassName = classNames(
+ color(change, metric),
+ 'inline-block h-3 w-3 stroke-[1px] stroke-current'
+ )
if (change > 0) {
- const color = metric === 'bounce_rate' ? 'text-red-400' : 'text-green-500'
- content = (
- <>
- <span className={color + ' font-bold'}>&uarr;</span>
- {formattedChange}
- </>
- )
+ icon = <ArrowUpRightIcon className={arrowClassName} />
} else if (change < 0) {
- const color = metric === 'bounce_rate' ? 'text-green-500' : 'text-red-400'
- content = (
- <>
- <span className={color + ' font-bold'}>&darr;</span>
- {formattedChange}
- </>
- )
- } else if (change === 0) {
- content = <>&#12336;{formattedChange}</>
+ icon = <ArrowDownRightIcon className={arrowClassName} />
+ } else if (change === 0 && !hideNumber) {
+ icon = <>&#12336;</>
}
return (
<span className={className} data-testid="change-arrow">
- {content}
+ {icon}
+ {formattedChange}
</span>
)
}
+
+function color(change: number, metric: Metric) {
+ const invert = metric === 'bounce_rate'
+
+ return change > 0 != invert ? 'text-green-500' : 'text-red-400'
+}
diff --git a/assets/js/dashboard/stats/reports/list.js b/assets/js/dashboard/stats/reports/list.js
index 48474f4593..2908778e20 100644
--- a/assets/js/dashboard/stats/reports/list.js
+++ b/assets/js/dashboard/stats/reports/list.js
@@ -163,7 +163,7 @@ export default function ListReport({
afterFetchData(response)
}
- setState({ loading: false, list: response.results })
+ setState({ loading: false, list: response.results, meta: response.meta })
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [keyLabel, query])
@@ -316,7 +316,7 @@ export default function ListReport({
style={{ width: colMinWidth, minWidth: colMinWidth }}
>
<span className="font-medium text-sm dark:text-gray-200 text-right">
- {metric.renderValue(listItem)}
+ {metric.renderValue(listItem, state.meta)}
</span>
</div>
)
diff --git a/assets/js/dashboard/stats/reports/metric-value.test.tsx b/assets/js/dashboard/stats/reports/metric-value.test.tsx
index 612187bb80..8e562cbd0b 100644
--- a/assets/js/dashboard/stats/reports/metric-value.test.tsx
+++ b/assets/js/dashboard/stats/reports/metric-value.test.tsx
@@ -10,6 +10,11 @@ import {
import MetricValue from './metric-value'
import SiteContextProvider, { PlausibleSite } from '../../site-context'
+jest.mock('@heroicons/react/24/solid', () => ({
+ ArrowUpRightIcon: () => <>↑</>,
+ ArrowDownRightIcon: () => <>↓</>
+}))
+
const REVENUE = { long: '$1,659.50', short: '$1.7K' }
describe('single value', () => {
@@ -81,7 +86,14 @@ describe('comparisons', () => {
expect(screen.getByTestId('metric-value')).toHaveTextContent('10↑')
expect(screen.getByRole('tooltip')).toHaveTextContent(
- '10 vs. 5 visitors↑ 100%'
+ [
+ '10 visitors',
+ '↑ 100%',
+ '01 Aug - 31 Aug',
+ 'vs',
+ '5 visitors',
+ '01 July - 31 July'
+ ].join('')
)
})
@@ -92,7 +104,14 @@ describe('comparisons', () => {
expect(screen.getByTestId('metric-value')).toHaveTextContent('5↓')
expect(screen.getByRole('tooltip')).toHaveTextContent(
- '5 vs. 10 visitors↓ 50%'
+ [
+ '5 visitors',
+ '↓ 50%',
+ '01 Aug - 31 Aug',
+ 'vs',
+ '10 visitors',
+ '01 July - 31 July'
+ ].join('')
)
})
@@ -101,9 +120,16 @@ describe('comparisons', () => {
<MetricValue {...valueProps('visitors', 10, { value: 10, change: 0 })} />
)
- expect(screen.getByTestId('metric-value')).toHaveTextContent('10〰')
+ expect(screen.getByTestId('metric-value')).toHaveTextContent('10')
expect(screen.getByRole('tooltip')).toHaveTextContent(
- '10 vs. 10 visitors〰 0%'
+ [
+ '10 visitors',
+ '〰 0%',
+ '01 Aug - 31 Aug',
+ 'vs',
+ '10 visitors',
+ '01 July - 31 July'
+ ].join('')
)
})
@@ -116,7 +142,14 @@ describe('comparisons', () => {
)
expect(screen.getByRole('tooltip')).toHaveTextContent(
- '10 vs. 10 conversions〰 0%'
+ [
+ '10 conversions',
+ '〰 0%',
+ '01 Aug - 31 Aug',
+ 'vs',
+ '10 conversions',
+ '01 July - 31 July'
+ ].join('')
)
})
@@ -128,7 +161,16 @@ describe('comparisons', () => {
/>
)
- expect(screen.getByRole('tooltip')).toHaveTextContent('10% vs. 10%〰 0%')
+ expect(screen.getByRole('tooltip')).toHaveTextContent(
+ [
+ '10% ',
+ '〰 0%',
+ '01 Aug - 31 Aug',
+ 'vs',
+ '10% ',
+ '01 July - 31 July'
+ ].join('')
+ )
})
it('renders with custom formatter', async () => {
@@ -141,7 +183,14 @@ describe('comparisons', () => {
expect(screen.getByTestId('metric-value')).toHaveTextContent('10$↑')
expect(screen.getByRole('tooltip')).toHaveTextContent(
- '10$ vs. 5$ test↑ 100%'
+ [
+ '10$ test',
+ '↑ 100%',
+ '01 Aug - 31 Aug',
+ 'vs',
+ '5$ test',
+ '01 July - 31 July'
+ ].join('')
)
})
@@ -155,9 +204,16 @@ describe('comparisons', () => {
/>
)
- expect(screen.getByTestId('metric-value')).toHaveTextContent('$1.7K〰')
+ expect(screen.getByTestId('metric-value')).toHaveTextContent('$1.7K')
expect(screen.getByRole('tooltip')).toHaveTextContent(
- '$1,659.50 vs. $1,659.50 average_revenue〰 0%'
+ [
+ '$1,659.50 average_revenue',
+ '〰 0%',
+ '01 Aug - 31 Aug',
+ 'vs',
+ '$1,659.50 average_revenue',
+ '01 July - 31 July'
+ ].join('')
)
})
@@ -190,6 +246,10 @@ function valueProps<T>(
}
}
},
+ meta: {
+ date_range_label: '01 Aug - 31 Aug',
+ comparison_date_range_label: '01 July - 31 July'
+ },
renderLabel: (_query: unknown) => metric.toUpperCase()
} as any /* eslint-disable-line @typescript-eslint/no-explicit-any */
}
diff --git a/assets/js/dashboard/stats/reports/metric-value.tsx b/assets/js/dashboard/stats/reports/metric-value.tsx
index b9187ef0e5..256c2aba1f 100644
--- a/assets/js/dashboard/stats/reports/metric-value.tsx
+++ b/assets/js/dashboard/stats/reports/metric-value.tsx
@@ -9,7 +9,7 @@ import {
MetricFormatterShort,
ValueType
} from './metric-formatter'
-import { DashboardQuery } from '../../query'
+import { BreakdownResultMeta, DashboardQuery } from '../../query'
import { useQueryContext } from '../../query-context'
import { PlausibleSite, useSiteContext } from '../../site-context'
@@ -42,6 +42,7 @@ export default function MetricValue(props: {
metric: Metric
renderLabel: (query: DashboardQuery) => string
formatter?: (value: ValueType) => string
+ meta: BreakdownResultMeta
}) {
const { query } = useQueryContext()
const site = useSiteContext()
@@ -69,13 +70,13 @@ export default function MetricValue(props: {
/>
}
>
- <span data-testid="metric-value">
+ <span className="cursor-default" data-testid="metric-value">
{shortFormatter(value)}
{comparison ? (
<ChangeArrow
change={comparison.change}
metric={metric}
- className="pl-2"
+ className="inline-block pl-1 w-4"
hideNumber
/>
) : null}
@@ -89,13 +90,15 @@ function ComparisonTooltipContent({
comparison,
metric,
metricLabel,
- formatter
+ formatter,
+ meta
}: {
value: ValueType
comparison: { value: ValueType; change: number } | null
metric: Metric
metricLabel: string
formatter?: (value: ValueType) => string
+ meta: BreakdownResultMeta
}) {
const longFormatter = formatter ?? MetricFormatterLong[metric]
@@ -109,17 +112,36 @@ function ComparisonTooltipContent({
if (comparison) {
return (
- <div className="whitespace-nowrap">
- {longFormatter(value)} vs. {longFormatter(comparison.value)}
- {label}
- <ChangeArrow
- metric={metric}
- change={comparison.change}
- className="pl-4 text-xs text-gray-100"
- />
+ <div className="text-left whitespace-nowrap py-1 space-y-2">
+ <div>
+ <div className="flex items-center">
+ <span className="font-bold text-base">
+ {longFormatter(value)} {label}
+ </span>
+ <ChangeArrow
+ metric={metric}
+ change={comparison.change}
+ className="pl-4 text-xs text-gray-100"
+ />
+ </div>
+ <div className="font-normal text-xs">{meta.date_range_label}</div>
+ </div>
+ <div>vs</div>
+ <div>
+ <div className="font-bold text-base">
+ {longFormatter(comparison.value)} {label}
+ </div>
+ <div className="font-normal text-xs">
+ {meta.comparison_date_range_label}
+ </div>
+ </div>
</div>
)
} else {
- return <div className="whitespace-nowrap">{longFormatter(value)}</div>
+ return (
+ <div className="whitespace-nowrap">
+ {longFormatter(value)} {label}
+ </div>
+ )
}
}
diff --git a/assets/js/dashboard/stats/reports/metrics.js b/assets/js/dashboard/stats/reports/metrics.js
index 81a1613956..5ea1a227e8 100644
--- a/assets/js/dashboard/stats/reports/metrics.js
+++ b/assets/js/dashboard/stats/reports/metrics.js
@@ -45,12 +45,13 @@ export class Metric {
this.renderValue = this.renderValue.bind(this)
}
- renderValue(listItem) {
+ renderValue(listItem, meta) {
return (
<MetricValue
listItem={listItem}
metric={this.key}
renderLabel={this.renderLabel}
+ meta={meta}
formatter={this.formatter}
/>
)
@@ -97,7 +98,7 @@ export const createVisitors = (props) => {
export const createConversionRate = (props) => {
const renderLabel = (_query) => 'CR'
return new Metric({
- width: 'w-16',
+ width: 'w-24',
...props,
key: 'conversion_rate',
renderLabel,
@@ -108,7 +109,7 @@ export const createConversionRate = (props) => {
export const createPercentage = (props) => {
const renderLabel = (_query) => '%'
return new Metric({
- width: 'w-16',
+ width: 'w-24',
...props,
key: 'percentage',
renderLabel,
diff --git a/assets/js/dashboard/util/url-search-params.test.ts b/assets/js/dashboard/util/url-search-params.test.ts
index fb47ab15a9..fb73c01808 100644
--- a/assets/js/dashboard/util/url-search-params.test.ts
+++ b/assets/js/dashboard/util/url-search-params.test.ts
@@ -11,6 +11,11 @@ import {
stringifySearchEntry
} from './url'
+beforeEach(() => {
+ // Silence logs in tests
+ jest.spyOn(console, 'error').mockImplementation(jest.fn())
+})
+
describe('using json URL parsing with URLSearchParams intermediate', () => {
it.each([['#'], ['&'], ['=']])('throws on special symbol %p', (s) => {
const searchString = `?param=${encodeURIComponent(s)}`
diff --git a/lib/plausible/stats/breakdown.ex b/lib/plausible/stats/breakdown.ex
index 81c2dddfc5..6e44c8437e 100644
--- a/lib/plausible/stats/breakdown.ex
+++ b/lib/plausible/stats/breakdown.ex
@@ -8,7 +8,7 @@ defmodule Plausible.Stats.Breakdown do
use Plausible.ClickhouseRepo
use Plausible.Stats.SQL.Fragments
- alias Plausible.Stats.{Query, QueryRunner, QueryOptimizer}
+ alias Plausible.Stats.{Query, QueryRunner, QueryOptimizer, Comparisons}
def breakdown(
site,
@@ -42,6 +42,27 @@ defmodule Plausible.Stats.Breakdown do
|> build_breakdown_result(query_with_metrics, metrics)
end
+ def formatted_date_ranges(query) do
+ formatted = %{
+ date_range_label: format_date_range(query)
+ }
+
+ if query.include.comparisons do
+ comparison_date_range_label =
+ query
+ |> Comparisons.get_comparison_query(query.include.comparisons)
+ |> format_date_range()
+
+ Map.put(
+ formatted,
+ :comparison_date_range_label,
+ comparison_date_range_label
+ )
+ else
+ formatted
+ end
+ end
+
defp build_breakdown_result(query_result, query, metrics) do
dimension_keys = query.dimensions |> Enum.map(&result_key/1)
@@ -135,4 +156,28 @@ defmodule Plausible.Stats.Breakdown do
end
defp dimension_filters(_), do: []
+
+ defp format_date_range(%Query{} = query) do
+ year = query.now.year
+ %Date.Range{first: first, last: last} = Query.date_range(query, trim_trailing: true)
+
+ cond do
+ first == last ->
+ strfdate(first, first.year != year)
+
+ first.year == last.year ->
+ "#{strfdate(first, false)} - #{strfdate(last, year != last.year)}"
+
+ true ->
+ "#{strfdate(first, true)} - #{strfdate(last, true)}"
+ end
+ end
+
+ defp strfdate(date, true = _include_year) do
+ Calendar.strftime(date, "%-d %b %Y")
+ end
+
+ defp strfdate(date, false = _include_year) do
+ Calendar.strftime(date, "%-d %b")
+ end
end
diff --git a/lib/plausible/stats/comparisons.ex b/lib/plausible/stats/comparisons.ex
index 4dc7d4d1a6..647658855b 100644
--- a/lib/plausible/stats/comparisons.ex
+++ b/lib/plausible/stats/comparisons.ex
@@ -97,19 +97,19 @@ defmodule Plausible.Stats.Comparisons do
end
defp get_comparison_date_range(source_query, %{mode: "year_over_year"} = options) do
- source_date_range = Query.date_range(source_query)
+ source_date_range = Query.date_range(source_query, trim_trailing: true)
start_date = Date.add(source_date_range.first, -365)
- end_date = earliest(source_date_range.last, source_query.now) |> Date.add(-365)
+ end_date = source_date_range.last |> Date.add(-365)
Date.range(start_date, end_date)
|> maybe_match_day_of_week(source_date_range, options)
end
defp get_comparison_date_range(source_query, %{mode: "previous_period"} = options) do
- source_date_range = Query.date_range(source_query)
+ source_date_range = Query.date_range(source_query, trim_trailing: true)
- last = earliest(source_date_range.last, source_query.now)
+ last = source_date_range.last
diff_in_days = Date.diff(source_date_range.first, last) - 1
new_first = Date.add(source_date_range.first, diff_in_days)
@@ -123,10 +123,6 @@ defmodule Plausible.Stats.Comparisons do
DateTimeRange.to_date_range(options.date_range, source_query.timezone)
end
- defp earliest(a, b) do
- if Date.compare(a, b) in [:eq, :lt], do: a, else: b
- end
-
defp maybe_match_day_of_week(comparison_date_range, source_date_range, options) do
if options[:match_day_of_week] do
day_to_match = Date.day_of_week(source_date_range.first)
diff --git a/lib/plausible/stats/query.ex b/lib/plausible/stats/query.ex
index 0c7430b7c2..23b0fbfef2 100644
--- a/lib/plausible/stats/query.ex
+++ b/lib/plausible/stats/query.ex
@@ -60,8 +60,21 @@ defmodule Plausible.Stats.Query do
end
end
- def date_range(query) do
- Plausible.Stats.DateTimeRange.to_date_range(query.utc_time_range, query.timezone)
+ def date_range(query, options \\ []) do
+ date_range = Plausible.Stats.DateTimeRange.to_date_range(query.utc_time_range, query.timezone)
+
+ if Keyword.get(options, :trim_trailing) do
+ Date.range(
+ date_range.first,
+ earliest(date_range.last, query.now)
+ )
+ else
+ date_range
+ end
+ end
+
+ defp earliest(a, b) do
+ if Date.compare(a, b) in [:eq, :lt], do: a, else: b
end
def set(query, keywords) do
diff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.ex
index e21b98f1f4..8794ea7500 100644
--- a/lib/plausible_web/controllers/api/stats_controller.ex
+++ b/lib/plausible_web/controllers/api/stats_controller.ex
@@ -474,6 +474,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: res,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -496,6 +497,7 @@ defmodule PlausibleWeb.Api.StatsController do
json(conn, %{
results: res,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -576,6 +578,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: res,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -603,6 +606,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: res,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -630,6 +634,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: res,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -657,6 +662,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: res,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -684,6 +690,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: res,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -711,6 +718,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: res,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -794,6 +802,7 @@ defmodule PlausibleWeb.Api.StatsController do
json(conn, %{
results: referrers,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -826,6 +835,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: pages,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -860,6 +870,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: entry_pages,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -895,6 +906,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: exit_pages,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -981,6 +993,7 @@ defmodule PlausibleWeb.Api.StatsController do
json(conn, %{
results: countries,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -1019,6 +1032,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: regions,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -1062,6 +1076,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: cities,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -1093,6 +1108,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: browsers,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -1133,6 +1149,7 @@ defmodule PlausibleWeb.Api.StatsController do
json(conn, %{
results: results,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -1164,6 +1181,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: systems,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -1204,6 +1222,7 @@ defmodule PlausibleWeb.Api.StatsController do
json(conn, %{
results: results,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -1235,6 +1254,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: sizes,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -1267,6 +1287,7 @@ defmodule PlausibleWeb.Api.StatsController do
else
json(conn, %{
results: conversions,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
skip_imported_reason: query.skip_imported_reason
})
end
@@ -1340,7 +1361,11 @@ defmodule PlausibleWeb.Api.StatsController do
Stats.breakdown(site, query, metrics, pagination)
|> transform_keys(%{prop_key => :name})
- %{results: props, skip_imported_reason: query.skip_imported_reason}
+ %{
+ results: props,
+ meta: Stats.Breakdown.formatted_date_ranges(query),
+ skip_imported_reason: query.skip_imported_reason
+ }
end
def current_visitors(conn, _) do
diff --git a/lib/plausible_web/live/sites.ex b/lib/plausible_web/live/sites.ex
index cf63a54097..16036c4e07 100644
--- a/lib/plausible_web/live/sites.ex
+++ b/lib/plausible_web/live/sites.ex
@@ -325,12 +325,40 @@ defmodule PlausibleWeb.Live.Sites do
attr :change, :integer, required: true
+ # Related React component: <ChangeArrow />
def percentage_change(assigns) do
~H"""
<p class="dark:text-gray-100">
<span :if={@change == 0} class="font-semibold">〰</span>
- <span :if={@change > 0} class="font-semibold text-green-500">↑</span>
- <span :if={@change < 0} class="font-semibold text-red-400">↓</span>
+ <svg
+ :if={@change > 0}
+ xmlns="http://www.w3.org/2000/svg"
+ fill="currentColor"
+ viewBox="0 0 24 24"
+ class="text-green-500 h-3 w-3 inline-block stroke-[1px] stroke-current"
+ >
+ <path
+ fill-rule="evenodd"
+ d="M8.25 3.75H19.5a.75.75 0 01.75.75v11.25a.75.75 0 01-1.5 0V6.31L5.03 20.03a.75.75 0 01-1.06-1.06L17.69 5.25H8.25a.75.75 0 010-1.5z"
+ clip-rule="evenodd"
+ >
+ </path>
+ </svg>
+ <svg
+ :if={@change < 0}
+ xmlns="http://www.w3.org/2000/svg"
+ fill="currentColor"
+ viewBox="0 0 24 24"
+ class="text-red-400 h-3 w-3 inline-block stroke-[1px] stroke-current"
+ >
+ <path
+ fill-rule="evenodd"
+ d="M3.97 3.97a.75.75 0 011.06 0l13.72 13.72V8.25a.75.75 0 011.5 0V19.5a.75.75 0 01-.75.75H8.25a.75.75 0 010-1.5h9.44L3.97 5.03a.75.75 0 010-1.06z"
+ clip-rule="evenodd"
+ >
+ </path>
+ </svg>
+
<%= abs(@change) %>%
</p>
"""
diff --git a/test/plausible_web/controllers/api/stats_controller/browsers_test.exs b/test/plausible_web/controllers/api/stats_controller/browsers_test.exs
index 0bd3d14cc5..def994fea0 100644
--- a/test/plausible_web/controllers/api/stats_controller/browsers_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/browsers_test.exs
@@ -229,6 +229,11 @@ defmodule PlausibleWeb.Api.StatsController.BrowsersTest do
}
}
]
+
+ assert json_response(conn, 200)["meta"] == %{
+ "date_range_label" => "7 Jan - 13 Jan 2021",
+ "comparison_date_range_label" => "31 Dec 2020 - 6 Jan 2021"
+ }
end
test "returns comparisons with limit", %{conn: conn, site: site} do
@@ -260,6 +265,11 @@ defmodule PlausibleWeb.Api.StatsController.BrowsersTest do
}
}
]
+
+ assert json_response(conn, 200)["meta"] == %{
+ "date_range_label" => "7 Jan - 13 Jan 2021",
+ "comparison_date_range_label" => "31 Dec 2020 - 6 Jan 2021"
+ }
end
end
diff --git a/test/plausible_web/controllers/api/stats_controller/sources_test.exs b/test/plausible_web/controllers/api/stats_controller/sources_test.exs
index 3071962eb6..10f4f8e8fb 100644
--- a/test/plausible_web/controllers/api/stats_controller/sources_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/sources_test.exs
@@ -87,6 +87,10 @@ defmodule PlausibleWeb.Api.StatsController.SourcesTest do
%{"name" => "Google", "visitors" => 2},
%{"name" => "DuckDuckGo", "visitors" => 1}
]
+
+ assert json_response(conn, 200)["meta"] == %{
+ "date_range_label" => "1 Jan 2021"
+ }
end
test "returns top sources with :is_not filter on custom pageview props", %{
@@ -663,6 +667,11 @@ defmodule PlausibleWeb.Api.StatsController.SourcesTest do
}
}
]
+
+ assert json_response(conn, 200)["meta"] == %{
+ "date_range_label" => "2 Jan 2021",
+ "comparison_date_range_label" => "1 Jan 2021"
+ }
end
end