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
Another iteration of Dashboard.Live.Pages (#5986)
RobertJoonas997546fc4fed
diff --git a/assets/js/dashboard/components/liveview-portal.tsx b/assets/js/dashboard/components/liveview-portal.tsxindex 23be924654..838009f6d0 100644--- a/assets/js/dashboard/components/liveview-portal.tsx+++ b/assets/js/dashboard/components/liveview-portal.tsx@@ -7,29 +7,58 @@import React from 'react'import classNames from 'classnames'+import { ReportHeader } from '../stats/reports/report-header'+import { ReportLayout } from '../stats/reports/report-layout'+import { TabButton, TabWrapper } from './tabs'+import { MoreLinkState } from '../stats/more-link-state'+import MoreLink from '../stats/more-link'-const MIN_HEIGHT = 380+const MIN_HEIGHT = 356type LiveViewPortalProps = {id: string+ tabs: { value: string; label: string }[]+ storageKey: stringclassName?: string}export const LiveViewPortal = React.memo(- function ({ id, className }: LiveViewPortalProps) {+ function ({ id, tabs, storageKey, className }: LiveViewPortalProps) {+ const activeTab = localStorage.getItem(storageKey) || 'pages'+return (<divid={id}className={classNames('group', className)}style={{ width: '100%', border: '0', minHeight: MIN_HEIGHT }}>- <div- className="w-full flex flex-col justify-center group-has-[[data-phx-teleported]]:hidden"- style={{ minHeight: MIN_HEIGHT }}- >- <div className="mx-auto loading">- <div />- </div>+ <div className={'group-has-[[data-phx-teleported]]:hidden'}>+ <ReportLayout>+ <ReportHeader>+ <div className="flex gap-x-3">+ <TabWrapper>+ {tabs.map(({ value, label }) => (+ <TabButton+ key={value}+ active={activeTab === value}+ onClick={() => {}}+ >+ {label}+ </TabButton>+ ))}+ </TabWrapper>+ </div>+ <MoreLink state={MoreLinkState.LOADING} linkProps={undefined} />+ </ReportHeader>+ <div+ className="w-full flex flex-col justify-center"+ style={{ minHeight: `${MIN_HEIGHT}px` }}+ >+ <div className="mx-auto loading">+ <div></div>+ </div>+ </div>+ </ReportLayout></div></div>)diff --git a/assets/js/dashboard/index.tsx b/assets/js/dashboard/index.tsxindex 72b947896a..0262471c01 100644--- a/assets/js/dashboard/index.tsx+++ b/assets/js/dashboard/index.tsx@@ -9,9 +9,10 @@ import { TopBar } from './nav-menu/top-bar'import Behaviours from './stats/behaviours'import { useQueryContext } from './query-context'import { useSiteContext } from './site-context'-import { isRealTimeDashboard } from './util/filters'+import { hasConversionGoalFilter, isRealTimeDashboard } from './util/filters'import { useAppNavigate } from './navigation/use-app-navigate'import { parseSearch } from './util/url-search-params'+import { getDomainScopedStorageKey } from './util/storage'function DashboardStats({importedDataInView,@@ -22,6 +23,7 @@ function DashboardStats({}) {const navigate = useAppNavigate()const site = useSiteContext()+ const { query } = useQueryContext()// Handler for navigation events delegated from LiveView dashboard.// Necessary to emulate navigation events in LiveView with pushState@@ -57,6 +59,17 @@ function DashboardStats({{site.flags.live_dashboard ? (<LiveViewPortalid="pages-breakdown-live"+ tabs={[+ {+ label: hasConversionGoalFilter(query)+ ? 'Conversion pages'+ : 'Top pages',+ value: 'pages'+ },+ { label: 'Entry pages', value: 'entry-pages' },+ { label: 'Exit pages', value: 'exit-pages' }+ ]}+ storageKey={getDomainScopedStorageKey('pageTab', site.domain)}className="w-full h-full border-0 overflow-hidden"/>) : (diff --git a/assets/js/liveview/dashboard_tabs.js b/assets/js/liveview/dashboard_tabs.jsindex 476fbc9ebf..50b2725329 100644--- a/assets/js/liveview/dashboard_tabs.js+++ b/assets/js/liveview/dashboard_tabs.js@@ -17,27 +17,29 @@ export default buildHook({this.addListener('click', this.el, (e) => {const button = e.target.closest('button')const tabKey = button && button.dataset.tabKey- const span = button && button.querySelector('span')- if (span && span.dataset.active === 'false') {- const reportLabel = button.dataset.reportLabel+ if (button && button.closest('div').dataset.active === 'false') {const storageKey = button.dataset.storageKeyconst target = button.dataset.target- const tile = this.el.closest('[data-tile]')- const title = tile.querySelector('[data-title]')- title.innerText = reportLabel-- this.el.querySelectorAll(`button[data-tab-key] span`).forEach((s) => {- this.js().setAttribute(s, 'data-active', 'false')+ this.el.querySelectorAll(`button[data-tab-key]`).forEach((b) => {+ if (b.dataset.tabKey === tabKey) {+ this.js().setAttribute(b.closest('div'), 'data-active', 'true')+ this.js().setAttribute(+ b.querySelector('span'),+ 'data-active',+ 'true'+ )+ } else {+ this.js().setAttribute(b.closest('div'), 'data-active', 'false')+ this.js().setAttribute(+ b.querySelector('span'),+ 'data-active',+ 'false'+ )+ }})- this.js().setAttribute(- button.querySelector('span'),- 'data-active',- 'true'- )-if (storageKey) {localStorage.setItem(`${storageKey}__${domain}`, tabKey)}diff --git a/lib/plausible/stats/dashboard_query_parser.ex b/lib/plausible/stats/dashboard/query_parser.exsimilarity index 98%rename from lib/plausible/stats/dashboard_query_parser.exrename to lib/plausible/stats/dashboard/query_parser.exindex 4b95d9fe91..dff9f08d8a 100644--- a/lib/plausible/stats/dashboard_query_parser.ex+++ b/lib/plausible/stats/dashboard/query_parser.ex@@ -1,4 +1,4 @@-defmodule Plausible.Stats.DashboardQueryParser do+defmodule Plausible.Stats.Dashboard.QueryParser do@moduledoc """Parses a dashboard query string into `%ParsedQueryParams{}`. Note that`metrics` and `dimensions` do not exist at this step yet, and are expected@@ -13,7 +13,7 @@ defmodule Plausible.Stats.DashboardQueryParser do# is false. Even if we don't want to include imported data, we# might still want to know whether imported data can be toggled# on/off on the dashboard.- imports_meta: true,+ imports_meta: false,time_labels: false,total_rows: false,trim_relative_date_range: true,diff --git a/lib/plausible/stats/dashboard_query_serializer.ex b/lib/plausible/stats/dashboard/query_serializer.exsimilarity index 94%rename from lib/plausible/stats/dashboard_query_serializer.exrename to lib/plausible/stats/dashboard/query_serializer.exindex 7790c1e4ac..dcaa2fac68 100644--- a/lib/plausible/stats/dashboard_query_serializer.ex+++ b/lib/plausible/stats/dashboard/query_serializer.ex@@ -1,10 +1,10 @@-defmodule Plausible.Stats.DashboardQuerySerializer do+defmodule Plausible.Stats.Dashboard.QuerySerializer do@moduledoc """Takes a `%ParsedQueryParams{}` struct and turns it into a querystring."""- alias Plausible.Stats.{ParsedQueryParams, DashboardQueryParser, QueryInclude}+ alias Plausible.Stats.{ParsedQueryParams, Dashboard, QueryInclude}def serialize(%ParsedQueryParams{} = params, segments \\ []) doparams@@ -62,7 +62,7 @@ defmodule Plausible.Stats.DashboardQuerySerializer dodefp get_serialized_fields(_, _), do: []defp get_serialized_fields_from_include(:imports, %QueryInclude{} = include) do- if include.imports == DashboardQueryParser.default_include().imports do+ if include.imports == Dashboard.QueryParser.default_include().imports do[]else[{"with_imported", to_string(include.imports)}]@@ -88,7 +88,7 @@ defmodule Plausible.Stats.DashboardQuerySerializer dodefp get_serialized_fields_from_include(:compare_match_day_of_week, include) doif include.compare_match_day_of_week ==- DashboardQueryParser.default_include().compare_match_day_of_week do+ Dashboard.QueryParser.default_include().compare_match_day_of_week do[]else[{"match_day_of_week", to_string(include.compare_match_day_of_week)}]diff --git a/lib/plausible/stats/dashboard/utils.ex b/lib/plausible/stats/dashboard/utils.exnew file mode 100644index 0000000000..78ccdaa702--- /dev/null+++ b/lib/plausible/stats/dashboard/utils.ex@@ -0,0 +1,47 @@+defmodule Plausible.Stats.Dashboard.Utils do+ @moduledoc """+ Shared utilities by different dashboard reports.+ """++ alias Plausible.Site+ alias Plausible.Stats.{Dashboard, ParsedQueryParams}++ def page_external_link_fn_for(site) do+ with true <- Plausible.Sites.regular?(site),+ [domain | _] <- String.split(site.domain, "/"),+ {:ok, domain} <- idna_encode(domain),+ {:ok, uri} <- URI.new("https://#{domain}/") do+ fn item ->+ "https://#{uri.host}#{hd(item.dimensions)}"+ end+ else+ _ -> nil+ end+ end++ def dashboard_route(%Site{} = site, %ParsedQueryParams{} = params, opts) do+ path = Keyword.get(opts, :path, "")++ params =+ case Keyword.get(opts, :filter) do+ nil -> params+ filter -> ParsedQueryParams.add_or_replace_filter(params, filter)+ end++ query_string =+ case Dashboard.QuerySerializer.serialize(params) do+ "" -> ""+ query_string -> "?" <> query_string+ end++ "/" <> site.domain <> path <> query_string+ end++ defp idna_encode(domain) do+ try do+ {:ok, domain |> String.to_charlist() |> :idna.encode() |> IO.iodata_to_binary()}+ catch+ _ -> {:error, :invalid_domain}+ end+ end+enddiff --git a/lib/plausible/stats/metrics.ex b/lib/plausible/stats/metrics.exindex d835c11418..8023d5bd0b 100644--- a/lib/plausible/stats/metrics.ex+++ b/lib/plausible/stats/metrics.ex@@ -66,6 +66,7 @@ defmodule Plausible.Stats.Metrics dodef dashboard_metric_label(:visitors, _context), do: "Visitors"def dashboard_metric_label(:conversion_rate, _context), do: "CR"+ def dashboard_metric_label(:group_conversion_rate, _context), do: "CR"def dashboard_metric_label(metric, _context), do: "#{metric}"enddiff --git a/lib/plausible_web/live/components/dashboard/base.ex b/lib/plausible_web/live/components/dashboard/base.exindex b44167d25b..096654daf9 100644--- a/lib/plausible_web/live/components/dashboard/base.ex+++ b/lib/plausible_web/live/components/dashboard/base.ex@@ -5,34 +5,17 @@ defmodule PlausibleWeb.Components.Dashboard.Base douse PlausibleWeb, :component- alias Plausible.Stats.DashboardQuerySerializer- alias Plausible.Stats.ParsedQueryParams-- attr :site, Plausible.Site, required: true- attr :params, :map, required: true- attr :path, :string, default: ""+ attr :to, :string, required: trueattr :class, :string, default: ""attr :rest, :globalslot :inner_block, required: truedef dashboard_link(assigns) do- query_string = DashboardQuerySerializer.serialize(assigns.params)- url = "/" <> assigns.site.domain <> assigns.path-- url =- if query_string != "" do- url <> "?" <> query_string- else- url- end-- assigns = assign(assigns, :url, url)-~H"""<.linkdata-type="dashboard-link"- patch={@url}+ patch={@to}class={@class}{@rest}>@@ -41,26 +24,6 @@ defmodule PlausibleWeb.Components.Dashboard.Base do"""end- attr :site, Plausible.Site, required: true- attr :params, :map, required: true- attr :filter, :list, required: true- attr :class, :string, default: ""- attr :rest, :global-- slot :inner_block, required: true-- def filter_link(assigns) do- params = ParsedQueryParams.add_or_replace_filter(assigns.params, assigns.filter)-- assigns = assign(assigns, :params, params)-- ~H"""- <.dashboard_link site={@site} params={@params} class={@class} {@rest}>- {render_slot(@inner_block)}- </.dashboard_link>- """- end-attr :style, :string, default: ""attr :background_class, :string, default: ""attr :width, :integer, required: truediff --git a/lib/plausible_web/live/components/dashboard/imported_data_warnings.ex b/lib/plausible_web/live/components/dashboard/imported_data_warnings.exnew file mode 100644index 0000000000..4cf0b9df64--- /dev/null+++ b/lib/plausible_web/live/components/dashboard/imported_data_warnings.ex@@ -0,0 +1,29 @@+defmodule PlausibleWeb.Components.Dashboard.ImportedDataWarnings do+ @moduledoc false++ use PlausibleWeb, :component+ alias Phoenix.LiveView.AsyncResult+ alias Plausible.Stats.QueryResult++ def unsupported_filters(assigns) do+ show? =+ case assigns.query_result do+ %AsyncResult{result: %QueryResult{meta: meta}} ->+ meta[:imports_skip_reason] == :unsupported_query++ _ ->+ false+ end++ assigns = assign(assigns, :show?, show?)++ ~H"""+ <div :if={@show?} data-test-id="unsupported-filters-warning">+ <span class="hidden">+ Imported data is excluded due to the applied filters+ </span>+ <Heroicons.exclamation_circle class="mb-1 size-4.5 text-gray-500 dark:text-gray-400" />+ </div>+ """+ end+enddiff --git a/lib/plausible_web/live/components/dashboard/metric.ex b/lib/plausible_web/live/components/dashboard/metric.exindex 62fa1f7e0b..d7a191f84a 100644--- a/lib/plausible_web/live/components/dashboard/metric.ex+++ b/lib/plausible_web/live/components/dashboard/metric.ex@@ -7,7 +7,8 @@ defmodule PlausibleWeb.Components.Dashboard.Metric do@formatters %{visitors: :number_short,- conversion_rate: :percentage+ conversion_rate: :percentage,+ group_conversion_rate: :percentage}attr :name, :atom, required: truediff --git a/lib/plausible_web/live/components/dashboard/report_list.ex b/lib/plausible_web/live/components/dashboard/report_list.exindex 474748c207..80d32e1fcf 100644--- a/lib/plausible_web/live/components/dashboard/report_list.ex+++ b/lib/plausible_web/live/components/dashboard/report_list.ex@@ -8,9 +8,10 @@ defmodule PlausibleWeb.Components.Dashboard.ReportList doalias PlausibleWeb.Components.Dashboard.Basealias PlausibleWeb.Components.Dashboard.Metricalias Plausible.Stats.QueryResult+ alias Plausible.Stats.Dashboard.Utils@max_items 9- @min_height 380+ @min_height 356@row_height 32@row_gap_height 4@data_container_height (@row_height + @row_gap_height) * (@max_items - 1) + @row_height@@ -44,10 +45,10 @@ defmodule PlausibleWeb.Components.Dashboard.ReportList do)~H"""- <.no_data :if={@empty?} min_height={@min_height} />+ <.no_data :if={@empty?} min_height={@min_height} data_test_id={@data_test_id} /><div :if={not @empty?} class="h-full flex flex-col" data-test-id={@data_test_id}>- <div style={"row-height: #{@row_height}px;"}>+ <div style={"min-height: #{@row_height}px;"}><.report_headerkey_label={@key_label}metric_labels={@metric_labels}@@ -72,14 +73,6 @@ defmodule PlausibleWeb.Components.Dashboard.ReportList docol_min_width={@col_min_width}/></div>-- <div class="w-full text-center">- <.details_link- site={@site}- params={@params}- path="/pages"- />- </div></div>"""end@@ -88,6 +81,7 @@ defmodule PlausibleWeb.Components.Dashboard.ReportList dodefp no_data(assigns) do~H"""<div+ data-test-id={@data_test_id}class="w-full h-full flex flex-col justify-center group-has-[.tile-tabs.phx-hook-loading]:hidden"style={"min-height: #{@min_height}px;"}>@@ -104,30 +98,34 @@ defmodule PlausibleWeb.Components.Dashboard.ReportList doassigns = assign(assigns, :url, url)~H"""- <.link+ <a:if={@url}target="_blank"rel="noreferrer"href={@url}- class="w-4 h-4 invisible group-hover:visible"+ class="invisible md:group-hover/row:visible"><svg- class="inline w-full h-full ml-1 -mt-1 text-gray-600 dark:text-gray-400"- fill="currentColor"- viewBox="0 0 20 20"+ xmlns="http://www.w3.org/2000/svg"+ fill="none"+ viewBox="0 0 24 24"+ class="inline size-3.5 mb-0.5 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200">- <path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z">- </path>- <path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z">- </path>+ <path+ stroke="currentColor"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="2"+ d="M9 5H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4M12 12l9-9-.303.303M14 3h7v7"+ /></svg>- </.link>+ </a>"""enddefp report_header(assigns) do~H"""- <div class="pt-3 w-full text-xs font-bold tracking-wide text-gray-500 flex items-center dark:text-gray-400">+ <div class="pt-3 w-full text-xs font-medium text-gray-500 flex items-center dark:text-gray-400"><span data-test-id="report-list-0-0" class="grow truncate">{@key_label}</span><div:for={{metric_label, index} <- Enum.with_index(@metric_labels)}@@ -145,26 +143,22 @@ defmodule PlausibleWeb.Components.Dashboard.ReportList do~H"""<div style={"min-height: #{@row_height}px;"}><div- class="group flex w-full items-center hover:bg-gray-100/60 dark:hover:bg-gray-850 rounded-sm transition-colors duration-150"+ class="group/row flex w-full items-center hover:bg-gray-100/60 dark:hover:bg-gray-850 rounded-sm transition-colors duration-150"style={"margin-top: #{@row_gap_height}px;"}><div class="grow w-full overflow-hidden" data-test-id={"report-list-#{1 + @item_index}-0"}><Base.barwidth={@metrics[:visitors]}max_width={@bar_max_value}- background_class="bg-green-50 group-hover:bg-green-100 dark:bg-gray-500/15 dark:group-hover:bg-gray-500/30"+ background_class="bg-green-50 group-hover/row:bg-green-100 dark:bg-gray-500/15 dark:group-hover/row:bg-gray-500/30">- <div class="flex justify-start px-2 py-1.5 group text-sm dark:text-gray-300 relative z-9 break-all w-full">- <span class="w-full md:truncate">- <Base.filter_link- class="max-w-max w-full flex items-center md:overflow-hidden hover:underline"- site={@site}- params={@params}- filter={[:is, @dimension, [@item_name]]}- >- {trim_name(@item_name, @col_min_width)}- </Base.filter_link>- </span>+ <div class="flex justify-start items-center gap-x-1.5 px-2 py-1.5 text-sm dark:text-gray-300 relative z-9 break-all w-full">+ <Base.dashboard_link+ class="max-w-max w-full flex items-center md:overflow-hidden hover:underline"+ to={Utils.dashboard_route(@site, @params, filter: [:is, @dimension, [@item_name]])}+ >+ {trim_name(@item_name, @col_min_width)}+ </Base.dashboard_link><.external_link item={@item} link_fn={assigns[:link_fn]} /></div></Base.bar>@@ -186,32 +180,6 @@ defmodule PlausibleWeb.Components.Dashboard.ReportList do"""end- defp details_link(assigns) do- ~H"""- <Base.dashboard_link- class="leading-snug font-bold text-sm text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-150 tracking-wide"- site={@site}- params={@params}- path={@path}- >- <svg- class="feather mr-1"- style="margin-top: -2px;"- xmlns="http://www.w3.org/2000/svg"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- >- <path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3" />- </svg>- DETAILS- </Base.dashboard_link>- """- end-@bar_metric :visitorsdefp bar_max_value(results, metrics) doindex = Enum.find_index(metrics, &(&1 == @bar_metric))diff --git a/lib/plausible_web/live/components/dashboard/tile.ex b/lib/plausible_web/live/components/dashboard/tile.exindex e8b7145fa2..4750325592 100644--- a/lib/plausible_web/live/components/dashboard/tile.ex+++ b/lib/plausible_web/live/components/dashboard/tile.ex@@ -4,36 +4,46 @@ defmodule PlausibleWeb.Components.Dashboard.Tile do"""use PlausibleWeb, :component+ alias PlausibleWeb.Components.Dashboard.Baseattr :id, :string, required: trueattr :class, :string, default: ""attr :title, :string, required: trueattr :height, :integer, required: trueattr :connected?, :boolean, required: true+ attr :details_route, :string, required: trueattr :target, :any, required: true+ slot :warningsslot :tabsslot :inner_block, required: truedef tile(assigns) do~H"""- <div class={[@class, "group overflow-x-hidden"]} data-tile id={@id}>- <div class="w-full flex justify-between h-full">- <div id={@id <> "-title"} class="flex gap-x-1" phx-update="ignore">- <h3 data-title class="font-bold dark:text-gray-100">{@title}</h3>- </div>-- <div- :if={@tabs != []}- id={@id <> "-tabs"}- phx-hook="DashboardTabs"- phx-target={@target}- class="tile-tabs flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2 items-baseline"- >- {render_slot(@tabs)}+ <div+ data-tile+ id={@id}+ class="relative min-h-[430px] w-full p-5 flex flex-col bg-white dark:bg-gray-900 shadow-sm rounded-md md:min-h-initial md:h-27.25rem"+ >+ <%!-- reportheader --%>+ <div class="w-full flex justify-between border-b border-gray-200 dark:border-gray-750">+ <div class="flex gap-x-3">+ <div+ :if={@tabs != []}+ id={@id <> "-tabs"}+ phx-hook="DashboardTabs"+ phx-target={@target}+ class="tile-tabs flex items-baseline gap-x-3.5 text-xs font-medium text-gray-500 dark:text-gray-400"+ >+ {render_slot(@tabs)}+ </div>+ <div class="group-[.phx-navigation-loading]:hidden group-has-[.tile-tabs.phx-hook-loading]:hidden">+ {render_slot(@warnings)}+ </div></div>+ <.details_link details_route={@details_route} path="/pages" /></div>-+ <%!-- reportbody --%><divclass="w-full flex-col justify-center group-[.phx-navigation-loading]:flex group-has-[.tile-tabs.phx-hook-loading]:flex hidden"style={"min-height: #{@height}px;"}@@ -67,20 +77,55 @@ defmodule PlausibleWeb.Components.Dashboard.Tile do)~H"""- <button- class="rounded-sm truncate text-left transition-colors duration-150"- data-tab-key={@tab_key}- data-report-label={@report_label}- data-storage-key="pageTab"- data-target={@target}+ <div+ {@data_attrs}+ class="-mb-px pb-4 data-[active=true]:border-b-2 data-[active=true]:border-gray-900 data-[active=true]:dark:border-gray-100"+ >+ <button+ class="group/tab flex rounded-sm"+ data-tab-key={@tab_key}+ data-report-label={@report_label}+ data-storage-key="pageTab"+ data-target={@target}+ >+ <span+ {@data_attrs}+ class="+ truncate text-left text-xs uppercase text-gray-500 dark:text-gray-400 font-semibold cursor-pointer+ data-[active=false]:group-hover/tab:text-gray-800+ data-[active=false]:dark:group-hover/tab:text-gray-200+ data-[active=true]:text-gray-900+ data-[active=true]:dark:text-gray-100+ data-[active=true]:font-bold+ data-[active=true]:font-bold+ data-[active=true]:tracking-[-.01em]"+ >+ {@report_label}+ </span>+ </button>+ </div>+ """+ end++ defp details_link(assigns) do+ ~H"""+ <Base.dashboard_link+ class="flex mt-px text-gray-500 dark:text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-150"+ to={@details_route}>- <span- {@data_attrs}- class="data-[active=true]:text-indigo-600 data-[active=true]:dark:text-indigo-500 data-[active=true]:font-bold data-[active=true]:underline data-[active=true]:decoration-2 data-[active=true]:decoration-indigo-600 data-[active=true]:dark:decoration-indigo-500 data-[active=false]:hover:text-indigo-700 data-[active=false]:dark:hover:text-indigo-400 data-[active=false]:cursor-pointer"+ <svg+ class="feather"+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round">- {@report_label}- </span>- </button>+ <path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3" />+ </svg>+ </Base.dashboard_link>"""endenddiff --git a/lib/plausible_web/live/dashboard.ex b/lib/plausible_web/live/dashboard.exindex 6e1360bbfa..96d85adfcd 100644--- a/lib/plausible_web/live/dashboard.ex+++ b/lib/plausible_web/live/dashboard.ex@@ -6,7 +6,7 @@ defmodule PlausibleWeb.Live.Dashboard douse PlausibleWeb, :live_viewalias Plausible.Repo- alias Plausible.Stats.DashboardQueryParser+ alias Plausible.Stats.Dashboardalias Plausible.Teams@spec enabled?(Plausible.Site.t() | nil) :: boolean()@@ -46,7 +46,7 @@ defmodule PlausibleWeb.Live.Dashboard dopath = uri.path |> String.split("/") |> Enum.drop(2){:ok, params} =- DashboardQueryParser.parse(+ Dashboard.QueryParser.parse(uri.query || "",socket.assigns.site,socket.assigns.user_prefsdiff --git a/lib/plausible_web/live/dashboard/pages.ex b/lib/plausible_web/live/dashboard/pages.exindex b711db1af2..2b7ebc1728 100644--- a/lib/plausible_web/live/dashboard/pages.ex+++ b/lib/plausible_web/live/dashboard/pages.ex@@ -5,12 +5,13 @@ defmodule PlausibleWeb.Live.Dashboard.Pages douse PlausibleWeb, :live_component- alias PlausibleWeb.Components.Dashboard.ReportList- alias PlausibleWeb.Components.Dashboard.Tile+ alias PlausibleWeb.Components.Dashboard.{ReportList, Tile, ImportedDataWarnings}alias Plausible.Statsalias Plausible.Stats.{ParsedQueryParams, QueryBuilder, QueryResult}+ import Plausible.Stats.Dashboard.Utils+@tabs [%{tab_key: "pages",@@ -51,18 +52,19 @@ defmodule PlausibleWeb.Live.Dashboard.Pages doenddef render(assigns) do- assigns = assign(assigns, :external_link_fn, &external_link/1)-~H"""<div><Tile.tileid="breakdown-tile-pages"- class="group/report"+ details_route={dashboard_route(@site, @params, path: "/#{@active_tab}")}title={get_tab_info(@active_tab, :report_label)}connected?={@connected?}target={@myself}height={ReportList.height()}>+ <:warnings>+ <ImportedDataWarnings.unsupported_filters query_result={@query_result} />+ </:warnings><:tabs><Tile.tab:for={%{tab_key: tab_key, report_label: report_label} <- @tabs}@@ -80,7 +82,7 @@ defmodule PlausibleWeb.Live.Dashboard.Pages dodimension={get_tab_info(@active_tab, :dimension)}params={@params}query_result={@query_result}- external_link_fn={@external_link_fn}+ external_link_fn={page_external_link_fn_for(@site)}/></Tile.tile></div>@@ -100,10 +102,6 @@ defmodule PlausibleWeb.Live.Dashboard.Pages doendend- defp external_link(_item) do- "https://example.com"- end-defp load_stats(socket) do%{active_tab: active_tab, site: site, params: params} = socket.assigns@@ -129,7 +127,7 @@ defmodule PlausibleWeb.Live.Dashboard.Pages dodefp choose_metrics(%ParsedQueryParams{} = params) doif ParsedQueryParams.conversion_goal_filter?(params) do- [:visitors, :conversion_rate]+ [:visitors, :group_conversion_rate]else[:visitors]enddiff --git a/test/plausible/stats/query/dashboard_query_parser_test.exs b/test/plausible/stats/dashboard/query_parser_test.exssimilarity index 99%rename from test/plausible/stats/query/dashboard_query_parser_test.exsrename to test/plausible/stats/dashboard/query_parser_test.exsindex b0906eb633..d35a547dfb 100644--- a/test/plausible/stats/query/dashboard_query_parser_test.exs+++ b/test/plausible/stats/dashboard/query_parser_test.exs@@ -1,6 +1,6 @@-defmodule Plausible.Stats.DashboardQueryParserTest do+defmodule Plausible.Stats.Dashboard.QueryParserTest douse Plausible.DataCase- import Plausible.Stats.DashboardQueryParser+ import Plausible.Stats.Dashboard.QueryParseralias Plausible.Stats.ParsedQueryParams@default_include default_include()diff --git a/test/plausible/stats/query/dashboard_query_serializer_test.exs b/test/plausible/stats/dashboard/query_serializer_test.exssimilarity index 98%rename from test/plausible/stats/query/dashboard_query_serializer_test.exsrename to test/plausible/stats/dashboard/query_serializer_test.exsindex ca925c94b6..ada5563c94 100644--- a/test/plausible/stats/query/dashboard_query_serializer_test.exs+++ b/test/plausible/stats/dashboard/query_serializer_test.exs@@ -1,6 +1,6 @@-defmodule Plausible.Stats.DashboardQuerySerializerTest do+defmodule Plausible.Stats.Dashboard.QuerySerializerTest douse Plausible.DataCase- import Plausible.Stats.{DashboardQuerySerializer, DashboardQueryParser}+ import Plausible.Stats.Dashboard.{QueryParser, QuerySerializer}alias Plausible.Stats.ParsedQueryParams@default_include default_include()diff --git a/test/plausible/stats/dashboard/utils_test.exs b/test/plausible/stats/dashboard/utils_test.exsnew file mode 100644index 0000000000..a21f5a5270--- /dev/null+++ b/test/plausible/stats/dashboard/utils_test.exs@@ -0,0 +1,40 @@+defmodule Plausible.Stats.Dashboard.UtilsTest do+ use Plausible.DataCase+ import Plausible.Stats.Dashboard.Utils++ describe "page_external_link_fn_for/1" do+ @tag :ee_only+ test "returns nil for a consolidated site" do+ site = build(:site, consolidated: true)+ assert is_nil(page_external_link_fn_for(site))+ end++ test "returns a function returning a valid link for valid site" do+ site = build(:site, domain: "abc.com")+ fun = page_external_link_fn_for(site)+ assert fun.(%{dimensions: ["/some-page"]}) == "https://abc.com/some-page"+ end++ test "returns a function returning a valid link for site with subdomain" do+ site = build(:site, domain: "foo.abc.com")+ fun = page_external_link_fn_for(site)+ assert fun.(%{dimensions: ["/some-page"]}) == "https://foo.abc.com/some-page"+ end++ test "subfolder in site domain is stripped" do+ site = build(:site, domain: "abc.com/subfolder")+ fun = page_external_link_fn_for(site)++ assert fun.(%{dimensions: ["/subfolder/some-page"]}) ==+ "https://abc.com/subfolder/some-page"++ assert fun.(%{dimensions: ["/some-page"]}) == "https://abc.com/some-page"+ end++ test "handles internationalized domain names" do+ site = build(:site, domain: "é-1.com")+ fun = page_external_link_fn_for(site)+ assert fun.(%{dimensions: ["/some-page"]}) == "https://xn---1-9ia.com/some-page"+ end+ end+enddiff --git a/test/plausible_web/live/dashboard/dashboard_test.exs b/test/plausible_web/live/dashboard/dashboard_test.exsindex 6fa050a0df..4dfadec1a1 100644--- a/test/plausible_web/live/dashboard/dashboard_test.exs+++ b/test/plausible_web/live/dashboard/dashboard_test.exs@@ -26,7 +26,6 @@ defmodule PlausibleWeb.Live.DashboardTest do{lv, _html} = get_liveview(conn, site)assert has_element?(lv, "#pages-breakdown-live-container")assert has_element?(lv, "#breakdown-tile-pages")- assert has_element?(lv, "#breakdown-tile-pages-title")assert has_element?(lv, "#breakdown-tile-pages-tabs")endenddiff --git a/test/plausible_web/live/dashboard/pages_test.exs b/test/plausible_web/live/dashboard/pages_test.exsindex 3a69f783e2..09ba906001 100644--- a/test/plausible_web/live/dashboard/pages_test.exs+++ b/test/plausible_web/live/dashboard/pages_test.exs@@ -9,6 +9,7 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest do@top_pages_report_list ~s|[data-test-id="pages-report-list"]|@entry_pages_report_list ~s|[data-test-id="entry-pages-report-list"]|@exit_pages_report_list ~s|[data-test-id="exit-pages-report-list"]|+ @unsupported_filters_warning ~s|#breakdown-tile-pages [data-test-id="unsupported-filters-warning"]|describe "Top Pages" dotest "eventually renders and orders items by visitor counts", %{conn: conn, site: site} do@@ -21,7 +22,7 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest dobuild(:pageview, pathname: "/three")])- assert report_list = get_liveview(conn, site) |> get_report_list(@top_pages_report_list)+ assert report_list = get_liveview(conn, site) |> wait_for_element(@top_pages_report_list)assert report_list_as_table(report_list, 4, 2) == [["Page", "Visitors"],@@ -40,7 +41,7 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest doassert report_list =get_liveview(conn, site, "period=realtime")- |> get_report_list(@top_pages_report_list)+ |> wait_for_element(@top_pages_report_list)assert report_list_as_table(report_list, 3, 2) == [["Page", "Current visitors"],@@ -60,11 +61,11 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest doassert report_list =get_liveview(conn, site, "period=day&f=is,goal,Signup")- |> get_report_list(@top_pages_report_list)+ |> wait_for_element(@top_pages_report_list)assert report_list_as_table(report_list, 2, 3) == [["Page", "Conversions", "CR"],- ["/two", "1", "33.33%"]+ ["/two", "1", "50.00%"]]refute get_in_report_list(report_list, 2, 0)@@ -85,7 +86,7 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest doassert report_list =get_liveview(conn, site)|> change_tab("entry-pages")- |> get_report_list(@entry_pages_report_list)+ |> wait_for_element(@entry_pages_report_list)assert report_list_as_table(report_list, 4, 2) == [["Entry page", "Unique entrances"],@@ -105,7 +106,7 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest doassert report_list =get_liveview(conn, site, "period=realtime")|> change_tab("entry-pages")- |> get_report_list(@entry_pages_report_list)+ |> wait_for_element(@entry_pages_report_list)assert report_list_as_table(report_list, 3, 2) == [["Entry page", "Current visitors"],@@ -119,15 +120,16 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest dopopulate_stats(site, [build(:pageview, pathname: "/one"),+ build(:pageview, pathname: "/two"),+ build(:pageview, pathname: "/two"),build(:pageview, user_id: 1, pathname: "/two"),- build(:event, user_id: 1, name: "Signup", pathname: "/two"),- build(:pageview, pathname: "/two")+ build(:event, user_id: 1, name: "Signup", pathname: "/two")])assert report_list =get_liveview(conn, site, "period=day&f=is,goal,Signup")|> change_tab("entry-pages")- |> get_report_list(@entry_pages_report_list)+ |> wait_for_element(@entry_pages_report_list)assert report_list_as_table(report_list, 2, 3) == [["Entry page", "Conversions", "CR"],@@ -152,7 +154,7 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest doassert report_list =get_liveview(conn, site)|> change_tab("exit-pages")- |> get_report_list(@exit_pages_report_list)+ |> wait_for_element(@exit_pages_report_list)assert report_list_as_table(report_list, 4, 2) == [["Exit page", "Unique exits"],@@ -172,7 +174,7 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest doassert report_list =get_liveview(conn, site, "period=realtime")|> change_tab("exit-pages")- |> get_report_list(@exit_pages_report_list)+ |> wait_for_element(@exit_pages_report_list)assert report_list_as_table(report_list, 3, 2) == [["Exit page", "Current visitors"],@@ -194,18 +196,77 @@ defmodule PlausibleWeb.Live.Dashboard.PagesTest doassert report_list =get_liveview(conn, site, "period=day&f=is,goal,Signup")|> change_tab("exit-pages")- |> get_report_list(@exit_pages_report_list)+ |> wait_for_element(@exit_pages_report_list)assert report_list_as_table(report_list, 2, 3) == [["Exit page", "Conversions", "CR"],- ["/two", "1", "33.33%"]+ ["/two", "1", "50.00%"]]refute get_in_report_list(report_list, 2, 0)endend- defp get_report_list(lv, selector) do+ describe "unsupported filters warning" do+ setup %{site: site} do+ site_import = insert(:site_import, site: site)++ populate_stats(site, site_import.id, [+ build(:pageview, timestamp: ~N[2021-01-02 00:00:00]),+ build(:imported_visitors, visitors: 1, date: ~D[2021-01-01]),+ build(:imported_pages, page: "/", visitors: 1, date: ~D[2021-01-01])+ ])++ :ok+ end++ test "shows up when mixing dimensions", %{conn: conn, site: site} do+ tooltip_element =+ get_liveview(conn, site, "period=all&f=is,browser,Chrome")+ |> wait_for_element(@unsupported_filters_warning)++ assert text(tooltip_element) =~ "Imported data is excluded due to the applied filters"+ end++ test "does not show up when mixing dimensions but imports not requested", %{+ conn: conn,+ site: site+ } do+ lv = get_liveview(conn, site, "period=all&f=is,browser,Chrome&with_imported=false")+ _report_list = wait_for_element(lv, @top_pages_report_list)+ html = render(lv)++ refute element_exists?(html, @unsupported_filters_warning)+ end++ test "does not show up when imports are included in the data", %{conn: conn, site: site} do+ lv = get_liveview(conn, site, "period=all")+ _report_list = wait_for_element(lv, @top_pages_report_list)+ html = render(lv)++ refute element_exists?(html, @unsupported_filters_warning)+ end++ test "does not show up when imports don't exist", %{conn: conn, user: user} do+ site_without_imports = new_site(owner: user, stats_start_date: ~D[2021-01-01])++ lv = get_liveview(conn, site_without_imports, "period=all")+ _report_list = wait_for_element(lv, @top_pages_report_list)+ html = render(lv)++ refute element_exists?(html, @unsupported_filters_warning)+ end++ test "does not show up when imports exist but out of range", %{conn: conn, site: site} do+ lv = get_liveview(conn, site, "period=day")+ _report_list = wait_for_element(lv, @top_pages_report_list)+ html = render(lv)++ refute element_exists?(html, @unsupported_filters_warning)+ end+ end++ defp wait_for_element(lv, selector) doeventually(fn ->html = render(lv){element_exists?(html, selector), find(html, selector)}