Skip to content

A platform for community discussion. Free, open, simple.

UX: Add multi-select to Site Traffic Explorer filters (#42663)

Alan Guo Xiang Tan74e2b4334a8f
diff --git a/app/assets/stylesheets/admin/admin_dashboard.scss b/app/assets/stylesheets/admin/admin_dashboard.scss
index 278612b55d5..01db5ddf5bf 100644
--- a/app/assets/stylesheets/admin/admin_dashboard.scss
+++ b/app/assets/stylesheets/admin/admin_dashboard.scss
@@ -306,7 +306,7 @@ $db-bar-height: var(--space-2);
display: flex;
justify-content: flex-end;
flex-grow: 1;
- gap: var(--space-10);
+ gap: clamp(var(--space-2), var(--space-8), var(--space-8));
@include viewport.until(sm) {
border-top: 1px solid var(--primary-low);
diff --git a/app/assets/stylesheets/admin/dashboard/site-traffic-explorer.scss b/app/assets/stylesheets/admin/dashboard/site-traffic-explorer.scss
index 56091011eab..a6072d9e179 100644
--- a/app/assets/stylesheets/admin/dashboard/site-traffic-explorer.scss
+++ b/app/assets/stylesheets/admin/dashboard/site-traffic-explorer.scss
@@ -1,35 +1,135 @@
@use "lib/viewport";
.site-traffic-explorer {
- .d-page-header {
- margin-bottom: var(--space-4);
- }
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-4);
+ padding-bottom: var(--space-8);
- &__content {
- display: flex;
- flex-direction: column;
- gap: var(--space-4);
- padding-bottom: var(--space-8);
+ .db-section__subheader {
+ justify-content: flex-end;
}
&__filters {
display: flex;
flex-wrap: wrap;
align-items: center;
+ min-width: 0;
+ gap: var(--space-2);
+ }
+
+ &__filter-dropdown {
+ .d-button-label {
+ @include ellipsis;
+ }
+ }
+
+ &__filter-controls {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: var(--space-2);
+
+ @include viewport.until(sm) {
+ flex-wrap: wrap;
+ }
+ }
+
+ &__filter-actions {
+ display: flex;
+ align-items: center;
gap: var(--space-2);
+ margin-inline-start: auto;
+
+ .btn {
+ padding-block: var(--space-1);
+ }
+ }
+
+ &__filter-apply {
+ gap: var(--space-2);
+ }
+
+ &__filter-apply-pending-count {
+ color: var(--tertiary);
+ background: var(--secondary);
+ padding: 0.21em 0.42em;
+ min-width: 0.6em;
+ border-radius: 1em;
+ font-size: var(--font-down-2-rem);
+ font-weight: 600;
}
&__filter-pill {
display: inline-flex;
align-items: center;
gap: var(--space-1);
+ min-width: 0;
+ max-width: 100%;
+ white-space: nowrap;
padding-inline-start: var(--space-3);
- border-radius: 2rem;
- background: var(--primary-low);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius-pill);
+ background: var(--primary-very-low);
+ font-size: var(--font-down-1-rem);
+
+ &.is-pending {
+ border-color: var(--tertiary);
+ border-style: dashed;
+ background: var(--tertiary-very-low);
+ }
+
+ .site-traffic-explorer__filter-pill-remaining,
+ .d-icon-angle-down {
+ color: var(--primary-medium);
+ }
+
+ .fk-d-menu__trigger {
+ min-width: 0;
+ gap: var(--space-1);
+ border: 0;
+ padding: 0;
+ background: transparent;
+ color: inherit;
+
+ &:hover,
+ &.-expanded {
+ border: 0;
+ padding: 0;
+ background: transparent;
+ color: inherit;
+
+ .site-traffic-explorer__filter-pill-remaining,
+ .d-icon-angle-down {
+ color: var(--primary);
+ }
+ }
+
+ &.-expanded .d-icon-angle-down {
+ transform: rotate(180deg);
+ }
+ }
}
&__filter-remove {
- padding: var(--space-1) var(--space-2);
+ color: var(--primary-medium);
+ border-top-right-radius: var(--d-border-radius-pill);
+ border-bottom-right-radius: var(--d-border-radius-pill);
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ border-left: 1px solid var(--primary-low);
+ }
+
+ &__filter-pill-values {
+ @include ellipsis;
+ display: inline-flex;
+ }
+
+ &__filter-pill-value {
+ flex-grow: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-weight: 600;
}
&__partial-warning {
@@ -39,6 +139,9 @@
&__empty {
border-radius: var(--d-border-radius);
padding: var(--space-3) var(--space-4);
+ border: 1px dashed var(--content-border-color);
+ background: var(--primary-very-low);
+ text-align: center;
}
&__skeleton {
@@ -109,91 +212,16 @@
}
}
- &__results {
- min-width: 0;
- }
-
- &__report {
- overflow: hidden;
- background: var(--secondary);
- }
-
- &__metrics {
- .db-section__subintro {
- flex: 1 1 15rem;
- }
-
- .db-section__metrics {
- align-items: flex-start;
- }
-
- @include viewport.until(md) {
- flex-direction: column;
- gap: var(--space-4);
-
- .db-section__subintro {
- flex-basis: auto;
- }
-
- .db-section__metrics {
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- width: 100%;
- }
+ .db-section__metrics {
+ @include viewport.until(sm) {
+ flex-wrap: wrap;
}
}
- &__metric {
- display: flex;
- flex-direction: column;
- gap: var(--space-1);
- min-width: 0;
-
- &.--primary {
- flex-flow: row wrap;
- align-items: baseline;
-
- .site-traffic-explorer__metric-value,
- .site-traffic-explorer__metric-label {
- color: var(--primary);
- font-size: var(--font-up-1);
- font-weight: 700;
- }
- }
- }
-
- &__metric-value {
- overflow-wrap: anywhere;
- font-variant-numeric: tabular-nums;
- }
-
- &__metric-label-row {
- display: flex;
- align-items: center;
- gap: var(--space-1);
- width: max-content;
- max-width: 100%;
- }
-
- &__metric-label {
- overflow-wrap: anywhere;
- }
-
- &__empty {
- border: 1px dashed var(--content-border-color);
- background: var(--primary-very-low);
- text-align: center;
- }
-
- &__cards {
- gap: 0;
- }
-
- &__card {
+ .db-section__row-block {
display: flex;
flex-direction: column;
gap: var(--space-3);
- min-width: 0;
}
&__tabs {
@@ -204,76 +232,63 @@
border-bottom: 1px solid var(--content-border-color);
button {
- appearance: none;
border: 0;
border-bottom: 2px solid transparent;
- padding-block: var(--space-2);
+ padding-bottom: var(--space-2);
padding-inline: 0;
background: transparent;
color: var(--primary-high);
- font: inherit;
font-size: var(--font-down-1-rem);
white-space: nowrap;
- cursor: pointer;
&.is-active {
border-bottom-color: var(--tertiary);
- color: var(--primary);
- font-weight: 600;
- }
-
- &:focus-visible {
- outline: 2px solid var(--tertiary);
- outline-offset: -2px;
+ color: var(--tertiary);
}
}
}
&__breakdown-list {
@include unstyled-list;
- display: flex;
- flex-direction: column;
- min-width: 0;
font-size: var(--font-down-1-rem);
+ margin-block-end: var(--space-2);
}
&__row {
- box-sizing: border-box;
display: flex;
align-items: center;
- justify-content: space-between;
- width: calc(100% + 2 * var(--space-2));
- min-width: 0;
- gap: var(--space-3);
+ gap: var(--space-1);
margin-inline: calc(-1 * var(--space-2));
- border: 0;
border-radius: var(--d-border-radius);
- padding-block: var(--space-1);
padding-inline: var(--space-2);
- background: transparent;
- color: var(--primary);
- font: inherit;
- text-align: start;
- }
+ cursor: pointer;
- &__row-label {
- @include ellipsis;
+ html.discourse-no-touch &:hover:not(:has(a:hover)) {
+ background: var(--token-color-surface-hovered);
+ }
}
&__row-count {
flex-shrink: 0;
margin-inline-start: auto;
color: var(--primary-medium);
- font-variant-numeric: tabular-nums;
}
&__row-link {
- display: block;
- flex: 0 1 auto;
- min-width: 0;
- overflow: hidden;
+ @include ellipsis;
color: inherit;
text-decoration: none;
+ margin: 0;
+ margin-right: var(
+ --space-4
+ ); // leave extra space on purpose to click the row not the link
+
+ &:hover {
+ .discourse-no-touch & {
+ color: var(--tertiary);
+ text-decoration: underline;
+ }
+ }
&:visited {
color: inherit;
@@ -285,123 +300,36 @@
}
}
- html.discourse-no-touch &__row-link:hover {
- color: var(--tertiary);
- text-decoration: underline;
- }
-
- &__row-filter-area {
- display: flex;
- align-items: center;
- align-self: stretch;
- justify-content: flex-end;
- flex: 1 0 auto;
- min-width: 0;
- margin-block: calc(-1 * var(--space-1));
- margin-inline-end: calc(-1 * var(--space-2));
- border: 0;
- padding-block: var(--space-1);
- padding-inline: 0 var(--space-2);
- background: transparent;
- color: inherit;
- font: inherit;
- cursor: pointer;
- }
-
- button.site-traffic-explorer__row {
- cursor: pointer;
-
- &:focus-visible {
- background: var(--token-color-surface-hovered);
- color: var(--tertiary);
- }
- }
-
- html.discourse-no-touch & .site-traffic-explorer__row:hover {
- background: var(--token-color-surface-hovered);
- }
-
- &__view-more {
- width: max-content;
- max-width: 100%;
- margin-block-start: auto;
- margin-inline: calc(-1 * var(--space-2));
- padding-inline: var(--space-2);
- font-size: var(--font-down-1-rem);
- }
-
&__dimension-label {
display: flex;
align-items: center;
- min-width: 0;
- width: 100%;
- }
-
- &__dimension-prefix {
- flex: 0 0 auto;
- margin-inline-end: var(--space-2);
+ gap: var(--space-2);
+ padding-block: var(--space-1);
}
&__dimension-text {
@include ellipsis;
- flex: 1 1 auto;
- min-width: 0;
}
&__card-empty {
padding-block: var(--space-3);
color: var(--primary-medium);
}
+}
- @include viewport.until(md) {
- &__cards {
- flex-direction: column;
- }
-
- &__card:not(:last-child) {
- border-right: 0;
- border-bottom: 1px solid var(--content-border-color);
- }
- }
-
- @include viewport.until(sm) {
- &__chart {
- height: 18rem;
- }
- }
+// The global `label` rule in common/base/discourse.scss wins on specificity
+// over the block class, so these resets have to match it at element level.
+label.site-traffic-explorer__row {
+ margin-block: 0;
+ font-weight: inherit;
}
.site-traffic-breakdown-modal {
- @include viewport.until(md) {
- .d-table {
- table-layout: fixed;
- }
+ .site-traffic-explorer__breakdown-list {
+ font-size: var(--font-0);
}
- &__dimension {
- max-width: 0;
- overflow: hidden;
-
- .site-traffic-explorer__row-link {
- display: block;
- }
-
- @include viewport.until(md) {
- max-width: none;
- }
- }
-
- &__pageviews {
- width: 1%;
- white-space: nowrap;
- text-align: end;
-
- @include viewport.until(md) {
- width: auto;
- }
-
- .d-table__mobile-label {
- text-align: start;
- }
+ .site-traffic-explorer__dimension-label {
+ padding-block: var(--space-2);
}
}
diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb
index 48471dd0af5..94414f5a0b2 100644
--- a/app/controllers/admin/dashboard_controller.rb
+++ b/app/controllers/admin/dashboard_controller.rb
@@ -61,21 +61,7 @@ class Admin::DashboardController < Admin::StaffController
end
def traffic
- permitted =
- params.permit(
- :start_date,
- :end_date,
- :traffic_type,
- :top_url,
- :entry_url,
- :referrer,
- :country,
- :network,
- :browser,
- :ip,
- )
-
- AdminDashboardSiteTrafficExplorer.call(service_params.deep_merge(params: permitted.to_h)) do
+ AdminDashboardSiteTrafficExplorer.call(service_params.deep_merge(params: traffic_params)) do
on_success { |traffic:| render json: traffic }
on_failed_contract { raise Discourse::InvalidParameters }
on_failed_step(:load_traffic) do |step|
@@ -176,6 +162,27 @@ class Admin::DashboardController < Admin::StaffController
private
+ def traffic_params
+ permitted = params.permit(:start_date, :end_date).to_h
+
+ AdminDashboardSiteTrafficExplorer::FILTER_KEYS.each do |key|
+ value = params[key]
+ next if value.nil?
+
+ if !value.is_a?(Array) || value.any? { |item| !item.is_a?(String) }
+ raise Discourse::InvalidParameters.new(key)
+ end
+
+ permitted[key] = if key == :traffic_type
+ value.flat_map { |item| item.split(",") }
+ else
+ value
+ end
+ end
+
+ permitted
+ end
+
def serialized_problems
serialize_data(AdminNotice.problem.order(:id), AdminNoticeSerializer)
end
diff --git a/app/services/admin_dashboard_site_traffic_explorer.rb b/app/services/admin_dashboard_site_traffic_explorer.rb
index 47c79f533e6..c6ea409609d 100644
--- a/app/services/admin_dashboard_site_traffic_explorer.rb
+++ b/app/services/admin_dashboard_site_traffic_explorer.rb
@@ -10,7 +10,6 @@ class AdminDashboardSiteTrafficExplorer
private_constant :STATEMENT_TIMEOUT_MS
FILTER_KEYS = %i[traffic_type top_url entry_url referrer country network browser ip].freeze
- private_constant :FILTER_KEYS
FILTER_DIMENSIONS = {
top_url: "top_urls",
@@ -32,14 +31,14 @@ class AdminDashboardSiteTrafficExplorer
params do
attribute :start_date, :date
attribute :end_date, :date
- attribute :traffic_type, :string
- attribute :top_url, :string
- attribute :entry_url, :string
- attribute :referrer, :string
- attribute :country, :string
- attribute :network, :string
- attribute :browser, :string
- attribute :ip, :string
+ attribute :traffic_type, :array
+ attribute :top_url, :array
+ attribute :entry_url, :array
+ attribute :referrer, :array
+ attribute :country, :array
+ attribute :network, :array
+ attribute :browser, :array
+ attribute :ip, :array
validates :start_date, :end_date, presence: true
validate :start_date_precedes_end_date
@@ -58,16 +57,21 @@ class AdminDashboardSiteTrafficExplorer
def normalize_filter(key, value)
return nil if value.nil?
+
+ raise Discourse::InvalidParameters.new(key) if value.empty? || value.size > DIMENSION_LIMIT
+
+ value.map { |item| normalize_filter_value(key, item) }.uniq
+ end
+
+ def normalize_filter_value(key, value)
return "" if key == :referrer && value == ""
raise Discourse::InvalidParameters.new(key) if value.blank?
case key
when :traffic_type
- traffic_types = value.to_s.split(",").uniq
- if traffic_types.empty? || (traffic_types - TRAFFIC_TYPE_VALUES).any?
- raise Discourse::InvalidParameters.new(key)
- end
- TRAFFIC_TYPE_VALUES.select { |traffic_type| traffic_types.include?(traffic_type) }
+ traffic_type = value.to_s
+ raise Discourse::InvalidParameters.new(key) if !TRAFFIC_TYPE_VALUES.include?(traffic_type)
+ traffic_type
when :top_url, :entry_url
BrowserPageviewEventUrlNormalizer.normalize_site_path(value) ||
raise(Discourse::InvalidParameters.new(key))
@@ -144,13 +148,21 @@ class AdminDashboardSiteTrafficExplorer
end_date: end_date + 1.day,
cap: cap,
site_host: BrowserPageviewEventUrlNormalizer.normalize_host(Discourse.current_hostname),
- top_url: filters[:top_url],
- entry_url: filters[:entry_url],
- referrer: filters[:referrer],
- country: filters[:country],
- network_asn: filters[:network],
- browser: filters[:browser] && BrowserPageviewEvent.browsers.fetch(filters[:browser]),
- ip_address: filters[:ip],
+ top_url_filtered: filters[:top_url].present?,
+ top_urls: filters[:top_url].presence || [nil],
+ entry_url_filtered: filters[:entry_url].present?,
+ entry_urls: filters[:entry_url].presence || [nil],
+ referrer_filtered: filters[:referrer].present?,
+ referrers: filters[:referrer].presence || [nil],
+ country_filtered: filters[:country].present?,
+ countries: filters[:country].presence || [nil],
+ network_filtered: filters[:network].present?,
+ network_asns: filters[:network].presence || [nil],
+ browser_filtered: filters[:browser].present?,
+ browsers:
+ filters[:browser]&.map { |browser| BrowserPageviewEvent.browsers.fetch(browser) } || [nil],
+ ip_filtered: filters[:ip].present?,
+ ip_addresses: filters[:ip].presence || [nil],
traffic_type_filtered: filters[:traffic_type].present?,
include_logged_in: filters[:traffic_type]&.include?("logged_in"),
include_anonymous: filters[:traffic_type]&.include?("anonymous"),
@@ -163,6 +175,28 @@ class AdminDashboardSiteTrafficExplorer
}
end
+ def filter_predicate(except: nil)
+ predicates = {
+ top_url: "(NOT :top_url_filtered OR normalized_url IN (:top_urls))",
+ entry_url: "(NOT :entry_url_filtered OR entry_url IN (:entry_urls))",
+ referrer: "(NOT :referrer_filtered OR referrer IN (:referrers))",
+ country: "(NOT :country_filtered OR country_code IN (:countries))",
+ network: "(NOT :network_filtered OR asn IN (:network_asns))",
+ browser: "(NOT :browser_filtered OR browser IN (:browsers))",
+ ip: "(NOT :ip_filtered OR host(ip_address) IN (:ip_addresses))",
+ traffic_type: <<~SQL.squish,
+ (
+ NOT :traffic_type_filtered
+ OR (:include_logged_in AND NOT likely_crawler AND user_id IS NOT NULL)
+ OR (:include_anonymous AND NOT likely_crawler AND user_id IS NULL)
+ OR (:include_likely_crawler AND likely_crawler)
+ )
+ SQL
+ }
+
+ predicates.except(except).values.join("\n AND ")
+ end
+
def query(start_date:, end_date:)
source_condition =
BrowserPageviewEvent.rollup_source_condition(table: "bpe", start_date:, end_date:)
@@ -231,7 +265,7 @@ class AdminDashboardSiteTrafficExplorer
) AS likely_crawler
FROM population
),
- dimensioned AS (
+ dimensioned AS MATERIALIZED (
SELECT
classified.created_at,
classified.session_id,
@@ -251,39 +285,10 @@ class AdminDashboardSiteTrafficExplorer
END AS referrer
FROM classified
),
- filtered AS MATERIALIZED (
+ filtered AS NOT MATERIALIZED (
SELECT *
FROM dimensioned
- WHERE (:top_url IS NULL OR normalized_url = :top_url)
- AND (
- :entry_url IS NULL
- OR entry_url = :entry_url
- )
- AND (
- :referrer IS NULL
- OR referrer = :referrer
- )
- AND (:country IS NULL OR country_code = :country)
- AND (:network_asn IS NULL OR asn = :network_asn)
- AND (:browser IS NULL OR browser = :browser)
- AND (:ip_address IS NULL OR host(ip_address) = :ip_address)
- AND (
- NOT :traffic_type_filtered
- OR (
- :include_logged_in
- AND NOT likely_crawler
- AND user_id IS NOT NULL
- )
- OR (
- :include_anonymous
- AND NOT likely_crawler
- AND user_id IS NULL
- )
- OR (
- :include_likely_crawler
- AND likely_crawler
- )
- )
+ WHERE #{filter_predicate}
),
sessions AS (
SELECT session_id, COUNT(*) AS pageviews
@@ -321,19 +326,6 @@ class AdminDashboardSiteTrafficExplorer
COALESCE(SUM(pageviews), 0)::integer AS pageviews,
COALESCE(SUM(logged_in_human_pageviews), 0)::integer AS logged_in_pageviews
FROM series_rows
- ),
- bounded_dimension_rows AS MATERIALIZED (
- SELECT
- CASE
- WHEN GROUPING(country_code) = 0 THEN 'countries'
- WHEN GROUPING(browser) = 0 THEN 'browsers'
- END AS dimension,
- country_code,
- browser,
- COUNT(*)::integer AS pageviews,
- MIN(ip_address) AS representative_ip
- FROM filtered
- GROUP BY GROUPING SETS ((country_code), (browser))
)
SELECT
(
@@ -359,16 +351,24 @@ class AdminDashboardSiteTrafficExplorer
) AS oldest_pageview_at,
jsonb_build_object(
'country', (
- SELECT host(MIN(ip_address))
- FROM population
- WHERE :country IS NOT NULL
- AND country_code = :country
+ SELECT COALESCE(jsonb_object_agg(country_code, representative_ip), '{}'::jsonb)
+ FROM (
+ SELECT country_code, host(MIN(ip_address)) AS representative_ip
+ FROM population
+ WHERE :country_filtered
+ AND country_code IN (:countries)
+ GROUP BY country_code
+ ) rows
),
'network', (
- SELECT host(MIN(ip_address))
- FROM population
- WHERE :network_asn IS NOT NULL
- AND asn = :network_asn
+ SELECT COALESCE(jsonb_object_agg(asn, representative_ip), '{}'::jsonb)
+ FROM (
+ SELECT asn, host(MIN(ip_address)) AS representative_ip
+ FROM population
+ WHERE :network_filtered
+ AND asn IN (:network_asns)
+ GROUP BY asn
+ ) rows
)
) AS active_filter_representative_ips,
jsonb_build_object(
@@ -417,16 +417,20 @@ class AdminDashboardSiteTrafficExplorer
SELECT COALESCE(
jsonb_agg(
jsonb_build_object('value', value, 'pageviews', pageviews)
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
),
'[]'::jsonb
)
FROM (
- SELECT normalized_url AS value, COUNT(*)::integer AS pageviews
- FROM filtered
- WHERE normalized_url IS NOT NULL
+ SELECT
+ normalized_url AS value,
+ COUNT(*)::integer AS pageviews,
+ :top_url_filtered AND normalized_url IN (:top_urls) AS selected
+ FROM dimensioned
+ WHERE #{filter_predicate(except: :top_url)}
+ AND normalized_url IS NOT NULL
GROUP BY normalized_url
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
LIMIT :dimension_limit
) rows
),
@@ -434,16 +438,20 @@ class AdminDashboardSiteTrafficExplorer
SELECT COALESCE(
jsonb_agg(
jsonb_build_object('value', value, 'pageviews', pageviews)
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
),
'[]'::jsonb
)
FROM (
- SELECT entry_url AS value, COUNT(*)::integer AS pageviews
- FROM filtered
- WHERE entry_url IS NOT NULL
+ SELECT
+ entry_url AS value,
+ COUNT(*)::integer AS pageviews,
+ :entry_url_filtered AND entry_url IN (:entry_urls) AS selected
+ FROM dimensioned
+ WHERE #{filter_predicate(except: :entry_url)}
+ AND entry_url IS NOT NULL
GROUP BY entry_url
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
LIMIT :dimension_limit
) rows
),
@@ -451,16 +459,20 @@ class AdminDashboardSiteTrafficExplorer
SELECT COALESCE(
jsonb_agg(
jsonb_build_object('value', value, 'pageviews', pageviews)
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
),
'[]'::jsonb
)
FROM (
- SELECT referrer AS value, COUNT(*)::integer AS pageviews
- FROM filtered
- WHERE referrer IS NOT NULL
+ SELECT
+ referrer AS value,
+ COUNT(*)::integer AS pageviews,
+ :referrer_filtered AND referrer IN (:referrers) AS selected
+ FROM dimensioned
+ WHERE #{filter_predicate(except: :referrer)}
+ AND referrer IS NOT NULL
GROUP BY referrer
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
LIMIT :dimension_limit
) rows
),
@@ -472,19 +484,21 @@ class AdminDashboardSiteTrafficExplorer
'pageviews', pageviews,
'representative_ip', representative_ip
)
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
),
'[]'::jsonb
)
FROM (
SELECT
country_code AS value,
- pageviews,
- host(representative_ip) AS representative_ip
- FROM bounded_dimension_rows
- WHERE dimension = 'countries'
+ COUNT(*)::integer AS pageviews,
+ host(MIN(ip_address)) AS representative_ip,
+ :country_filtered AND country_code IN (:countries) AS selected
+ FROM dimensioned
+ WHERE #{filter_predicate(except: :country)}
AND country_code IS NOT NULL
- ORDER BY pageviews DESC, value
+ GROUP BY country_code
+ ORDER BY selected DESC, pageviews DESC, value
LIMIT :dimension_limit
) rows
),
@@ -496,7 +510,7 @@ class AdminDashboardSiteTrafficExplorer
'pageviews', pageviews,
'representative_ip', representative_ip
)
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
),
'[]'::jsonb
)
@@ -504,11 +518,13 @@ class AdminDashboardSiteTrafficExplorer
SELECT
'AS' || asn AS value,
COUNT(*)::integer AS pageviews,
- host(MIN(ip_address)) AS representative_ip
- FROM filtered
- WHERE asn IS NOT NULL
+ host(MIN(ip_address)) AS representative_ip,
+ :network_filtered AND asn IN (:network_asns) AS selected
+ FROM dimensioned
+ WHERE #{filter_predicate(except: :network)}
+ AND asn IS NOT NULL
GROUP BY asn
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
LIMIT :dimension_limit
) rows
),
@@ -516,15 +532,19 @@ class AdminDashboardSiteTrafficExplorer
SELECT COALESCE(
jsonb_agg(
jsonb_build_object('value', value, 'pageviews', pageviews)
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
),
'[]'::jsonb
)
FROM (
- SELECT browser AS value, pageviews
- FROM bounded_dimension_rows
- WHERE dimension = 'browsers'
- ORDER BY pageviews DESC, value
+ SELECT
+ browser AS value,
+ COUNT(*)::integer AS pageviews,
+ :browser_filtered AND browser IN (:browsers) AS selected
+ FROM dimensioned
+ WHERE #{filter_predicate(except: :browser)}
+ GROUP BY browser
+ ORDER BY selected DESC, pageviews DESC, value
LIMIT :dimension_limit
) rows
),
@@ -532,15 +552,19 @@ class AdminDashboardSiteTrafficExplorer
SELECT COALESCE(
jsonb_agg(
jsonb_build_object('value', value, 'pageviews', pageviews)
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
),
'[]'::jsonb
)
FROM (
- SELECT host(ip_address) AS value, COUNT(*)::integer AS pageviews
- FROM filtered
+ SELECT
+ host(ip_address) AS value,
+ COUNT(*)::integer AS pageviews,
+ :ip_filtered AND host(ip_address) IN (:ip_addresses) AS selected
+ FROM dimensioned
+ WHERE #{filter_predicate(except: :ip)}
GROUP BY ip_address
- ORDER BY pageviews DESC, value
+ ORDER BY selected DESC, pageviews DESC, value
LIMIT :dimension_limit
) rows
)
@@ -597,15 +621,21 @@ class AdminDashboardSiteTrafficExplorer
)
end
- canonical_value = key == :network ? "AS#{value}" : value
dimension = FILTER_DIMENSIONS.fetch(key)
- [
+ value.map do |item|
+ canonical_value = key == :network ? "AS#{item}" : item
+ representative_ip_key = key == :network ? item.to_s : canonical_value.to_s
{
key: key,
value: canonical_value,
- label: dimension_label(dimension, canonical_value, representative_ips[key.to_s]),
- },
- ]
+ label:
+ dimension_label(
+ dimension,
+ canonical_value,
+ representative_ips.dig(key.to_s, representative_ip_key),
+ ),
+ }
+ end
end
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 9349a5bc871..071c82fce7a 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -7264,17 +7264,41 @@ en:
timeout: "This traffic query took too long. Choose a shorter date range and try again."
unexpected: "Couldn't load site traffic. Try again."
empty: "No matching pageviews"
- summary: "Traffic summary"
- traffic_over_time: "Traffic over time"
- pageviews: "Pageviews"
- metric_information: "About this metric"
+ metric_information: "About %{metric}"
active_filters: "Active traffic filters"
- filter_description: "%{filter} is <strong>%{value}</strong>"
+ filtering_to:
+ traffic_type:
+ one: "Filtering to %{count} traffic type"
+ other: "Filtering to %{count} traffic types"
+ top_url:
+ one: "Filtering to %{count} top URL"
+ other: "Filtering to %{count} top URLs"
+ entry_url:
+ one: "Filtering to %{count} entry URL"
+ other: "Filtering to %{count} entry URLs"
+ referrer:
+ one: "Filtering to %{count} referrer"
+ other: "Filtering to %{count} referrers"
+ country:
+ one: "Filtering to %{count} country"
+ other: "Filtering to %{count} countries"
+ network:
+ one: "Filtering to %{count} network"
+ other: "Filtering to %{count} networks"
+ browser:
+ one: "Filtering to %{count} browser"
+ other: "Filtering to %{count} browsers"
+ ip:
+ one: "Filtering to %{count} IP address"
+ other: "Filtering to %{count} IP addresses"
+ remove_filter_value: "Remove %{value}"
+ clear_all: "Clear all"
+ apply: "Apply"
filter_by:
one: "Filter by %{label}, %{count} pageview"
other: "Filter by %{label}, %{count} pageviews"
remove_filter: "Remove %{filter} filter"
- remove_traffic_type_filter: "Remove %{value} traffic filter"
+ # remove_traffic_type_filter: "Remove %{value} traffic filter"
view_more: "View more"
no_dimension_data: "No data for this breakdown."
direct_or_unknown: "Direct / unknown"
@@ -7290,14 +7314,6 @@ en:
entry_urls: "Entry URLs"
browsers: "Browsers"
ip_addresses: "IP addresses"
- columns:
- referrers: "Referrer"
- countries: "Country"
- networks: "Network"
- top_urls: "URL"
- entry_urls: "Entry URL"
- browsers: "Browser"
- ip_addresses: "IP address"
filters:
traffic_type: "Traffic type"
top_url: "Top URL"
@@ -7307,9 +7323,10 @@ en:
network: "Network"
browser: "Browser"
ip: "IP address"
+ headline:
+ one: "%{formatted_count} pageview"
+ other: "%{formatted_count} pageviews"
metrics:
- pageviews:
- label: "Pageviews"
distinct_sessions:
label: "Distinct sessions"
logged_in_share:
diff --git a/frontend/discourse/admin/components/site-traffic-explorer-breakdown-card.gjs b/frontend/discourse/admin/components/site-traffic-explorer-breakdown-card.gjs
index d4da2ea4902..b3347d9be56 100644
--- a/frontend/discourse/admin/components/site-traffic-explorer-breakdown-card.gjs
+++ b/frontend/discourse/admin/components/site-traffic-explorer-breakdown-card.gjs
@@ -3,12 +3,10 @@ import { tracked } from "@glimmer/tracking";
import { concat, fn } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
-import { next, schedule } from "@ember/runloop";
+import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import SiteTrafficExplorerBreakdownModal from "discourse/admin/components/site-traffic-explorer-breakdown-modal";
-import SiteTrafficExplorerDimensionLabel from "discourse/admin/components/site-traffic-explorer-dimension-label";
-import SiteTrafficExplorerPageviewCount from "discourse/admin/components/site-traffic-explorer-pageview-count";
-import { countryName } from "discourse/admin/lib/format-country";
+import SiteTrafficExplorerBreakdownRow from "discourse/admin/components/site-traffic-explorer-breakdown-row";
import getURL from "discourse/lib/get-url";
import { eq } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
@@ -37,19 +35,6 @@ export default class SiteTrafficExplorerBreakdownCard extends Component {
return this.rows.length > CARD_ROW_LIMIT;
}
- @action
- filterLabel(row) {
- const label =
- this.activeTab.dimension === "countries"
- ? countryName(row.value)
- : row.label;
-
- return i18n("admin.site_traffic_explorer.filter_by", {
- label,
- count: row.pageviews,
- });
- }
-
@action
selectTab(index) {
this.activeTabIndex = index;
@@ -87,15 +72,17 @@ export default class SiteTrafficExplorerBreakdownCard extends Component {
const result = await this.modal.show(SiteTrafficExplorerBreakdownModal, {
model: {
title: this.activeTab.label,
- columnLabel: this.activeTab.columnLabel,
dimension: this.activeTab.dimension,
rows: this.rows,
rowLink: this.rowLink,
+ selectedValues: this.rows
+ .filter((row) => this.isSelected(row))
+ .map((row) => row.value),
},
});
- if (result?.filterRow) {
- this.filter(result.filterRow);
+ if (result?.filterRows) {
+ this.args.applyModalFilters(this.activeTab.filter, result.filterRows);
}
}
@@ -125,23 +112,20 @@ export default class SiteTrafficExplorerBreakdownCard extends Component {
}
@action
- filter(row) {
- const filterKey = this.activeTab.filter;
- this.args.setFilter(filterKey, row);
+ toggleFilter(row) {
+ this.args.toggleFilter(this.activeTab.filter, row);
+ }
- next(() => {
- document
- .querySelector(`#site-traffic-filter-pill-${filterKey} button`)
- ?.focus();
- });
+ @action
+ isSelected(row) {
+ return this.args.isFilterSelected(this.activeTab.filter, row.value);
}
<template>
<section
- class="db-section__row-block site-traffic-explorer__card"
+ class="db-section__row-block"
data-test-site-traffic-card={{@name}}
>
- <h2 class="sr-only">{{@title}}</h2>
<div
class="site-traffic-explorer__tabs"
role="tablist"
@@ -175,66 +159,16 @@ export default class SiteTrafficExplorerBreakdownCard extends Component {
}}
>
<ul class="site-traffic-explorer__breakdown-list">
- {{#each this.visibleRows as |row|}}
+ {{#each this.visibleRows as |row index|}}
<li>
- {{#let (this.rowLink row) as |rowLink|}}
- {{#if rowLink}}
- <span
- class="site-traffic-explorer__row"
- data-test-site-traffic-row
- >
- <a
- href={{rowLink.href}}
- rel={{rowLink.rel}}
- target={{rowLink.target}}
- class="site-traffic-explorer__row-link"
- >
- <SiteTrafficExplorerDimensionLabel
- @dimension={{this.activeTab.dimension}}
- @row={{row}}
- />
- </a>
- <button
- type="button"
- class="site-traffic-explorer__row-filter-area"
- aria-label={{this.filterLabel row}}
- {{on "click" (fn this.filter row)}}
- >
- <SiteTrafficExplorerPageviewCount
- @value={{row.pageviews}}
- as |formattedValue|
- >
- <span class="site-traffic-explorer__row-count">
- {{formattedValue}}
- </span>
- </SiteTrafficExplorerPageviewCount>
- </button>
- </span>
- {{else}}
- <button
- type="button"
- class="site-traffic-explorer__row"
- aria-label={{this.filterLabel row}}
- data-test-site-traffic-row
- {{on "click" (fn this.filter row)}}
- >
- <span class="site-traffic-explorer__row-label">
- <SiteTrafficExplorerDimensionLabel
- @dimension={{this.activeTab.dimension}}
- @row={{row}}
- />
- </span>
- <SiteTrafficExplorerPageviewCount
- @value={{row.pageviews}}
- as |formattedValue|
- >
- <span class="site-traffic-explorer__row-count">
- {{formattedValue}}
- </span>
- </SiteTrafficExplorerPageviewCount>
- </button>
- {{/if}}
- {{/let}}
+ <SiteTrafficExplorerBreakdownRow
+ @row={{row}}
+ @dimension={{this.activeTab.dimension}}
+ @rowLink={{this.rowLink row}}
+ @inputId={{concat "site-traffic-" @name "-filter-" index}}
+ @checked={{this.isSelected row}}
+ @onToggle={{fn this.toggleFilter row}}
+ />
</li>
{{else}}
<li class="site-traffic-explorer__card-empty">
@@ -244,7 +178,7 @@ export default class SiteTrafficExplorerBreakdownCard extends Component {
</ul>
{{#if this.canExpand}}
<DButton
- class="site-traffic-explorer__view-more btn-flat"
+ class="btn-small btn-link --primary"
@action={{this.openModal}}
@label="admin.site_traffic_explorer.view_more"
/>
diff --git a/frontend/discourse/admin/components/site-traffic-explorer-breakdown-modal.gjs b/frontend/discourse/admin/components/site-traffic-explorer-breakdown-modal.gjs
index b30c1439d70..3a16ac16aea 100644
--- a/frontend/discourse/admin/components/site-traffic-explorer-breakdown-modal.gjs
+++ b/frontend/discourse/admin/components/site-traffic-explorer-breakdown-modal.gjs
@@ -1,33 +1,40 @@
import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { concat, fn } from "@ember/helper";
import { action } from "@ember/object";
-import SiteTrafficExplorerDimensionLabel from "discourse/admin/components/site-traffic-explorer-dimension-label";
-import SiteTrafficExplorerPageviewCount from "discourse/admin/components/site-traffic-explorer-pageview-count";
-import { countryName } from "discourse/admin/lib/format-country";
+import SiteTrafficExplorerBreakdownRow from "discourse/admin/components/site-traffic-explorer-breakdown-row";
import DButton from "discourse/ui-kit/d-button";
import DModal from "discourse/ui-kit/d-modal";
-import { i18n } from "discourse-i18n";
export default class SiteTrafficExplorerBreakdownModal extends Component {
+ @tracked selectedValues = [];
+
+ constructor() {
+ super(...arguments);
+ this.selectedValues = [...this.args.model.selectedValues];
+ }
+
get rows() {
return this.args.model.rows.slice(0, 50);
}
@action
- filterLabel(row) {
- const label =
- this.args.model.dimension === "countries"
- ? countryName(row.value)
- : row.label;
+ toggleFilter(row) {
+ this.selectedValues = this.selectedValues.includes(row.value)
+ ? this.selectedValues.filter((value) => value !== row.value)
+ : [...this.selectedValues, row.value];
+ }
- return i18n("admin.site_traffic_explorer.filter_by", {
- label,
- count: row.pageviews,
- });
+ @action
+ isSelected(row) {
+ return this.selectedValues.includes(row.value);
}
@action
- filter(row) {
- this.args.closeModal({ filterRow: row });
+ applyFilters() {
+ this.args.closeModal({
+ filterRows: this.rows.filter((row) => this.isSelected(row)),
+ });
}
<template>
@@ -37,69 +44,28 @@ export default class SiteTrafficExplorerBreakdownModal extends Component {
class="site-traffic-breakdown-modal"
>
<:body>
- <table class="d-table">
- <thead class="d-table__header">
- <tr class="d-table__row">
- <th class="d-table__header-cell" scope="col">
- {{@model.columnLabel}}
- </th>
- <th
- class="d-table__header-cell site-traffic-breakdown-modal__pageviews"
- scope="col"
- >{{i18n "admin.site_traffic_explorer.pageviews"}}</th>
- </tr>
- </thead>
- <tbody class="d-table__body">
- {{#each this.rows as |row|}}
- <tr class="d-table__row">
- <td
- class="d-table__cell --overview site-traffic-breakdown-modal__dimension"
- >
- {{#let (@model.rowLink row) as |rowLink|}}
- {{#if rowLink}}
- <a
- href={{rowLink.href}}
- rel={{rowLink.rel}}
- target={{rowLink.target}}
- class="site-traffic-explorer__row-link"
- >
- <SiteTrafficExplorerDimensionLabel
- @dimension={{@model.dimension}}
- @row={{row}}
- />
- </a>
- {{else}}
- <SiteTrafficExplorerDimensionLabel
- @dimension={{@model.dimension}}
- @row={{row}}
- />
- {{/if}}
- {{/let}}
- </td>
- <td
- class="d-table__cell --detail site-traffic-breakdown-modal__pageviews"
- >
- <div class="d-table__mobile-label">
- {{i18n "admin.site_traffic_explorer.pageviews"}}
- </div>
- <SiteTrafficExplorerPageviewCount
- @value={{row.pageviews}}
- as |formattedValue|
- >
- <DButton
- @display="link"
- @translatedLabel={{formattedValue}}
- @translatedAriaLabel={{this.filterLabel row}}
- @action={{this.filter}}
- @actionParam={{row}}
- />
- </SiteTrafficExplorerPageviewCount>
- </td>
- </tr>
- {{/each}}
- </tbody>
- </table>
+ <ul class="site-traffic-explorer__breakdown-list">
+ {{#each this.rows as |row index|}}
+ <li>
+ <SiteTrafficExplorerBreakdownRow
+ @row={{row}}
+ @dimension={{@model.dimension}}
+ @rowLink={{@model.rowLink row}}
+ @inputId={{concat "site-traffic-expanded-filter-" index}}
+ @checked={{this.isSelected row}}
+ @onToggle={{fn this.toggleFilter row}}
+ />
+ </li>
+ {{/each}}
+ </ul>
</:body>
+ <:footer>
+ <DButton
+ class="btn-primary"
+ @action={{this.applyFilters}}
+ @label="admin.site_traffic_explorer.apply"
+ />
+ </:footer>
</DModal>
</template>
}
diff --git a/frontend/discourse/admin/components/site-traffic-explorer-breakdown-row.gjs b/frontend/discourse/admin/components/site-traffic-explorer-breakdown-row.gjs
new file mode 100644
index 00000000000..c0750baf7f5
--- /dev/null
+++ b/frontend/discourse/admin/components/site-traffic-explorer-breakdown-row.gjs
@@ -0,0 +1,53 @@
+import { on } from "@ember/modifier";
+import SiteTrafficExplorerDimensionLabel from "discourse/admin/components/site-traffic-explorer-dimension-label";
+import SiteTrafficExplorerPageviewCount from "discourse/admin/components/site-traffic-explorer-pageview-count";
+import { i18n } from "discourse-i18n";
+
+function filterLabel(row) {
+ return i18n("admin.site_traffic_explorer.filter_by", {
+ label: row.label,
+ count: row.pageviews,
+ });
+}
+
+export default <template>
+ <label class="site-traffic-explorer__row" data-test-site-traffic-row>
+ <input
+ id={{@inputId}}
+ class="site-traffic-explorer__row-checkbox"
+ type="checkbox"
+ aria-label={{filterLabel @row}}
+ checked={{@checked}}
+ {{on "change" @onToggle}}
+ />
+
+ {{#if @rowLink}}
+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}
+ <a
+ href={{@rowLink.href}}
+ rel={{@rowLink.rel}}
+ target={{@rowLink.target}}
+ class="site-traffic-explorer__row-link"
+ >
+ <SiteTrafficExplorerDimensionLabel
+ @dimension={{@dimension}}
+ @row={{@row}}
+ />
+ </a>
+ {{else}}
+ <SiteTrafficExplorerDimensionLabel
+ @dimension={{@dimension}}
+ @row={{@row}}
+ />
+ {{/if}}
+
+ <span class="site-traffic-explorer__row-count">
+ <SiteTrafficExplorerPageviewCount
+ @value={{@row.pageviews}}
+ as |formattedValue|
+ >
+ {{formattedValue}}
+ </SiteTrafficExplorerPageviewCount>
+ </span>
+ </label>
+</template>
diff --git a/frontend/discourse/admin/components/site-traffic-explorer-filter-pills.gjs b/frontend/discourse/admin/components/site-traffic-explorer-filter-pills.gjs
index 982b91a93f8..4ccbb0c7a00 100644
--- a/frontend/discourse/admin/components/site-traffic-explorer-filter-pills.gjs
+++ b/frontend/discourse/admin/components/site-traffic-explorer-filter-pills.gjs
@@ -1,72 +1,226 @@
import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
import { fn } from "@ember/helper";
import { action } from "@ember/object";
-import { trustHTML } from "@ember/template";
-import { countryName } from "discourse/admin/lib/format-country";
-import { escapeExpression } from "discourse/lib/utilities";
+import { schedule } from "@ember/runloop";
+import DMenu from "discourse/float-kit/components/d-menu";
+import { gt, or } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import dOnResize from "discourse/ui-kit/modifiers/d-on-resize";
import { i18n } from "discourse-i18n";
+const MAX_VISIBLE_FILTER_VALUES = 3;
+
+// Container widths in rem, from the shared scale in lib/breakpoints.scss.
+const VALUE_COUNT_BREAKPOINTS = [
+ { minWidth: 48, count: MAX_VISIBLE_FILTER_VALUES },
+ { minWidth: 40, count: 2 },
+];
+
export default class SiteTrafficExplorerFilterPills extends Component {
+ @tracked maxVisibleValues = MAX_VISIBLE_FILTER_VALUES;
+
+ get applyLabel() {
+ const label = i18n("admin.site_traffic_explorer.apply");
+
+ return this.args.pendingFilterCount > 0
+ ? `${label} (${this.args.pendingFilterCount})`
+ : label;
+ }
+
@action
filterLabel(key) {
return i18n(`admin.site_traffic_explorer.filters.${key}`);
}
@action
- removeLabel(filter) {
- if (filter.key === "traffic_type") {
- return i18n("admin.site_traffic_explorer.remove_traffic_type_filter", {
- value: filter.label,
- });
- }
+ filteringToLabel(filter) {
+ return i18n(`admin.site_traffic_explorer.filtering_to.${filter.key}`, {
+ count: filter.values.length,
+ });
+ }
+ @action
+ removeLabel(filter) {
return i18n("admin.site_traffic_explorer.remove_filter", {
filter: this.filterLabel(filter.key),
});
}
@action
- filterDescription(filter) {
- const value =
- filter.key === "country" ? countryName(filter.value) : filter.label;
+ visibleValues(filter) {
+ return filter.values.slice(0, this.maxVisibleValues);
+ }
+
+ @action
+ remainingCount(filter) {
+ return Math.max(0, filter.values.length - this.maxVisibleValues);
+ }
- return i18n("admin.site_traffic_explorer.filter_description", {
- filter: escapeExpression(this.filterLabel(filter.key)),
- value: escapeExpression(value),
+ @action
+ updateMaxVisibleValues([entry]) {
+ const rootFontSize = parseFloat(
+ getComputedStyle(document.documentElement).fontSize
+ );
+ const width = entry.contentRect.width / rootFontSize;
+ const count =
+ VALUE_COUNT_BREAKPOINTS.find(({ minWidth }) => width >= minWidth)
+ ?.count ?? 1;
+
+ if (this.maxVisibleValues !== count) {
+ this.maxVisibleValues = count;
+ }
+ }
+
+ @action
+ removeValueLabel(value) {
+ return i18n("admin.site_traffic_explorer.remove_filter_value", {
+ value: value.label,
+ });
+ }
+
+ @action
+ removeFilterValue(filter, value) {
+ this.args.removeFilterValue(filter.key, value.value);
+
+ schedule("afterRender", () => {
+ const nextRemoveButton = document.querySelector(
+ "[data-test-site-traffic-filter-dropdown-value] button"
+ );
+ const pillRemoveButton = document.querySelector(
+ `#${this.filterId(filter)} .site-traffic-explorer__filter-remove`
+ );
+ (nextRemoveButton ?? pillRemoveButton)?.focus();
});
}
@action
filterId(filter) {
- const suffix = filter.key === "traffic_type" ? `-${filter.value}` : "";
- return `site-traffic-filter-pill-${filter.key}${suffix}`;
+ return `site-traffic-filter-pill-${filter.key}`;
}
<template>
- {{#if @filters.length}}
+ {{#if (or (gt @filters.length 0) @hasPendingFilters)}}
<div
- class="site-traffic-explorer__filters"
- role="group"
- aria-label={{i18n "admin.site_traffic_explorer.active_filters"}}
+ class="site-traffic-explorer__filter-controls"
+ {{dOnResize this.updateMaxVisibleValues}}
>
- {{#each @filters as |filter|}}
- <span
- class="site-traffic-explorer__filter-pill"
- id={{this.filterId filter}}
- data-test-site-traffic-filter-pill={{filter.key}}
- >
- <span>
- {{trustHTML (this.filterDescription filter)}}
+ <div
+ class="site-traffic-explorer__filters"
+ role="group"
+ aria-label={{i18n "admin.site_traffic_explorer.active_filters"}}
+ >
+ {{#each @filters key="key" as |filter|}}
+ <span
+ class="site-traffic-explorer__filter-pill
+ {{if filter.pending 'is-pending'}}"
+ id={{this.filterId filter}}
+ data-test-site-traffic-filter-pill={{filter.key}}
+ >
+ {{#if (gt filter.values.length 1)}}
+ <DMenu
+ @identifier={{this.filterId filter}}
+ @inline={{true}}
+ @title={{this.filterLabel filter.key}}
+ >
+ <:trigger>
+ {{this.filterLabel filter.key}}:
+ <span class="site-traffic-explorer__filter-pill-values">
+ {{~#each (this.visibleValues filter) as |value index|~}}
+ {{~if index ", "~}}<span
+ class="site-traffic-explorer__filter-pill-value"
+ >{{value.label}}</span>
+ {{~/each~}}
+ </span>
+ {{#if (gt (this.remainingCount filter) 0)}}
+ <span
+ class="site-traffic-explorer__filter-pill-remaining"
+ >+{{this.remainingCount filter}}</span>
+ {{/if}}
+ {{dIcon "angle-down"}}
+ </:trigger>
+ <:content>
+ <DDropdownMenu
+ class="site-traffic-explorer__filter-dropdown"
+ data-test-site-traffic-filter-dropdown
+ as |dropdown|
+ >
+ <dropdown.subheader>{{this.filteringToLabel
+ filter
+ }}</dropdown.subheader>
+
+ {{#each filter.values as |value|}}
+ <dropdown.item
+ data-test-site-traffic-filter-dropdown-value
+ >
+ <DButton
+ @suffixIcon="xmark"
+ @translatedLabel={{value.label}}
+ @translatedAriaLabel={{this.removeValueLabel value}}
+ @translatedTitle={{this.removeValueLabel value}}
+ @action={{fn this.removeFilterValue filter value}}
+ />
+ </dropdown.item>
+ {{/each}}
+
+ <dropdown.divider />
+
+ <dropdown.item>
+ <DButton
+ @label="admin.site_traffic_explorer.clear_all"
+ @action={{fn @clearFilter filter.key}}
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ {{else}}
+ {{this.filterLabel filter.key}}:
+ <span class="site-traffic-explorer__filter-pill-values">
+ {{#each filter.values as |value|}}
+ <strong>{{value.label}}</strong>
+ {{/each}}
+ </span>
+ {{/if}}
+ <DButton
+ class="btn-flat btn-small site-traffic-explorer__filter-remove"
+ @icon="xmark"
+ @translatedAriaLabel={{this.removeLabel filter}}
+ @action={{fn @clearFilter filter.key}}
+ />
</span>
+ {{/each}}
+ </div>
+
+ <div class="site-traffic-explorer__filter-actions">
+ {{#if (gt @filters.length 0)}}
<DButton
- class="btn-flat site-traffic-explorer__filter-remove"
- @icon="xmark"
- @translatedAriaLabel={{this.removeLabel filter}}
- @action={{fn @removeFilter filter.key filter.value}}
+ class="btn-transparent --primary"
+ @label="admin.site_traffic_explorer.clear_all"
+ @action={{@clearAllFilters}}
/>
- </span>
- {{/each}}
+ {{/if}}
+
+ {{#if @hasPendingFilters}}
+ <DButton
+ class="btn-primary site-traffic-explorer__filter-apply"
+ @translatedAriaLabel={{this.applyLabel}}
+ @action={{@applyFilters}}
+ data-test-site-traffic-apply-filters
+ >
+ <span class="d-button-label">{{i18n
+ "admin.site_traffic_explorer.apply"
+ }}</span>
+ {{#if (gt @pendingFilterCount 0)}}
+ <span
+ class="site-traffic-explorer__filter-apply-pending-count"
+ >{{@pendingFilterCount}}</span>
+ {{/if}}
+ </DButton>
+ {{/if}}
+ </div>
</div>
{{/if}}
</template>
diff --git a/frontend/discourse/admin/components/site-traffic-explorer-metric.gjs b/frontend/discourse/admin/components/site-traffic-explorer-metric.gjs
index 3a9d525acf5..1a4429f1a76 100644
--- a/frontend/discourse/admin/components/site-traffic-explorer-metric.gjs
+++ b/frontend/discourse/admin/components/site-traffic-explorer-metric.gjs
@@ -1,38 +1,25 @@
import { concat } from "@ember/helper";
-import SiteTrafficExplorerPageviewCount from "discourse/admin/components/site-traffic-explorer-pageview-count";
import DTooltip from "discourse/float-kit/components/d-tooltip";
import { i18n } from "discourse-i18n";
export default <template>
- <div
- class="site-traffic-explorer__metric {{if @primary '--primary'}}"
- data-test-site-traffic-metric={{@name}}
- >
- {{#if @compact}}
- <SiteTrafficExplorerPageviewCount @value={{@value}} as |formattedValue|>
- <span
- class="db-section__metric-number site-traffic-explorer__metric-value"
- >{{formattedValue}}</span>
- </SiteTrafficExplorerPageviewCount>
- {{else}}
- <span
- class="db-section__metric-number site-traffic-explorer__metric-value"
- >{{@value}}</span>
- {{/if}}
- <span class="site-traffic-explorer__metric-label-row">
- <span
- class="db-section__metric-label site-traffic-explorer__metric-label"
- >{{@label}}</span>
+ <div class="db-section__metric" data-test-site-traffic-metric={{@name}}>
+ <div class="db-section__metric-number">{{@value}}</div>
+
+ <div class="db-section__metric-label">{{@label}}
{{#if @tooltip}}
<DTooltip
class="db-section__info"
@identifier={{concat "site-traffic-explorer-" @name "-tooltip"}}
@icon="far-circle-question"
- @title={{i18n "admin.site_traffic_explorer.metric_information"}}
+ aria-label={{i18n
+ "admin.site_traffic_explorer.metric_information"
+ metric=@label
+ }}
>
<:content>{{@tooltip}}</:content>
</DTooltip>
- {{/if}}
- </span>
+ {{/if}}</div>
+
</div>
</template>
diff --git a/frontend/discourse/admin/components/site-traffic-explorer-pageview-count.gjs b/frontend/discourse/admin/components/site-traffic-explorer-pageview-count.gjs
index e9e0fb3e9b3..12d7b26645d 100644
--- a/frontend/discourse/admin/components/site-traffic-explorer-pageview-count.gjs
+++ b/frontend/discourse/admin/components/site-traffic-explorer-pageview-count.gjs
@@ -1,11 +1,16 @@
import {
formatExactPageviewCount,
formatPageviewCount,
+ isPageviewCountRounded,
} from "discourse/admin/lib/format-pageview-count";
import DTooltip from "discourse/float-kit/components/d-tooltip";
export default <template>
- <DTooltip @content={{formatExactPageviewCount @value}}>
- <:trigger>{{yield (formatPageviewCount @value)}}</:trigger>
- </DTooltip>
+ {{#if (isPageviewCountRounded @value)}}
+ <DTooltip @content={{formatExactPageviewCount @value}}>
+ <:trigger>{{yield (formatPageviewCount @value)}}</:trigger>
+ </DTooltip>
+ {{else}}
+ {{yield (formatPageviewCount @value)}}
+ {{/if}}
</template>
diff --git a/frontend/discourse/admin/components/site-traffic-explorer.gjs b/frontend/discourse/admin/components/site-traffic-explorer.gjs
index bad537c7e3b..f34cc750509 100644
--- a/frontend/discourse/admin/components/site-traffic-explorer.gjs
+++ b/frontend/discourse/admin/components/site-traffic-explorer.gjs
@@ -8,11 +8,15 @@ import DashboardDateRange from "discourse/admin/components/dashboard/date-range"
import SiteTrafficExplorerBreakdownCard from "discourse/admin/components/site-traffic-explorer-breakdown-card";
import SiteTrafficExplorerFilterPills from "discourse/admin/components/site-traffic-explorer-filter-pills";
import SiteTrafficExplorerMetric from "discourse/admin/components/site-traffic-explorer-metric";
+import { formatPageviewCount } from "discourse/admin/lib/format-pageview-count";
import { formatMinutesSeconds } from "discourse/lib/formatter";
import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
import DPageHeader from "discourse/ui-kit/d-page-header";
import I18n, { i18n } from "discourse-i18n";
+const SKELETON_METRICS = Array.from({ length: 4 });
+const SKELETON_BREAKDOWNS = Array.from({ length: 3 });
+const SKELETON_ROWS = Array.from({ length: 5 });
const TRAFFIC_TYPE_BY_SERIES = {
page_view_logged_in_browser: "logged_in",
page_view_anon_browser: "anonymous",
@@ -29,12 +33,6 @@ export default class SiteTrafficExplorer extends Component {
get metrics() {
return [
- {
- name: "pageviews",
- label: i18n("admin.site_traffic_explorer.metrics.pageviews.label"),
- value: this.summary.pageviews ?? 0,
- compact: true,
- },
{
name: "distinct_sessions",
label: i18n(
@@ -73,12 +71,13 @@ export default class SiteTrafficExplorer extends Component {
];
}
- get primaryMetric() {
- return this.metrics[0];
- }
+ get headlineText() {
+ const count = this.summary.pageviews ?? 0;
- get secondaryMetrics() {
- return this.metrics.slice(1);
+ return i18n("admin.site_traffic_explorer.headline", {
+ count,
+ formatted_count: formatPageviewCount(count),
+ });
}
@cached
@@ -175,11 +174,6 @@ export default class SiteTrafficExplorer extends Component {
const availableDate = partial.available_start_date
? moment(partial.available_start_date).format("ll")
: null;
- if (partial.reason === "retention") {
- return i18n("admin.site_traffic_explorer.partial.retention", {
- date: availableDate,
- });
- }
const pageviewLimitStart = moment(partial.pageview_limit_start_at);
const pageviewLimitDate = pageviewLimitStart.format("ll");
@@ -193,6 +187,11 @@ export default class SiteTrafficExplorer extends Component {
pageviewLimitTime,
});
}
+ if (partial.reason === "retention") {
+ return i18n("admin.site_traffic_explorer.partial.retention", {
+ date: availableDate,
+ });
+ }
return i18n("admin.site_traffic_explorer.partial.pageview_limit", {
limit: this.#number(partial.pageview_limit),
date: pageviewLimitDate,
@@ -208,7 +207,7 @@ export default class SiteTrafficExplorer extends Component {
@action
announceResults() {
- if (!this.args.traffic) {
+ if (this.args.loading || !this.args.traffic) {
return;
}
@@ -233,14 +232,13 @@ export default class SiteTrafficExplorer extends Component {
dimension,
filter,
label: i18n(`admin.site_traffic_explorer.dimensions.${dimension}`),
- columnLabel: i18n(`admin.site_traffic_explorer.columns.${dimension}`),
};
}
<template>
<div
- class="site-traffic-explorer admin-config-page"
- {{didUpdate this.announceResults @traffic @hasPageviews}}
+ class="admin-config-page"
+ {{didUpdate this.announceResults @traffic @loading @hasPageviews}}
>
<DPageHeader
@titleLabel={{i18n "admin.site_traffic_explorer.title"}}
@@ -269,16 +267,19 @@ export default class SiteTrafficExplorer extends Component {
</:actions>
</DPageHeader>
- <div class="admin-container site-traffic-explorer__content">
+ <div class="admin-container site-traffic-explorer">
<SiteTrafficExplorerFilterPills
@filters={{@activeFilters}}
- @removeFilter={{@removeFilter}}
+ @hasPendingFilters={{@hasPendingFilters}}
+ @pendingFilterCount={{@pendingFilterCount}}
+ @removeFilterValue={{@removeFilterValue}}
+ @clearFilter={{@clearFilter}}
+ @clearAllFilters={{@clearAllFilters}}
+ @applyFilters={{@applyFilters}}
/>
{{#if @fetchError}}
- <div
- class="db-section__wrapper --column site-traffic-explorer__report"
- >
+ <div class="db-section__wrapper --column">
<div class="db-section__traffic-chart site-traffic-explorer__chart">
<div class="db-section__traffic-chart-message" role="alert">
{{this.fetchErrorMessage}}
@@ -286,7 +287,46 @@ export default class SiteTrafficExplorer extends Component {
</div>
</div>
{{else}}
- {{#if this.partialWarning}}
+ {{#if @loading}}
+ <div
+ class="db-skeleton --animation site-traffic-explorer__skeleton"
+ role="status"
+ aria-label={{i18n "admin.site_traffic_explorer.loading"}}
+ data-test-site-traffic-skeleton
+ >
+ <div class="db-skeleton__section-wrapper">
+ <div class="db-skeleton__subheader">
+ <div class="db-skeleton__subintro">
+ <div class="db-skeleton__heading-line"></div>
+ </div>
+ <div class="db-skeleton__metric-row">
+ {{#each SKELETON_METRICS}}
+ <div class="db-skeleton__metric">
+ <div class="db-skeleton__metric-number"></div>
+ <div class="db-skeleton__metric-label"></div>
+ </div>
+ {{/each}}
+ </div>
+ </div>
+ <div class="db-skeleton__chart"></div>
+ <div class="db-skeleton__row">
+ {{#each SKELETON_BREAKDOWNS}}
+ <div class="db-skeleton__row-block">
+ <div class="db-skeleton__row-block-title"></div>
+ <ul class="db-skeleton__list">
+ {{#each SKELETON_ROWS}}
+ <li class="db-skeleton__list-row">
+ <span class="db-skeleton__list-name"></span>
+ <span class="db-skeleton__list-value"></span>
+ </li>
+ {{/each}}
+ </ul>
+ </div>
+ {{/each}}
+ </div>
+ </div>
+ </div>
+ {{else if this.partialWarning}}
<p
class="alert alert-warning site-traffic-explorer__partial-warning"
data-test-site-traffic-partial-warning
@@ -297,98 +337,82 @@ export default class SiteTrafficExplorer extends Component {
{{/if}}
{{#if @traffic}}
- <div class="site-traffic-explorer__results">
- {{#if @hasPageviews}}
- <div
- class="db-section__wrapper --column site-traffic-explorer__report"
- >
- <section
- class="db-section__subheader site-traffic-explorer__metrics"
- aria-labelledby="site-traffic-explorer-metrics"
- >
- <h2 id="site-traffic-explorer-metrics" class="sr-only">
- {{i18n "admin.site_traffic_explorer.summary"}}
- </h2>
- <div class="db-section__subintro">
+
+ {{#if @hasPageviews}}
+ <div class="db-section__wrapper --column" hidden={{@loading}}>
+ <section class="db-section__subheader">
+ <div class="db-section__subintro">
+ <h3>{{this.headlineText}}</h3>
+ </div>
+
+ <div class="db-section__metrics">
+ {{#each this.metrics as |metric|}}
<SiteTrafficExplorerMetric
- @name={{this.primaryMetric.name}}
- @label={{this.primaryMetric.label}}
- @tooltip={{this.primaryMetric.tooltip}}
- @value={{this.primaryMetric.value}}
- @compact={{this.primaryMetric.compact}}
- @primary={{true}}
+ @name={{metric.name}}
+ @label={{metric.label}}
+ @tooltip={{metric.tooltip}}
+ @value={{metric.value}}
/>
- </div>
- <div class="db-section__metrics">
- {{#each this.secondaryMetrics as |metric|}}
- <SiteTrafficExplorerMetric
- @name={{metric.name}}
- @label={{metric.label}}
- @tooltip={{metric.tooltip}}
- @value={{metric.value}}
- @compact={{metric.compact}}
- />
- {{/each}}
- </div>
- </section>
-
- <div
- class="db-section__traffic-chart site-traffic-explorer__chart"
- aria-label={{i18n
- "admin.site_traffic_explorer.traffic_over_time"
- }}
- >
- <AdminReportStackedChart
- @model={{this.chartModel}}
- @options={{this.chartOptions}}
- class="db-section__traffic-chart-canvas"
- />
- <div class="sr-only">
- {{#each this.series as |series|}}
- <span
- data-test-traffic-series={{series.key}}
- >{{series.total}}</span>
- {{/each}}
- </div>
+ {{/each}}
</div>
+ </section>
- <div class="db-section__row site-traffic-explorer__cards">
- <SiteTrafficExplorerBreakdownCard
- @name="acquisition"
- @title={{i18n
- "admin.site_traffic_explorer.cards.acquisition"
- }}
- @tabs={{this.acquisitionTabs}}
- @dimensions={{@traffic.dimensions}}
- @setFilter={{@setFilter}}
- />
- <SiteTrafficExplorerBreakdownCard
- @name="pages"
- @title={{i18n "admin.site_traffic_explorer.cards.pages"}}
- @tabs={{this.pagesTabs}}
- @dimensions={{@traffic.dimensions}}
- @setFilter={{@setFilter}}
- />
- <SiteTrafficExplorerBreakdownCard
- @name="visitors"
- @title={{i18n
- "admin.site_traffic_explorer.cards.visitors"
- }}
- @tabs={{this.visitorsTabs}}
- @dimensions={{@traffic.dimensions}}
- @setFilter={{@setFilter}}
- />
+ <div class="db-section__traffic-chart">
+ <AdminReportStackedChart
+ @model={{this.chartModel}}
+ @options={{this.chartOptions}}
+ class="db-section__traffic-chart-canvas"
+ />
+ <div class="sr-only">
+ {{#each this.series as |series|}}
+ <span
+ data-test-traffic-series={{series.key}}
+ >{{series.total}}</span>
+ {{/each}}
</div>
</div>
- {{else}}
- <div
- class="site-traffic-explorer__empty"
- data-test-site-traffic-empty
- >
- {{i18n "admin.site_traffic_explorer.empty"}}
+
+ <div class="db-section__row">
+ <SiteTrafficExplorerBreakdownCard
+ @name="acquisition"
+ @title={{i18n
+ "admin.site_traffic_explorer.cards.acquisition"
+ }}
+ @tabs={{this.acquisitionTabs}}
+ @dimensions={{@traffic.dimensions}}
+ @isFilterSelected={{@isFilterSelected}}
+ @toggleFilter={{@toggleFilter}}
+ @applyModalFilters={{@applyModalFilters}}
+ />
+ <SiteTrafficExplorerBreakdownCard
+ @name="pages"
+ @title={{i18n "admin.site_traffic_explorer.cards.pages"}}
+ @tabs={{this.pagesTabs}}
+ @dimensions={{@traffic.dimensions}}
+ @isFilterSelected={{@isFilterSelected}}
+ @toggleFilter={{@toggleFilter}}
+ @applyModalFilters={{@applyModalFilters}}
+ />
+ <SiteTrafficExplorerBreakdownCard
+ @name="visitors"
+ @title={{i18n "admin.site_traffic_explorer.cards.visitors"}}
+ @tabs={{this.visitorsTabs}}
+ @dimensions={{@traffic.dimensions}}
+ @isFilterSelected={{@isFilterSelected}}
+ @toggleFilter={{@toggleFilter}}
+ @applyModalFilters={{@applyModalFilters}}
+ />
</div>
- {{/if}}
- </div>
+ </div>
+ {{else}}
+ <div
+ class="site-traffic-explorer__empty"
+ data-test-site-traffic-empty
+ >
+ {{i18n "admin.site_traffic_explorer.empty"}}
+ </div>
+ {{/if}}
+
{{/if}}
{{/if}}
</div>
diff --git a/frontend/discourse/admin/controllers/admin-site-traffic.js b/frontend/discourse/admin/controllers/admin-site-traffic.js
index 7d4aeb9af9a..278dab205aa 100644
--- a/frontend/discourse/admin/controllers/admin-site-traffic.js
+++ b/frontend/discourse/admin/controllers/admin-site-traffic.js
@@ -7,6 +7,7 @@ import {
PERIOD_CUSTOM,
VALID_PERIODS,
} from "discourse/admin/lib/dashboard-date-range";
+import { countryName } from "discourse/admin/lib/format-country";
import { i18n } from "discourse-i18n";
const FILTER_KEYS = [
@@ -21,6 +22,7 @@ const FILTER_KEYS = [
];
const TRAFFIC_TYPES = ["logged_in", "anonymous", "likely_crawler"];
+const DIMENSION_LIMIT = 50;
const TRAFFIC_TYPE_LABEL_KEYS = {
logged_in: "logged_in_human",
anonymous: "anonymous_human",
@@ -49,6 +51,11 @@ export default class AdminSiteTrafficController extends Controller {
@tracked network = null;
@tracked browser = null;
@tracked ip = null;
+ @tracked traffic = null;
+ @tracked fetchError = null;
+ @tracked draftFilters = Object.fromEntries(
+ FILTER_KEYS.map((key) => [key, []])
+ );
queryParams = ["range", "start_date", "end_date", ...FILTER_KEYS];
@@ -83,59 +90,41 @@ export default class AdminSiteTrafficController extends Controller {
}
get activeFilters() {
- return FILTER_KEYS.flatMap((key) => {
- const values =
- key === "traffic_type"
- ? this.traffic_type === null
- ? []
- : this.selectedTrafficTypes
- : [this[key]];
-
- return values
- .filter((value) => value !== null)
- .map((value) => {
- const rows = this.traffic?.dimensions?.[DIMENSION_KEYS[key]] ?? [];
- const activeFilter = this.traffic?.active_filters?.find(
- (filter) => filter.key === key && filter.value === value
- );
- const label =
- activeFilter?.label ??
- rows.find((row) => row.value === value)?.label;
-
- return {
- key,
- value,
- label:
- label ??
- (key === "traffic_type"
- ? i18n(
- `admin.site_traffic_explorer.series.${TRAFFIC_TYPE_LABEL_KEYS[value]}`
- )
- : key === "referrer" && value === ""
- ? i18n("admin.site_traffic_explorer.direct_or_unknown")
- : value),
- };
- });
- });
+ const pending = this.hasPendingFilters;
+
+ return FILTER_KEYS.filter((key) => this.draftFilters[key].length).map(
+ (key) => ({
+ key,
+ pending,
+ values: this.draftFilters[key].map((value) => ({
+ value,
+ label: this.#filterLabel(key, value),
+ })),
+ })
+ );
}
get selectedTrafficTypes() {
- if (this.traffic_type === null) {
+ const values = this.draftFilters.traffic_type;
+ if (values.length === 0) {
return TRAFFIC_TYPES;
}
- const selected = this.traffic_type.split(",");
- return TRAFFIC_TYPES.filter((trafficType) =>
- selected.includes(trafficType)
- );
+ return TRAFFIC_TYPES.filter((trafficType) => values.includes(trafficType));
}
- get traffic() {
- return this.model?.traffic ?? null;
+ get hasPendingFilters() {
+ return FILTER_KEYS.some(
+ (key) =>
+ !this.#sameValues(this.draftFilters[key], this.#appliedValues(key))
+ );
}
- get fetchError() {
- return this.model?.fetchError ?? null;
+ get pendingFilterCount() {
+ return FILTER_KEYS.reduce(
+ (count, key) => count + this.draftFilters[key].length,
+ 0
+ );
}
#customDate(value, edge) {
@@ -147,8 +136,62 @@ export default class AdminSiteTrafficController extends Controller {
return parsed.isValid() ? parsed[edge]("day").toDate() : null;
}
+ #decorateTraffic(traffic) {
+ const countries = traffic.dimensions?.countries ?? [];
+ const activeFilters = (traffic.active_filters ?? []).map((filter) =>
+ filter.key === "country"
+ ? { ...filter, label: countryName(filter.value) }
+ : filter
+ );
+ const dimensions = {
+ ...traffic.dimensions,
+ countries: countries.map((row) => ({
+ ...row,
+ label: countryName(row.value),
+ })),
+ };
+
+ for (const [filterKey, dimensionKey] of Object.entries(DIMENSION_KEYS)) {
+ const rows = dimensions[dimensionKey] ?? [];
+ const activeRows = activeFilters.filter(
+ (filter) => filter.key === filterKey
+ );
+ if (activeRows.length === 0) {
+ continue;
+ }
+
+ const activeValues = new Set(activeRows.map((filter) => filter.value));
+ const rowsByValue = new Map(rows.map((row) => [row.value, row]));
+ dimensions[dimensionKey] = [
+ ...activeRows.map(
+ (filter) =>
+ rowsByValue.get(filter.value) ?? {
+ value: filter.value,
+ label: filter.label,
+ pageviews: 0,
+ }
+ ),
+ ...rows.filter((row) => !activeValues.has(row.value)),
+ ].slice(0, DIMENSION_LIMIT);
+ }
+
+ return {
+ ...traffic,
+ dimensions,
+ active_filters: activeFilters,
+ };
+ }
+
+ loadTraffic(model) {
+ this.#resetDraftFilters();
+ this.traffic = model.traffic ? this.#decorateTraffic(model.traffic) : null;
+ this.fetchError = model.fetchError;
+ this.#reconcileFilters(this.traffic?.active_filters ?? []);
+ }
+
@action
setPeriod(period) {
+ this.#resetDraftFilters();
this.range = period;
this.start_date = null;
this.end_date = null;
@@ -156,14 +199,21 @@ export default class AdminSiteTrafficController extends Controller {
@action
setCustomDateRange(startDate, endDate) {
+ this.#resetDraftFilters();
this.range = PERIOD_CUSTOM;
this.start_date = moment(startDate).format("YYYY-MM-DD");
this.end_date = moment(endDate).format("YYYY-MM-DD");
}
@action
- setFilter(key, row) {
- this[key] = row.value;
+ toggleFilter(key, row) {
+ const values = this.draftFilters[key];
+ this.#setDraftValues(
+ key,
+ values.includes(row.value)
+ ? values.filter((value) => value !== row.value)
+ : [...values, row.value]
+ );
}
@action
@@ -173,42 +223,158 @@ export default class AdminSiteTrafficController extends Controller {
? selectedTrafficTypes.filter((selected) => selected !== trafficType)
: [...selectedTrafficTypes, trafficType];
- this.#setTrafficTypes(nextTrafficTypes);
+ this.#setDraftValues(
+ "traffic_type",
+ nextTrafficTypes.length === TRAFFIC_TYPES.length ? [] : nextTrafficTypes
+ );
}
@action
- removeFilter(key, value) {
- if (key === "traffic_type") {
- const remainingTrafficTypes = this.selectedTrafficTypes.filter(
- (trafficType) => trafficType !== value
- );
- this.#setTrafficTypes(remainingTrafficTypes);
- return;
+ removeFilterValue(key, value) {
+ this.#setDraftValues(
+ key,
+ this.draftFilters[key].filter((item) => item !== value)
+ );
+ }
+
+ @action
+ clearFilter(key) {
+ this.#setDraftValues(key, []);
+ }
+
+ @action
+ clearAllFilters() {
+ this.draftFilters = Object.fromEntries(FILTER_KEYS.map((key) => [key, []]));
+
+ for (const key of FILTER_KEYS) {
+ this[key] = null;
}
+ }
- this[key] = null;
+ @action
+ applyFilters() {
+ for (const key of FILTER_KEYS) {
+ this[key] = this.#serializeValues(this.draftFilters[key]);
+ }
+ }
+
+ @action
+ applyModalFilters(key, rows) {
+ this.#setDraftValues(
+ key,
+ rows.map((row) => row.value)
+ );
+ }
+
+ @action
+ isFilterSelected(key, value) {
+ return this.draftFilters[key].includes(value);
}
@action
resetState() {
- this.model = null;
this.range = DEFAULT_PERIOD;
this.start_date = null;
this.end_date = null;
for (const key of FILTER_KEYS) {
this[key] = null;
}
+ this.#resetDraftFilters();
+ this.traffic = null;
+ this.fetchError = null;
+ }
+
+ #appliedValues(key) {
+ const value = this[key];
+ if (value === null) {
+ return [];
+ }
+
+ if (value.startsWith("[")) {
+ try {
+ const values = JSON.parse(value);
+ if (
+ Array.isArray(values) &&
+ values.every((item) => typeof item === "string")
+ ) {
+ return values;
+ }
+ } catch {
+ // The server will validate malformed values when the request runs.
+ }
+ }
+
+ return key === "traffic_type" ? value.split(",") : [value];
}
- #setTrafficTypes(trafficTypes) {
- const orderedTrafficTypes = TRAFFIC_TYPES.filter((trafficType) =>
- trafficTypes.includes(trafficType)
+ #filterLabel(key, value) {
+ const rows = this.traffic?.dimensions?.[DIMENSION_KEYS[key]] ?? [];
+ const activeFilter = this.traffic?.active_filters?.find(
+ (filter) => filter.key === key && filter.value === value
);
+ const label =
+ activeFilter?.label ?? rows.find((row) => row.value === value)?.label;
+
+ if (label) {
+ return label;
+ }
+ if (key === "traffic_type") {
+ return i18n(
+ `admin.site_traffic_explorer.series.${TRAFFIC_TYPE_LABEL_KEYS[value]}`
+ );
+ }
+ if (key === "referrer" && value === "") {
+ return i18n("admin.site_traffic_explorer.direct_or_unknown");
+ }
+ return value;
+ }
+
+ #resetDraftFilters() {
+ this.draftFilters = Object.fromEntries(
+ FILTER_KEYS.map((key) => [key, [...this.#appliedValues(key)]])
+ );
+ }
+
+ #reconcileFilters(activeFilters) {
+ const filters = Object.fromEntries(FILTER_KEYS.map((key) => [key, []]));
- this.traffic_type =
- orderedTrafficTypes.length === 0 ||
- orderedTrafficTypes.length === TRAFFIC_TYPES.length
- ? null
- : orderedTrafficTypes.join(",");
+ for (const filter of activeFilters) {
+ filters[filter.key].push(filter.value);
+ }
+ for (const key of FILTER_KEYS) {
+ if (!this.#sameValues(filters[key], this.#appliedValues(key))) {
+ this[key] = this.#serializeValues(filters[key]);
+ }
+ }
+
+ this.draftFilters = filters;
+ }
+
+ #setDraftValues(key, values) {
+ this.draftFilters = { ...this.draftFilters, [key]: values };
+
+ const hasDraftFilters = FILTER_KEYS.some(
+ (filterKey) => this.draftFilters[filterKey].length
+ );
+ const hasAppliedFilters = FILTER_KEYS.some(
+ (filterKey) => this.#appliedValues(filterKey).length
+ );
+ if (!hasDraftFilters && hasAppliedFilters) {
+ this.applyFilters();
+ }
+ }
+
+ #sameValues(first, second) {
+ return (
+ first.length === second.length &&
+ first.every((value, index) => value === second[index])
+ );
+ }
+
+ #serializeValues(values) {
+ if (values.length === 0) {
+ return null;
+ }
+ return values.length === 1 ? values[0] : JSON.stringify(values);
}
}
diff --git a/frontend/discourse/admin/lib/format-pageview-count.js b/frontend/discourse/admin/lib/format-pageview-count.js
index 835af5a91b9..f1430cb8841 100644
--- a/frontend/discourse/admin/lib/format-pageview-count.js
+++ b/frontend/discourse/admin/lib/format-pageview-count.js
@@ -1,18 +1,42 @@
import I18n from "discourse-i18n";
+function truncateToUnit(value, unit) {
+ return Math.floor(value / unit) * unit;
+}
+
export function formatPageviewCount(value) {
if (value >= 1_000_000) {
- const formatted = I18n.toNumber(value / 1_000_000, { precision: 1 });
+ const truncated = truncateToUnit(value, 100_000);
+ const formatted = I18n.toNumber(truncated / 1_000_000, { precision: 1 });
return `${formatted.replace(/[,.]0$/, "")}M`;
}
+ if (value >= 10_000) {
+ const truncated = truncateToUnit(value, 1_000);
+ return `${I18n.toNumber(truncated / 1_000, { precision: 0 })}K`;
+ }
+
if (value >= 1_000) {
- return `${I18n.toNumber(Math.round(value / 1_000), { precision: 0 })}K`;
+ const truncated = truncateToUnit(value, 100);
+ const formatted = I18n.toNumber(truncated / 1_000, { precision: 1 });
+ return `${formatted.replace(/[,.]0$/, "")}K`;
}
return I18n.toNumber(value, { precision: 0 });
}
+export function isPageviewCountRounded(value) {
+ if (value >= 1_000_000) {
+ return value % 100_000 !== 0;
+ }
+
+ if (value >= 10_000) {
+ return value % 1_000 !== 0;
+ }
+
+ return value >= 1_000 && value % 100 !== 0;
+}
+
export function formatExactPageviewCount(value) {
return I18n.toNumber(value, { precision: 0 });
}
diff --git a/frontend/discourse/admin/routes/admin-site-traffic.js b/frontend/discourse/admin/routes/admin-site-traffic.js
index dd3d8cde450..42696583a9c 100644
--- a/frontend/discourse/admin/routes/admin-site-traffic.js
+++ b/frontend/discourse/admin/routes/admin-site-traffic.js
@@ -69,6 +69,11 @@ export default class AdminSiteTrafficRoute extends DiscourseRoute {
}));
}
+ setupController(controller, model) {
+ super.setupController(controller, model);
+ controller.loadTraffic(model);
+ }
+
@action
loading(transition) {
if (!this.controllerFor("admin-site-traffic").model) {
@@ -132,8 +137,9 @@ export default class AdminSiteTrafficRoute extends DiscourseRoute {
};
for (const key of FILTER_KEYS) {
- if (params[key] !== null && params[key] !== undefined) {
- requestParams[key] = params[key];
+ const values = this.#filterValues(key, params[key]);
+ if (values.length) {
+ requestParams[key] = values;
}
}
@@ -145,9 +151,35 @@ export default class AdminSiteTrafficRoute extends DiscourseRoute {
return TRAFFIC_TYPES;
}
- const selected = value.split(",");
+ const selected = this.#filterValues("traffic_type", value);
return TRAFFIC_TYPES.filter((trafficType) =>
selected.includes(trafficType)
);
}
+
+ #filterValues(key, value) {
+ if (value === null || value === undefined) {
+ return [];
+ }
+
+ if (value === "") {
+ return key === "referrer" ? [value] : [];
+ }
+
+ if (value.startsWith("[")) {
+ try {
+ const values = JSON.parse(value);
+ if (
+ Array.isArray(values) &&
+ values.every((item) => typeof item === "string")
+ ) {
+ return values;
+ }
+ } catch {
+ return [];
+ }
+ }
+
+ return key === "traffic_type" ? value.split(",") : [value];
+ }
}
diff --git a/frontend/discourse/admin/templates/admin-site-traffic.gjs b/frontend/discourse/admin/templates/admin-site-traffic.gjs
index ca8fe126e56..845bebe290a 100644
--- a/frontend/discourse/admin/templates/admin-site-traffic.gjs
+++ b/frontend/discourse/admin/templates/admin-site-traffic.gjs
@@ -9,11 +9,18 @@ export default <template>
@startDate={{@controller.startDate}}
@endDate={{@controller.endDate}}
@activeFilters={{@controller.activeFilters}}
+ @hasPendingFilters={{@controller.hasPendingFilters}}
+ @pendingFilterCount={{@controller.pendingFilterCount}}
@trafficTypes={{@controller.selectedTrafficTypes}}
@setPeriod={{@controller.setPeriod}}
@setCustomDateRange={{@controller.setCustomDateRange}}
- @setFilter={{@controller.setFilter}}
+ @toggleFilter={{@controller.toggleFilter}}
+ @isFilterSelected={{@controller.isFilterSelected}}
@toggleTrafficType={{@controller.toggleTrafficType}}
- @removeFilter={{@controller.removeFilter}}
+ @removeFilterValue={{@controller.removeFilterValue}}
+ @clearFilter={{@controller.clearFilter}}
+ @clearAllFilters={{@controller.clearAllFilters}}
+ @applyFilters={{@controller.applyFilters}}
+ @applyModalFilters={{@controller.applyModalFilters}}
/>
</template>
diff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rb
index eb72f1c6952..b6d0c07b853 100644
--- a/spec/requests/admin/dashboard_controller_spec.rb
+++ b/spec/requests/admin/dashboard_controller_spec.rb
@@ -1552,51 +1552,83 @@ RSpec.describe Admin::DashboardController do
)
end
- it "applies the direct referrer filter" do
+ it "matches any selected value within a dimension and every selected dimension" do
+ referrers = ["search.example/results?q=discourse", ""]
+
get "/admin/dashboard/site-traffic-explorer.json",
- params: request_params.merge(referrer: "")
+ params: request_params.merge(referrer: referrers)
+
+ expect(response.parsed_body.slice("summary", "active_filters")).to eq(
+ "summary" => {
+ "pageviews" => 2,
+ "distinct_sessions" => 2,
+ "logged_in_share" => 50,
+ "bounce_rate" => 50,
+ "average_session_duration_seconds" => 30,
+ },
+ "active_filters" => [
+ {
+ "key" => "referrer",
+ "value" => "search.example/results?q=discourse",
+ "label" => "search.example/results?q=discourse",
+ },
+ { "key" => "referrer", "value" => "", "label" => "Direct / unknown" },
+ ],
+ )
- expect(status: response.status, body: response.parsed_body).to eq(
- status: 200,
- body: {
- "partial_data" => nil,
- "summary" => {
- "pageviews" => 1,
- "distinct_sessions" => 1,
- "logged_in_share" => 0,
- "bounce_rate" => 100,
- "average_session_duration_seconds" => 0,
+ get "/admin/dashboard/site-traffic-explorer.json",
+ params: request_params.merge(referrer: referrers, country: ["US"])
+
+ expect(response.parsed_body.slice("summary", "active_filters")).to eq(
+ "summary" => {
+ "pageviews" => 1,
+ "distinct_sessions" => 1,
+ "logged_in_share" => 100,
+ "bounce_rate" => 0,
+ "average_session_duration_seconds" => 60,
+ },
+ "active_filters" => [
+ {
+ "key" => "referrer",
+ "value" => "search.example/results?q=discourse",
+ "label" => "search.example/results?q=discourse",
},
- "series" => [
- {
- "date" => "2026-05-11",
- "pageviews" => 1,
- "logged_in_human_pageviews" => 0,
- "anonymous_human_pageviews" => 1,
- "likely_crawler_pageviews" => 0,
- },
- ],
- "series_colors" => series_colors,
- "dimensions" => {
- "top_urls" => [{ "value" => "/top", "label" => "/top", "pageviews" => 1 }],
- "entry_urls" => [{ "value" => "/top", "label" => "/top", "pageviews" => 1 }],
- "referrers" => [{ "value" => "", "label" => "Direct / unknown", "pageviews" => 1 }],
- "countries" => [{ "value" => "GB", "label" => "United Kingdom", "pageviews" => 1 }],
- "networks" => [
- { "value" => "AS64496", "label" => "Example Network (AS64496)", "pageviews" => 1 },
- ],
- "browsers" => [{ "value" => "firefox", "label" => "Firefox", "pageviews" => 1 }],
- "ip_addresses" => [
- { "value" => "198.51.100.2", "label" => "198.51.100.2", "pageviews" => 1 },
- ],
+ { "key" => "referrer", "value" => "", "label" => "Direct / unknown" },
+ { "key" => "country", "value" => "US", "label" => "United States" },
+ ],
+ )
+ expect(response.parsed_body.dig("dimensions", "referrers")).to eq(
+ [
+ {
+ "value" => "search.example/results?q=discourse",
+ "label" => "search.example/results?q=discourse",
+ "pageviews" => 1,
},
- "active_filters" => [
- { "key" => "referrer", "value" => "", "label" => "Direct / unknown" },
- ],
- },
+ ],
)
end
+ it "rejects object-shaped filter values" do
+ get "/admin/dashboard/site-traffic-explorer.json",
+ params: request_params.merge(country: { nested: "US" })
+
+ expect(response.status).to eq(400)
+ end
+
+ it "accepts the dimension limit and rejects one more filter value" do
+ referrers = 50.times.map { |index| "referrer-#{index}.example" }
+
+ get "/admin/dashboard/site-traffic-explorer.json",
+ params: request_params.merge(referrer: referrers)
+
+ expect(response.status).to eq(200)
+
+ get "/admin/dashboard/site-traffic-explorer.json",
+ params: request_params.merge(referrer: [*referrers, "one-too-many.example"])
+
+ expect(response.status).to eq(400)
+ end
+
it "treats same-site referrers as internal navigation" do
same_site_pageview =
Fabricate(
diff --git a/spec/system/admin_dashboard_redesign/site_traffic_explorer_spec.rb b/spec/system/admin_dashboard_redesign/site_traffic_explorer_spec.rb
index 347fa66f8ae..ca0d636aa11 100644
--- a/spec/system/admin_dashboard_redesign/site_traffic_explorer_spec.rb
+++ b/spec/system/admin_dashboard_redesign/site_traffic_explorer_spec.rb
@@ -60,8 +60,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
)
traffic.visit(start_date: "2026-05-01", end_date: "2026-05-12")
-
- expect(traffic).to have_metric(label: "Pageviews", value: "1")
expect(traffic).to have_series_total(label: "anonymous-human", value: "1")
expect(traffic).to have_no_series(label: "likely-crawler")
end
@@ -96,8 +94,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
)
traffic.visit(start_date: "2026-05-14", end_date: "2026-05-14")
-
- expect(traffic).to have_metric(label: "Pageviews", value: "2")
expect(traffic).to have_metric(label: "Distinct sessions", value: "2")
expect(traffic).to have_metric(label: "Bounce rate", value: "50%")
expect(traffic).to have_metric(label: "Average session duration", value: "10s")
@@ -180,7 +176,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
expect(traffic).to have_page_title
expect(traffic).to have_date_range("May 1, 2026 – May 12, 2026")
expect(traffic).to have_no_filter_pills
- expect(traffic).to have_metric(label: "Pageviews", value: "4")
expect(traffic).to have_metric(label: "Distinct sessions", value: "3")
expect(traffic).to have_metric(label: "Logged-in share", value: "50%")
expect(traffic).to have_metric(label: "Bounce rate", value: "67%")
@@ -195,9 +190,10 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
end_date: "2026-05-12",
traffic_type: "logged_in,anonymous",
)
- expect(traffic).to have_filter_pill(dimension: "traffic_type", label: "Logged in")
- expect(traffic).to have_filter_pill(dimension: "traffic_type", label: "Anonymous")
- expect(traffic).to have_metric(label: "Pageviews", value: "3")
+ expect(traffic).to have_grouped_filter_pill(
+ dimension: "traffic_type",
+ label: "Traffic type: Logged in, Anonymous",
+ )
expect(traffic).to have_metric(label: "Distinct sessions", value: "2")
expect(traffic).to have_series_total(label: "logged-in-human", value: "2")
expect(traffic).to have_series_total(label: "anonymous-human", value: "1")
@@ -208,24 +204,19 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
traffic.go_back
expect(traffic).to have_no_filter_pills
- expect(traffic).to have_metric(label: "Pageviews", value: "4")
traffic.go_forward
- expect(traffic).to have_filter_pill(dimension: "traffic_type", label: "Logged in")
- expect(traffic).to have_filter_pill(dimension: "traffic_type", label: "Anonymous")
+ expect(traffic).to have_grouped_filter_pill(
+ dimension: "traffic_type",
+ label: "Traffic type: Logged in, Anonymous",
+ )
expect(traffic).to have_metric(label: "Distinct sessions", value: "2")
- traffic.remove_filter("traffic_type", label: "Logged in")
- expect(traffic).to have_filter_pill(dimension: "traffic_type", label: "Anonymous")
- expect(traffic).to have_metric(label: "Pageviews", value: "1")
-
- traffic.remove_filter("traffic_type", label: "Anonymous")
+ traffic.remove_filter("traffic_type")
expect(traffic).to have_no_filter_pills
- expect(traffic).to have_metric(label: "Pageviews", value: "4")
traffic.visit(start_date: "2026-05-01", end_date: "2026-05-12", traffic_type: "likely_crawler")
expect(traffic).to have_filter_pill(dimension: "traffic_type", label: "Likely crawlers")
- expect(traffic).to have_metric(label: "Pageviews", value: "1")
expect(traffic).to have_metric(label: "Distinct sessions", value: "1")
expect(traffic).to have_series_total(label: "logged-in-human", value: "0")
expect(traffic).to have_series_total(label: "anonymous-human", value: "0")
@@ -234,7 +225,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
"/admin/dashboard/site-traffic-explorer?end_date=2026-05-12&range=custom&start_date=2026-05-01&traffic_type=likely_crawler",
)
traffic.remove_filter("traffic_type", label: "Likely crawlers")
- expect(traffic).to have_metric(label: "Pageviews", value: "4")
expect(traffic).to have_card_tabs(card: "acquisition", tabs: %w[Referrers Countries Networks])
expect(traffic).to have_card_tabs(card: "pages", tabs: ["Top URLs", "Entry URLs"])
@@ -251,9 +241,8 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
traffic.select_tab(card: "pages", tab: "Entry URLs")
expect(traffic).to have_row(card: "pages", label: "/latest", count: "1")
expect(traffic).to have_url_link(card: "pages", label: "/latest", href: "/latest")
- traffic.filter_row(card: "pages", label: "/latest")
+ traffic.filter_by_clicking_row(card: "pages", label: "/latest")
expect(traffic).to have_filter_pill(dimension: "entry_url", label: "/latest")
- expect(traffic).to have_metric(label: "Pageviews", value: "1")
expect(page).to have_current_path(
"/admin/dashboard/site-traffic-explorer?end_date=2026-05-12&entry_url=%2Flatest&range=custom&start_date=2026-05-01",
)
@@ -261,7 +250,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
traffic.filter_row(card: "acquisition", label: "Direct / unknown")
expect(traffic).to have_filter_pill(dimension: "referrer", label: "Direct / unknown")
- expect(traffic).to have_metric(label: "Pageviews", value: "2")
expect(page).to have_current_path(
"/admin/dashboard/site-traffic-explorer?end_date=2026-05-12&range=custom&referrer=&start_date=2026-05-01",
)
@@ -272,7 +260,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
dimension: "referrer",
label: "search.example/results?q=discourse",
)
- expect(traffic).to have_metric(label: "Pageviews", value: "1")
expect(page).to have_current_path(
"/admin/dashboard/site-traffic-explorer?end_date=2026-05-12&range=custom&referrer=search.example%2Fresults%3Fq%3Ddiscourse&start_date=2026-05-01",
)
@@ -281,7 +268,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
traffic.select_tab(card: "acquisition", tab: "Networks")
traffic.filter_row(card: "acquisition", label: "Example Network (AS64496)")
expect(traffic).to have_filter_pill(dimension: "network", label: "Example Network (AS64496)")
- expect(traffic).to have_metric(label: "Pageviews", value: "2")
expect(page).to have_current_path(
"/admin/dashboard/site-traffic-explorer?end_date=2026-05-12&network=AS64496&range=custom&start_date=2026-05-01",
)
@@ -290,7 +276,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
traffic.select_tab(card: "visitors", tab: "Browsers")
traffic.filter_row(card: "visitors", label: "Google Chrome")
expect(traffic).to have_filter_pill(dimension: "browser", label: "Google Chrome")
- expect(traffic).to have_metric(label: "Pageviews", value: "3")
expect(page).to have_current_path(
"/admin/dashboard/site-traffic-explorer?browser=chrome&end_date=2026-05-12&range=custom&start_date=2026-05-01",
)
@@ -299,7 +284,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
traffic.select_tab(card: "acquisition", tab: "Countries")
traffic.filter_row(card: "acquisition", label: "United States")
expect(traffic).to have_filter_pill(dimension: "country", label: "United States")
- expect(traffic).to have_metric(label: "Pageviews", value: "3")
expect(traffic).to have_metric(label: "Logged-in share", value: "67%")
expect(traffic).to have_metric(label: "Distinct sessions", value: "2")
expect(traffic).to have_metric(label: "Bounce rate", value: "50%")
@@ -308,14 +292,11 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
)
traffic.remove_filter("country")
- expect(traffic).to have_metric(label: "Pageviews", value: "4")
traffic.select_tab(card: "acquisition", tab: "Countries")
traffic.filter_row(card: "acquisition", label: "United Kingdom")
expect(traffic).to have_filter_pill(dimension: "country", label: "United Kingdom")
- expect(traffic).to have_metric(label: "Pageviews", value: "1")
traffic.remove_filter("country")
- expect(traffic).to have_metric(label: "Pageviews", value: "4")
traffic.select_tab(card: "acquisition", tab: "Countries")
traffic.filter_row(card: "acquisition", label: "United States")
expect(traffic).to have_filter_pill(dimension: "country", label: "United States")
@@ -324,7 +305,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
traffic.filter_row(card: "pages", label: "/top")
expect(traffic).to have_filter_pill(dimension: "country", label: "United States")
expect(traffic).to have_filter_pill(dimension: "top_url", label: "/top")
- expect(traffic).to have_metric(label: "Pageviews", value: "1")
expect(traffic).to have_metric(label: "Distinct sessions", value: "1")
expect(traffic).to have_metric(label: "Bounce rate", value: "0%")
expect(page).to have_current_path(
@@ -343,7 +323,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
expect(traffic).to have_filter_pill(dimension: "country", label: "United States")
expect(traffic).to have_filter_pill(dimension: "top_url", label: "/top")
expect(traffic).to have_filter_pill(dimension: "ip", label: "192.0.2.1")
- expect(traffic).to have_metric(label: "Pageviews", value: "1")
expect(page).to have_current_path(
"/admin/dashboard/site-traffic-explorer?country=US&end_date=2026-05-12&ip=192.0.2.1&range=custom&start_date=2026-05-01&top_url=%2Ftop",
)
@@ -353,7 +332,6 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
traffic.remove_filter("ip")
expect(traffic).to have_no_filter_pills
- expect(traffic).to have_metric(label: "Pageviews", value: "4")
traffic.select_date_preset("Last 7 days")
@@ -372,11 +350,11 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
time: Time.zone.local(2026, 5, 14, 12, 0, 0) do
sign_in(admin)
- additional_path = nil
+ additional_paths = []
9.times do |index|
topic = Fabricate(:topic, title: "Traffic topic #{index}")
path = "/t/#{topic.slug}/#{topic.id}"
- additional_path = path if index == 8
+ additional_paths << path if index >= 7
event_count = 9 - index
event_count.times do |event_index|
Fabricate(
@@ -390,16 +368,127 @@ RSpec.describe "Admin Dashboard Redesign | Site Traffic Explorer" do
end
traffic.visit(start_date: "2026-05-01", end_date: "2026-05-12")
+ traffic.select_filter_row(card: "visitors", label: "Unknown browser")
traffic.expand("pages")
- expect(traffic).to have_expanded_table(title: "Top URLs", column: "URL")
- expect(traffic).to have_expanded_url_link(label: additional_path)
+ expect(traffic).to have_expanded_breakdown(title: "Top URLs")
+ additional_paths.each { |path| expect(traffic).to have_expanded_url_link(label: path) }
+
+ additional_paths.each { |path| traffic.select_expanded_filter_row(label: path) }
+
+ expect(traffic).to have_expanded_breakdown(title: "Top URLs")
+ traffic.apply_expanded_filters
+
+ expect(traffic).to have_grouped_filter_pill(
+ dimension: "top_url",
+ label: "Top URL: #{additional_paths.first}, #{additional_paths.second}",
+ )
+ expect(traffic).to have_filter_pill(dimension: "browser", label: "Unknown browser")
+ expect(traffic).to have_no_expanded_breakdown
+ expect(traffic).to have_apply_filters(count: 3)
+ traffic.apply_filters
+
+ expect(traffic).to have_no_apply_filters
+ expected_path =
+ "/admin/dashboard/site-traffic-explorer?browser=unknown&end_date=2026-05-12&" \
+ "range=custom&start_date=2026-05-01&" \
+ "top_url=#{ERB::Util.url_encode(additional_paths.to_json)}"
+ expect(page).to have_current_path(expected_path)
+ end
+
+ it "lets an admin review and apply several filter values together",
+ time: Time.zone.local(2026, 5, 14, 12, 0, 0) do
+ sign_in(admin)
+
+ [
+ %w[/first one.example US first-session],
+ %w[/second two.example US second-session],
+ %w[/third one.example GB third-session],
+ ["/fourth", nil, "US", "fourth-session"],
+ %w[/fifth three.example US fifth-session],
+ ].each do |url, normalized_referrer, country_code, session_id|
+ Fabricate(
+ :browser_pageview_event,
+ url: url,
+ country_code: country_code,
+ ip_address: country_code == "US" ? "192.0.2.1" : "198.51.100.2",
+ normalized_referrer: normalized_referrer,
+ normalized_referrer_version: BrowserPageviewEventUrlNormalizer::REFERRER_VERSION,
+ session_id: session_id,
+ source: BrowserPageviewEvent::SOURCE_BEACON,
+ created_at: "2026-05-10 10:00:00",
+ )
+ end
+
+ traffic.visit(start_date: "2026-05-01", end_date: "2026-05-12")
+
+ traffic.select_filter_row(card: "acquisition", label: "one.example")
+ traffic.select_filter_row(card: "acquisition", label: "two.example")
+ traffic.select_filter_row(card: "acquisition", label: "three.example")
+ traffic.select_filter_row(card: "acquisition", label: "Direct / unknown")
+ traffic.select_tab(card: "acquisition", tab: "Countries")
+ traffic.select_filter_row(card: "acquisition", label: "United States")
+
+ expect(traffic).to have_grouped_filter_pill(
+ dimension: "referrer",
+ label: "Referrer: one.example, two.example, three.example +1",
+ )
+ expect(traffic).to have_filter_pill(dimension: "country", label: "United States")
+ expect(traffic).to have_apply_filters(count: 5)
+ expect(page).to have_current_path(
+ "/admin/dashboard/site-traffic-explorer?end_date=2026-05-12&range=custom&start_date=2026-05-01",
+ )
+
+ traffic.expand_filter_pill("referrer")
+
+ expect(traffic).to have_filter_dropdown(
+ values: ["one.example", "two.example", "three.example", "Direct / unknown"],
+ )
+ traffic.remove_filter_value("three.example")
+
+ expect(traffic).to have_filter_dropdown(
+ values: ["one.example", "two.example", "Direct / unknown"],
+ )
+ traffic.expand_filter_pill("referrer")
+
+ expect(traffic).to have_grouped_filter_pill(
+ dimension: "referrer",
+ label: "Referrer: one.example, two.example, Direct / unknown",
+ )
+
+ traffic.select_tab(card: "acquisition", tab: "Referrers")
+
+ expect(traffic).to have_filter_row_selected(card: "acquisition", label: "one.example")
+ expect(traffic).to have_filter_row_unselected(card: "acquisition", label: "three.example")
+
+ traffic.select_filter_row(card: "acquisition", label: "Direct / unknown")
+ traffic.select_filter_row(card: "acquisition", label: "three.example")
+ traffic.apply_filters
- traffic.filter_expanded_row(label: additional_path)
+ expect(traffic).to have_grouped_filter_pill(
+ dimension: "referrer",
+ label: "Referrer: one.example, two.example, three.example",
+ )
+ expect(traffic).to have_no_apply_filters
+ expect(page).to have_current_path(
+ "/admin/dashboard/site-traffic-explorer?country=US&end_date=2026-05-12&range=custom&referrer=%5B%22one.example%22%2C%22two.example%22%2C%22three.example%22%5D&start_date=2026-05-01",
+ )
- expect(traffic).to have_filter_pill(dimension: "top_url", label: additional_path)
- expect(traffic).to have_no_expanded_table
+ page.refresh
+
+ expect(traffic).to have_grouped_filter_pill(
+ dimension: "referrer",
+ label: "Referrer: one.example, two.example, three.example",
+ )
+ expect(traffic).to have_filter_pill(dimension: "country", label: "United States")
+
+ traffic.clear_all
+
+ expect(traffic).to have_no_filter_pills
+ expect(page).to have_current_path(
+ "/admin/dashboard/site-traffic-explorer?end_date=2026-05-12&range=custom&start_date=2026-05-01",
+ )
end
it "warns an admin when the selected range has incomplete traffic data",
diff --git a/spec/system/page_objects/pages/admin_site_traffic_explorer.rb b/spec/system/page_objects/pages/admin_site_traffic_explorer.rb
index 73a61531b4f..ea248bb187c 100644
--- a/spec/system/page_objects/pages/admin_site_traffic_explorer.rb
+++ b/spec/system/page_objects/pages/admin_site_traffic_explorer.rb
@@ -5,7 +5,6 @@ module PageObjects
class AdminSiteTrafficExplorer < PageObjects::Pages::Base
PATH = "/admin/dashboard/site-traffic-explorer"
METRIC_KEYS = {
- "Pageviews" => "pageviews",
"Distinct sessions" => "distinct_sessions",
"Logged-in share" => "logged_in_share",
"Bounce rate" => "bounce_rate",
@@ -113,21 +112,48 @@ module PageObjects
def filter_row(card:, label:)
within("[data-test-site-traffic-card='#{card}']") do
- find("button[aria-label^='Filter by #{label},']").click
+ find("input[type='checkbox'][aria-label^='Filter by #{label},']").click
end
+ find("[data-test-site-traffic-apply-filters]").click
self
end
+ def filter_by_clicking_row(card:, label:)
+ within("[data-test-site-traffic-card='#{card}']") do
+ within("[data-test-site-traffic-row]", text: label) do
+ find(".site-traffic-explorer__row-checkbox").click
+ end
+ end
+ find("[data-test-site-traffic-apply-filters]").click
+ self
+ end
+
+ def select_filter_row(card:, label:)
+ within("[data-test-site-traffic-card='#{card}']") do
+ find("input[type='checkbox'][aria-label^='Filter by #{label},']").click
+ end
+ self
+ end
+
+ def has_filter_row_selected?(card:, label:)
+ within("[data-test-site-traffic-card='#{card}']") do
+ has_css?("input[type='checkbox'][aria-label^='Filter by #{label},']:checked")
+ end
+ end
+
+ def has_filter_row_unselected?(card:, label:)
+ within("[data-test-site-traffic-card='#{card}']") do
+ has_css?("input[type='checkbox'][aria-label^='Filter by #{label},']:not(:checked)")
+ end
+ end
+
def has_filter_pill?(dimension:, label:)
selector = "[data-test-site-traffic-filter-pill='#{dimension}']"
- remove_label =
- if dimension == "traffic_type"
- "Remove #{label} traffic filter"
- else
- "Remove #{FILTER_LABELS.fetch(dimension)} filter"
- end
+ remove_label = "Remove #{FILTER_LABELS.fetch(dimension)} filter"
+ expected_text = "#{FILTER_LABELS.fetch(dimension)}: #{label}".gsub(/\s+/, "")
- has_css?(selector, text: "#{FILTER_LABELS.fetch(dimension)} is #{label}", count: 1) &&
+ has_css?(selector, count: 1) &&
+ find(selector).text.gsub(/\s+/, "").include?(expected_text) &&
has_css?("#{selector} button[aria-label='#{remove_label}']")
end
@@ -135,14 +161,76 @@ module PageObjects
has_no_css?("[data-test-site-traffic-filter-pill]")
end
+ def has_grouped_filter_pill?(dimension:, label:)
+ selector = "[data-test-site-traffic-filter-pill='#{dimension}'] .fk-d-menu__trigger"
+
+ has_css?(selector, count: 1) &&
+ find(selector).text.gsub(/\s+/, "").include?(label.gsub(/\s+/, ""))
+ end
+
+ def expand_filter_pill(dimension)
+ within("[data-test-site-traffic-filter-pill='#{dimension}']") do
+ find(".fk-d-menu__trigger").click
+ end
+ self
+ end
+
+ def has_filter_dropdown?(values:)
+ row_selector = "[data-test-site-traffic-filter-dropdown-value]"
+ value_selector = "#{row_selector} .d-button-label"
+
+ has_css?(row_selector, count: values.length) &&
+ values.all? { |value| has_css?(value_selector, exact_text: value, count: 1) }
+ end
+
+ def has_no_filter_dropdown?
+ has_no_css?("[data-test-site-traffic-filter-dropdown]")
+ end
+
+ def remove_filter_value(value)
+ within("[data-test-site-traffic-filter-dropdown]") { find_button("Remove #{value}").click }
+ self
+ end
+
+ def has_apply_filters?(count:)
+ selector = "[data-test-site-traffic-apply-filters]"
+
+ has_css?(selector, count: 1) &&
+ has_css?(
+ "#{selector} .site-traffic-explorer__filter-apply-pending-count",
+ exact_text: count.to_s,
+ count: 1,
+ )
+ end
+
+ def has_no_apply_filters?
+ has_no_button?("Apply", exact: false)
+ end
+
+ def apply_filters
+ find("[data-test-site-traffic-apply-filters]").click
+ self
+ end
+
+ def clear_all
+ find_button("Clear all", exact: true).click
+ self
+ end
+
def remove_filter(name, label: nil)
- remove_label =
- if name == "traffic_type"
- "Remove #{label} traffic filter"
- else
- "Remove #{FILTER_LABELS.fetch(name)} filter"
+ remove_label = "Remove #{FILTER_LABELS.fetch(name)} filter"
+ selector = "[data-test-site-traffic-filter-pill='#{name}']"
+ if label && has_css?("#{selector} .fk-d-menu__trigger", wait: 0)
+ within(selector) { find(".fk-d-menu__trigger").click }
+ within("[data-test-site-traffic-filter-dropdown]") do
+ find_button("Remove #{label}").click
end
- find("button[aria-label='#{remove_label}']").click
+ else
+ find("button[aria-label='#{remove_label}']").click
+ end
+ if has_css?("[data-test-site-traffic-apply-filters]", wait: 0)
+ find("[data-test-site-traffic-apply-filters]").click
+ end
self
end
@@ -151,11 +239,9 @@ module PageObjects
self
end
- def has_expanded_table?(title:, column:)
+ def has_expanded_breakdown?(title:)
selector = ".site-traffic-breakdown-modal[role='dialog']"
- has_css?(selector, text: title) &&
- has_css?("#{selector} .d-table__header-cell", exact_text: column) &&
- has_css?("#{selector} .d-table__body .d-table__row")
+ has_css?(selector, text: title) && has_css?("#{selector} [data-test-site-traffic-row]")
end
def has_expanded_url_link?(label:)
@@ -163,14 +249,23 @@ module PageObjects
has_css?("#{selector} a[href='#{label}']", exact_text: label)
end
- def filter_expanded_row(label:)
+ def select_expanded_filter_row(label:)
+ within(".site-traffic-breakdown-modal[role='dialog']") do
+ within("[data-test-site-traffic-row]", text: label) do
+ find("input[type='checkbox'][aria-label^='Filter by #{label},']").click
+ end
+ end
+ self
+ end
+
+ def apply_expanded_filters
within(".site-traffic-breakdown-modal[role='dialog']") do
- within("tr", text: label) { find("button[aria-label^='Filter by #{label},']").click }
+ find_button("Apply", exact: true).click
end
self
end
- def has_no_expanded_table?
+ def has_no_expanded_breakdown?
has_no_css?(".site-traffic-breakdown-modal[role='dialog']")
end