Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Improve top bar and main graph stats UI (#6245)
Sanne de Vries17ce41341d91
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ff06539c24..9db870448e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@ All notable changes to this project will be documented in this file.- Keybind hints are hidden on smaller screens- Site index is sortable alphanumerically and by traffic- "Top referrers" and "Search terms" breakdowns are rendered side by side with other "Sources" tabs instead of replacing them+- Improved top bar and top stats UI/styling+- Moved graph interval picker, export button, imported data toggle and notices out of the graph and into a new options menu in the top bar### Fixed@@ -30,6 +32,8 @@ All notable changes to this project will be documented in this file.- Fixed issue with all non-interactive events being counted as interactive- Fixed countries map countries staying highlighted on Chrome- Fixed comparison tooltip in the top pages report missing date labels+- Fixed top bar not scrolling horizontally on mobile+- Fixed incline/decline percentages not showing in top stats in comparison mode## v3.2.0 - 2026-01-16diff --git a/assets/js/dashboard/components/combobox.js b/assets/js/dashboard/components/combobox.jsindex 17670f2180..0d8d3229a6 100644--- a/assets/js/dashboard/components/combobox.js+++ b/assets/js/dashboard/components/combobox.js@@ -5,6 +5,7 @@ import React, {useEffect,useRef} from 'react'+import { Spinner } from './icons'import { Transition } from '@headlessui/react'import { ChevronDownIcon } from '@heroicons/react/20/solid'import classNames from 'classnames'@@ -352,7 +353,9 @@ export default function PlausibleCombobox({{!singleOption && renderMultiOptionContent()}<div className="cursor-pointer absolute inset-y-0 right-0 flex items-center pr-2">{!loading && <ChevronDownIcon className="h-4 w-4 text-gray-500" />}- {loading && <Spinner />}+ {loading && (+ <Spinner className="animate-spin size-4 text-indigo-500" />+ )}</div></div>{isOpen && (@@ -374,28 +377,3 @@ export default function PlausibleCombobox({</div>)}--function Spinner() {- return (- <svg- className="animate-spin h-4 w-4 text-indigo-500"- xmlns="http://www.w3.org/2000/svg"- fill="none"- viewBox="0 0 24 24"- >- <circle- className="opacity-25"- cx="12"- cy="12"- r="10"- stroke="currentColor"- strokeWidth="4"- ></circle>- <path- className="opacity-75"- fill="currentColor"- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"- ></path>- </svg>- )-}diff --git a/assets/js/dashboard/components/notice.js b/assets/js/dashboard/components/feature-setup-notice.tsxsimilarity index 86%rename from assets/js/dashboard/components/notice.jsrename to assets/js/dashboard/components/feature-setup-notice.tsxindex df5b007d36..570b04a808 100644--- a/assets/js/dashboard/components/notice.js+++ b/assets/js/dashboard/components/feature-setup-notice.tsx@@ -9,6 +9,12 @@ export function FeatureSetupNotice({info,callToAction,onHideAction+}: {+ feature: keyof typeof MODES+ title: React.ReactNode+ info: React.ReactNode+ callToAction: { link: string; action: string }+ onHideAction: () => void}) {const site = useSiteContext()const sectionTitle = MODES[feature].title@@ -72,14 +78,12 @@ export function FeatureSetupNotice({return (<div className="size-full flex items-center justify-center"><div className="py-3 max-w-2xl">- <div className="text-center text-pretty mt-2 text-gray-800 dark:text-gray-200 font-medium text-pretty">+ <div className="text-center mt-2 text-gray-800 dark:text-gray-200 font-medium text-pretty">{title}</div>-- <div className="text-center text-pretty mt-4 font-small text-sm text-gray-500 dark:text-gray-200 text-pretty">+ <div className="text-center mt-4 font-small text-sm text-gray-500 dark:text-gray-200 text-pretty">{info}</div>-<div className="text-xs sm:text-sm flex my-6 justify-center">{renderHideButton()}{renderCallToAction()}diff --git a/assets/js/dashboard/components/icons.tsx b/assets/js/dashboard/components/icons.tsxnew file mode 100644index 0000000000..f70d27af69--- /dev/null+++ b/assets/js/dashboard/components/icons.tsx@@ -0,0 +1,65 @@+import React from 'react'++export const GlobeIcon = ({ className }: { className?: string }) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ fill="none"+ viewBox="0 0 24 24"+ className={className}+ >+ <path+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ d="M22 12H2M12 22c5.714-5.442 5.714-14.558 0-20M12 22C6.286 16.558 6.286 7.442 12 2"+ />+ <path+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10Z"+ />+ </svg>+)++export const FilterIcon = ({ className }: { className?: string }) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ fill="none"+ viewBox="0 0 24 24"+ className={className}+ >+ <path+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="2"+ d="M6 12h12M2 5h20M10 19h4"+ />+ </svg>+)++export const Spinner = ({ className }: { className?: string }) => (+ <svg+ className={className}+ xmlns="http://www.w3.org/2000/svg"+ fill="none"+ viewBox="0 0 24 24"+ >+ <circle+ className="opacity-25"+ cx="12"+ cy="12"+ r="10"+ stroke="currentColor"+ strokeWidth="4"+ />+ <path+ className="opacity-75"+ fill="currentColor"+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"+ />+ </svg>+)diff --git a/assets/js/dashboard/components/notice.tsx b/assets/js/dashboard/components/notice.tsxnew file mode 100644index 0000000000..cf4c221d7c--- /dev/null+++ b/assets/js/dashboard/components/notice.tsx@@ -0,0 +1,26 @@+import React from 'react'+import classNames from 'classnames'++export type NoticeProps = {+ title: string+ description?: string+ className?: string+}++export const Notice = ({ title, description, className }: NoticeProps) => (+ <div+ className={classNames(+ 'flex flex-col gap-y-0.5 rounded-md bg-yellow-100/60 dark:bg-yellow-700/30 px-3 py-2.5',+ className+ )}+ >+ <p className="text-sm font-semibold text-gray-900 dark:text-gray-100">+ {title}+ </p>+ {description && (+ <p className="text-sm text-gray-600 dark:text-gray-200/60">+ {description}+ </p>+ )}+ </div>+)diff --git a/assets/js/dashboard/components/popover.tsx b/assets/js/dashboard/components/popover.tsxindex 66ca3fc91c..ef0bfedde3 100644--- a/assets/js/dashboard/components/popover.tsx+++ b/assets/js/dashboard/components/popover.tsx@@ -33,12 +33,12 @@ const panel = {const toggleButton = {classNames: {rounded:- 'flex items-center rounded text-sm leading-tight h-9 transition-all duration-150',+ 'flex items-center rounded-md text-sm leading-tight h-8 transition-all duration-150',shadow:'bg-white dark:bg-gray-750 shadow-sm text-gray-800 dark:text-gray-200 dark:hover:bg-gray-700',ghost:- 'text-gray-700 dark:text-gray-100 hover:bg-gray-200 dark:hover:bg-gray-900',- truncatedText: 'truncate block font-medium',+ 'gap-x-1.5 px-2.5 font-medium text-gray-700 dark:text-gray-100 hover:bg-gray-150/80 dark:hover:bg-gray-800 aria-expanded:bg-gray-150/80 dark:aria-expanded:bg-gray-800',+ truncatedText: 'truncate block',linkLike:'text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors duration-150'}diff --git a/assets/js/dashboard/components/segmented-control.tsx b/assets/js/dashboard/components/segmented-control.tsxnew file mode 100644index 0000000000..99dca5756a--- /dev/null+++ b/assets/js/dashboard/components/segmented-control.tsx@@ -0,0 +1,53 @@+import React from 'react'+import classNames from 'classnames'++export type SegmentedControlOption<T extends string> = {+ value: T+ label: string+}++export function SegmentedControl<T extends string>({+ options,+ selected,+ onSelect,+ ariaLabel,+ getTestId+}: {+ options: SegmentedControlOption<T>[]+ selected: T+ onSelect: (value: T) => void+ ariaLabel: string+ getTestId?: (value: T, isSelected: boolean) => string | undefined+}) {+ return (+ <div+ role="group"+ aria-label={ariaLabel}+ className="inline-flex items-stretch rounded-lg border border-gray-300 p-0.5 dark:border-gray-600"+ >+ {options.map(({ value, label }) => {+ const isSelected = value === selected+ return (+ <button+ key={value}+ type="button"+ title={label}+ aria-pressed={isSelected}+ aria-label={label}+ onClick={() => onSelect(value)}+ data-testid={getTestId?.(value, isSelected)}+ data-selected={isSelected}+ className={classNames(+ 'flex-1 whitespace-nowrap rounded-md py-1 px-1.5 text-xs font-medium transition-colors',+ isSelected+ ? 'bg-gray-150 text-gray-900 dark:bg-gray-600/80 dark:text-gray-100'+ : 'text-gray-500 dark:text-gray-300'+ )}+ >+ {label}+ </button>+ )+ })}+ </div>+ )+}diff --git a/assets/js/dashboard/components/toggle.tsx b/assets/js/dashboard/components/toggle.tsxnew file mode 100644index 0000000000..3da13cb45a--- /dev/null+++ b/assets/js/dashboard/components/toggle.tsx@@ -0,0 +1,20 @@+import React from 'react'+import classNames from 'classnames'++export function Toggle({ on, disabled }: { on: boolean; disabled?: boolean }) {+ return (+ <div+ className={classNames(+ 'relative inline-flex h-4 w-7 shrink-0 rounded-full transition-colors duration-200',+ on && !disabled ? 'bg-indigo-600' : 'bg-gray-200 dark:bg-gray-600'+ )}+ >+ <span+ className={classNames(+ 'inline-block mt-0.5 h-3 w-3 rounded-full bg-white shadow-sm transition-transform duration-200',+ on ? 'translate-x-[14px]' : 'translate-x-0.5'+ )}+ />+ </div>+ )+}diff --git a/assets/js/dashboard/index.tsx b/assets/js/dashboard/index.tsxindex ed22e0c22a..a0e514c4e5 100644--- a/assets/js/dashboard/index.tsx+++ b/assets/js/dashboard/index.tsx@@ -8,6 +8,8 @@ import { TopBar } from './nav-menu/top-bar'import Behaviours from './stats/behaviours'import { useDashboardStateContext } from './dashboard-state-context'import { isRealTimeDashboard } from './util/filters'+import { GraphIntervalProvider } from './stats/graph/graph-interval-context'+import { ImportsIncludedProvider } from './stats/graph/imports-included-context'function DashboardStats({importedDataInView,@@ -40,17 +42,21 @@ function Dashboard() {const [importedDataInView, setImportedDataInView] = useState(false)return (- <div className="mb-16 grid grid-cols-1 md:grid-cols-2 gap-5">- <TopBar showCurrentVisitors={!isRealTimeDashboard} />- <DashboardStats- importedDataInView={- isRealTimeDashboard ? undefined : importedDataInView- }- updateImportedDataInView={- isRealTimeDashboard ? undefined : setImportedDataInView- }- />- </div>+ <GraphIntervalProvider>+ <ImportsIncludedProvider>+ <div className="mb-16 grid grid-cols-1 md:grid-cols-2 gap-5">+ <TopBar showCurrentVisitors={!isRealTimeDashboard} />+ <DashboardStats+ importedDataInView={+ isRealTimeDashboard ? undefined : importedDataInView+ }+ updateImportedDataInView={+ isRealTimeDashboard ? undefined : setImportedDataInView+ }+ />+ </div>+ </ImportsIncludedProvider>+ </GraphIntervalProvider>)}diff --git a/assets/js/dashboard/nav-menu/dashboard-options-menu.tsx b/assets/js/dashboard/nav-menu/dashboard-options-menu.tsxnew file mode 100644index 0000000000..88567690af--- /dev/null+++ b/assets/js/dashboard/nav-menu/dashboard-options-menu.tsx@@ -0,0 +1,203 @@+import React, { useRef, useState } from 'react'+import { Popover, Transition } from '@headlessui/react'+import {+ EllipsisVerticalIcon,+ ArrowDownTrayIcon+} from '@heroicons/react/24/outline'+import { Toggle } from '../components/toggle'+import { Spinner } from '../components/icons'+import classNames from 'classnames'+import { popover, BlurMenuButtonOnEscape } from '../components/popover'+import { useGraphIntervalContext } from '../stats/graph/graph-interval-context'+import { useImportsIncludedContext } from '../stats/graph/imports-included-context'+import { useDashboardStateContext } from '../dashboard-state-context'+import { DashboardPeriod } from '../dashboard-time-periods'+import { IntervalPicker } from '../stats/graph/interval-picker'+import { AppNavigationLink } from '../navigation/use-app-navigate'+import { useSiteContext } from '../site-context'+import * as api from '../api'+import { Notice } from '../components/notice'+import { isModifierPressed, isTyping, Keybind } from '../keybinding'+import { useMatch } from 'react-router-dom'+import { rootRoute } from '../router'++function ExportItem({ selectedInterval }: { selectedInterval: string }) {+ const site = useSiteContext()+ const { dashboardState } = useDashboardStateContext()+ const [exporting, setExporting] = useState(false)++ function pollExportReady() {+ if (document.cookie.includes('exporting')) {+ setTimeout(pollExportReady, 1000)+ } else {+ setExporting(false)+ }+ }++ function startExport() {+ setExporting(true)+ document.cookie = 'exporting='+ pollExportReady()+ }++ const params = api.dashboardStateToSearchParams(dashboardState, [+ { interval: selectedInterval, comparison: undefined }+ ])+ const endpoint = `/${encodeURIComponent(site.domain)}/export?${params}`++ return (+ <a+ href={endpoint}+ download+ onClick={startExport}+ className={classNames(+ popover.items.classNames.navigationLink,+ popover.items.classNames.hoverLink+ )}+ >+ <span className="text-sm">Export stats</span>+ {exporting ? (+ <Spinner className="animate-spin size-4 text-indigo-500" />+ ) : (+ <ArrowDownTrayIcon className="size-4 stroke-2" />+ )}+ </a>+ )+}++function ImportedSwitchItem({ disabled }: { disabled: boolean }) {+ const { dashboardState } = useDashboardStateContext()+ const importsSwitchedOn = dashboardState.with_imported++ return (+ <AppNavigationLink+ data-testid="import-switch"+ search={+ disabled+ ? (search) => search+ : (search) => ({ ...search, with_imported: !importsSwitchedOn })+ }+ className={classNames(+ popover.items.classNames.navigationLink,+ disabled+ ? 'cursor-not-allowed opacity-50'+ : popover.items.classNames.hoverLink+ )}+ >+ Include imported data+ <Toggle on={importsSwitchedOn} disabled={disabled} />+ </AppNavigationLink>+ )+}++function DashboardOptionsMenuItems() {+ const { selectedInterval, onIntervalClick, availableIntervals } =+ useGraphIntervalContext()+ const imports = useImportsIncludedContext()+ const buttonRef = useRef<HTMLButtonElement>(null)++ const showIntervalSection = availableIntervals.length > 1++ const dashboardRouteMatch = useMatch(rootRoute.path)+ const n = availableIntervals.length++ return (+ <>+ {showIntervalSection && !!dashboardRouteMatch && (+ <Keybind+ targetRef="document"+ type="keydown"+ keyboardKey="i"+ handler={() => {+ const idx = availableIntervals.indexOf(selectedInterval)+ const i = idx >= 0 ? idx : 0+ onIntervalClick(availableIntervals[(i + 1) % n])+ }}+ shouldIgnoreWhen={[isModifierPressed, isTyping]}+ />+ )}+ <BlurMenuButtonOnEscape targetRef={buttonRef} />+ <Popover.Button+ ref={buttonRef}+ data-testid="dashboard-options-menu"+ className={classNames(+ popover.toggleButton.classNames.rounded,+ popover.toggleButton.classNames.ghost,+ 'justify-center'+ )}+ >+ <EllipsisVerticalIcon className="size-4" />+ </Popover.Button>+ <Transition+ as="div"+ {...popover.transition.props}+ className={classNames(popover.transition.classNames.right, 'mt-2')}+ >+ <Popover.Panel+ className={classNames(+ popover.panel.classNames.roundedSheet,+ 'min-w-72'+ )}+ >+ {showIntervalSection && (+ <IntervalPicker+ selectedInterval={selectedInterval}+ onIntervalClick={onIntervalClick}+ options={availableIntervals}+ />+ )}+ <ExportItem selectedInterval={selectedInterval} />+ {imports.status === 'visible' && (+ <>+ <ImportedSwitchItem disabled={imports.disabled} />+ {imports.disabled ? (+ <Notice+ className="m-1"+ title="Imported data unavailable with current filters."+ />+ ) : (+ imports.intervalUnsupportedNotice && (+ <Notice+ className="m-1"+ {...imports.intervalUnsupportedNotice}+ />+ )+ )}+ </>+ )}+ </Popover.Panel>+ </Transition>+ </>+ )+}++export function DashboardOptionsMenu() {+ const imports = useImportsIncludedContext()+ const { dashboardState } = useDashboardStateContext()+ const isRealtime = dashboardState.period === DashboardPeriod.realtime++ if (isRealtime) {+ return null+ }++ if (imports.status === 'loading') {+ return (+ <button+ disabled+ className={classNames(+ popover.toggleButton.classNames.rounded,+ popover.toggleButton.classNames.ghost,+ 'justify-center'+ )}+ >+ <EllipsisVerticalIcon className="size-4" />+ </button>+ )+ }++ return (+ <Popover className="md:relative">+ {() => <DashboardOptionsMenuItems />}+ </Popover>+ )+}diff --git a/assets/js/dashboard/nav-menu/filter-menu.tsx b/assets/js/dashboard/nav-menu/filter-menu.tsxindex ba1c6178a7..fa90e8425d 100644--- a/assets/js/dashboard/nav-menu/filter-menu.tsx+++ b/assets/js/dashboard/nav-menu/filter-menu.tsx@@ -5,7 +5,7 @@ import {} from '../util/filters'import { PlausibleSite, useSiteContext } from '../site-context'import { filterRoute } from '../router'-import { MagnifyingGlassIcon } from '@heroicons/react/24/outline'+import { FilterIcon } from '../components/icons'import { Popover, Transition } from '@headlessui/react'import { popover, BlurMenuButtonOnEscape } from '../components/popover'import classNames from 'classnames'@@ -59,11 +59,10 @@ const FilterMenuItems = ({ closeDropdown }: { closeDropdown: () => void }) => {ref={buttonRef}className={classNames(popover.toggleButton.classNames.rounded,- popover.toggleButton.classNames.ghost,- 'justify-center gap-1 px-3'+ popover.toggleButton.classNames.ghost)}>- <MagnifyingGlassIcon className="block h-4 w-4" />+ <FilterIcon className="block size-3.5" /><span className={popover.toggleButton.classNames.truncatedText}>Filter</span>diff --git a/assets/js/dashboard/nav-menu/filter-pill.tsx b/assets/js/dashboard/nav-menu/filter-pill.tsxindex 916441da6d..c202e22536 100644--- a/assets/js/dashboard/nav-menu/filter-pill.tsx+++ b/assets/js/dashboard/nav-menu/filter-pill.tsx@@ -32,12 +32,12 @@ export function FilterPill({interactive,actions}: FilterPillProps) {- const contentClassName = 'flex w-full h-full items-center py-2 pl-3 last:pr-3'+ const contentClassName = 'flex w-full h-full items-center pl-2.5 last:pr-2.5'return (<divclassName={classNames(- 'flex h-9 shadow rounded bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 text-sm items-center',+ 'flex h-8 shadow rounded-md bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 text-sm items-center',className)}>@@ -53,7 +53,7 @@ export function FilterPill({{!!interactive.onRemoveClick && (<buttontitle={`Remove filter: ${plainText}`}- className="flex items-center h-full px-2 mr-1 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500 "+ className="flex items-center h-full pl-1.5 pr-2.5 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500 "onClick={interactive.onRemoveClick}><XMarkIcon className="w-4 h-4" />diff --git a/assets/js/dashboard/nav-menu/filter-pills-list.tsx b/assets/js/dashboard/nav-menu/filter-pills-list.tsxindex 9b04d6cb35..43dc8a5cb2 100644--- a/assets/js/dashboard/nav-menu/filter-pills-list.tsx+++ b/assets/js/dashboard/nav-menu/filter-pills-list.tsx@@ -13,7 +13,7 @@ import { filterRoute } from '../router'import { canRemoveFilter } from '../filtering/segments'import { useSegmentsContext } from '../filtering/segments-context'-export const PILL_X_GAP_PX = 16+export const PILL_X_GAP_PX = 10export const PILL_Y_GAP_PX = 8type SliceStartEnd = {diff --git a/assets/js/dashboard/nav-menu/filters-bar.tsx b/assets/js/dashboard/nav-menu/filters-bar.tsxindex 8b04abd212..79bf8c5f0e 100644--- a/assets/js/dashboard/nav-menu/filters-bar.tsx+++ b/assets/js/dashboard/nav-menu/filters-bar.tsx@@ -18,9 +18,7 @@ import { useUserContext } from '../user-context'// `..[ filter (x) ]..[ filter (x) ]..[ three dot menu ]..`// where `..` represents an ideally equal length.// The following calculations guarantee that.-const BUFFER_RIGHT_PX = 16 - PILL_X_GAP_PX-const BUFFER_LEFT_PX = 16-const SEE_MORE_WIDTH_PX = 36+const SEE_MORE_WIDTH_PX = 32const SEE_MORE_RIGHT_MARGIN_PX = PILL_X_GAP_PXconst SEE_MORE_LEFT_MARGIN_PX = 0@@ -162,9 +160,7 @@ export const FiltersBar = ({ accessors }: FiltersBarProps) => {topBar && leftSection && rightSection? getElementWidthOrNull(topBar)! -getElementWidthOrNull(leftSection)! -- getElementWidthOrNull(rightSection)! -- BUFFER_LEFT_PX -- BUFFER_RIGHT_PX+ getElementWidthOrNull(rightSection)!: null,seeMoreWidth:SEE_MORE_LEFT_MARGIN_PX +@@ -190,7 +186,6 @@ export const FiltersBar = ({ accessors }: FiltersBarProps) => {return (<div- style={{ paddingRight: BUFFER_RIGHT_PX, paddingLeft: BUFFER_LEFT_PX }}className={classNames('flex w-full items-center',visibility === null && 'invisible' // hide until we've calculated the positions@@ -267,11 +262,11 @@ const SeeMoreMenu = ({marginRight: SEE_MORE_RIGHT_MARGIN_PX}}>- <EllipsisHorizontalIcon className="block h-5 w-5" />+ <EllipsisHorizontalIcon className="block size-4" />{showMoreFilters && (<divaria-hidden="true"- className="absolute flex justify-end left-0 right-0 bottom-0 translate-y-1/4 pr-[3px]"+ className="absolute flex justify-end left-0 -right-1 bottom-0 translate-y-1/4"><div className="text-[10px] leading-[10px] min-w-[10px] font-medium shadow-sm px-[3px] py-[1px] flex items-center rounded-xs bg-gray-100 dark:bg-gray-850">+{filtersInMenuCount}diff --git a/assets/js/dashboard/nav-menu/query-periods/comparison-period-menu.tsx b/assets/js/dashboard/nav-menu/query-periods/comparison-period-menu.tsxindex 34f17cc47c..ad723cec9a 100644--- a/assets/js/dashboard/nav-menu/query-periods/comparison-period-menu.tsx+++ b/assets/js/dashboard/nav-menu/query-periods/comparison-period-menu.tsx@@ -19,8 +19,7 @@ import {import { Popover, Transition } from '@headlessui/react'import { popover, BlurMenuButtonOnEscape } from '../../components/popover'import {- datemenuButtonClassName,- DateMenuChevron,+ DateMenuCalendarIcon,PopoverMenuProps,linkClassName,CalendarPanel,@@ -123,11 +122,18 @@ export const ComparisonPeriodMenu = ({return (<><BlurMenuButtonOnEscape targetRef={buttonRef} />- <Popover.Button className={datemenuButtonClassName} ref={buttonRef}>+ <Popover.Button+ className={classNames(+ popover.toggleButton.classNames.rounded,+ popover.toggleButton.classNames.ghost,+ 'bg-gray-150/80 dark:bg-gray-800'+ )}+ ref={buttonRef}+ >+ <DateMenuCalendarIcon /><span className={popover.toggleButton.classNames.truncatedText}>{getCurrentComparisonPeriodDisplayName({ site, dashboardState })}</span>- <DateMenuChevron /></Popover.Button><ComparisonPeriodMenuItemscloseDropdown={closeDropdown}diff --git a/assets/js/dashboard/nav-menu/query-periods/dashboard-period-menu.tsx b/assets/js/dashboard/nav-menu/query-periods/dashboard-period-menu.tsxindex e5fd6afcd2..bc26d2581c 100644--- a/assets/js/dashboard/nav-menu/query-periods/dashboard-period-menu.tsx+++ b/assets/js/dashboard/nav-menu/query-periods/dashboard-period-menu.tsx@@ -19,15 +19,15 @@ import {DashboardPeriod,getCurrentPeriodDisplayName,getSearchToApplyCustomDates,- isComparisonForbidden+ isComparisonForbidden,+ isComparisonEnabled} from '../../dashboard-time-periods'import { useMatch } from 'react-router-dom'import { rootRoute } from '../../router'import { Popover, Transition } from '@headlessui/react'import { popover, BlurMenuButtonOnEscape } from '../../components/popover'import {- datemenuButtonClassName,- DateMenuChevron,+ DateMenuCalendarIcon,PopoverMenuProps,linkClassName,CalendarPanel,@@ -36,6 +36,7 @@ import {import { DateRangeCalendar } from './date-range-calendar'import { formatISO, nowForSite } from '../../util/date'import { MenuSeparator } from '../nav-menu-components'+import { MovePeriodArrows, periodsWithArrows } from './move-period-arrows'function DashboardPeriodMenuKeybinds({closeDropdown,@@ -85,6 +86,7 @@ export const DashboardPeriodMenu = ({}: PopoverMenuProps) => {const site = useSiteContext()const { dashboardState } = useDashboardStateContext()+ const isComparing = isComparisonEnabled(dashboardState.comparison)const buttonRef = useRef<HTMLButtonElement>(null)const toggleCalendar = () => {if (typeof calendarButtonRef.current?.click === 'function') {@@ -95,15 +97,34 @@ export const DashboardPeriodMenu = ({return (<><BlurMenuButtonOnEscape targetRef={buttonRef} />- <Popover.Button ref={buttonRef} className={datemenuButtonClassName}>- <span- data-testid="current-query-period"- className={popover.toggleButton.classNames.truncatedText}+ <div+ className={classNames(+ 'flex rounded-md h-8 transition-all duration-150',+ 'hover:bg-gray-150/80 dark:hover:bg-gray-800',+ 'has-[[aria-expanded=true]]:bg-gray-150/80 dark:has-[[aria-expanded=true]]:bg-gray-800',+ 'has-[button:focus-visible]:ring-2 has-[button:focus-visible]:ring-indigo-500 has-[button:focus-visible]:ring-offset-2 dark:has-[button:focus-visible]:ring-offset-gray-900',+ isComparing && 'bg-gray-150/80 dark:bg-gray-800'+ )}+ >+ <Popover.Button+ ref={buttonRef}+ className={classNames(+ 'flex items-center gap-x-1.5 pl-2.5 text-sm font-medium text-gray-700 dark:text-gray-100 leading-tight h-full rounded-md focus-visible:ring-0 focus-visible:ring-offset-0',+ periodsWithArrows.includes(dashboardState.period)+ ? 'pr-1.5'+ : 'pr-2.5'+ )}>- {getCurrentPeriodDisplayName({ dashboardState, site })}- </span>- <DateMenuChevron />- </Popover.Button>+ <DateMenuCalendarIcon />+ <span+ data-testid="current-query-period"+ className={popover.toggleButton.classNames.truncatedText}+ >+ {getCurrentPeriodDisplayName({ dashboardState, site })}+ </span>+ </Popover.Button>+ <MovePeriodArrows />+ </div><DashboardPeriodMenuInnertoggleCalendar={toggleCalendar}closeDropdown={closeDropdown}diff --git a/assets/js/dashboard/nav-menu/query-periods/dashboard-period-picker.tsx b/assets/js/dashboard/nav-menu/query-periods/dashboard-period-picker.tsxindex aceb3d3f23..52f172d36d 100644--- a/assets/js/dashboard/nav-menu/query-periods/dashboard-period-picker.tsx+++ b/assets/js/dashboard/nav-menu/query-periods/dashboard-period-picker.tsx@@ -2,7 +2,6 @@ import React, { useRef } from 'react'import classNames from 'classnames'import { useDashboardStateContext } from '../../dashboard-state-context'import { isComparisonEnabled } from '../../dashboard-time-periods'-import { MovePeriodArrows } from './move-period-arrows'import { MainCalendar, DashboardPeriodMenu } from './dashboard-period-menu'import {ComparisonCalendarMenu,@@ -21,8 +20,7 @@ export function DashboardPeriodPicker({ className }: { className?: string }) {data-testid="query-period-picker"className={classNames('flex shrink-0', className)}>- <MovePeriodArrows className={isComparing ? 'hidden md:flex' : ''} />- <Popover className="min-w-36 md:relative lg:w-48">+ <Popover className="md:relative">{({ close }) => (<DashboardPeriodMenucloseDropdown={close}@@ -30,7 +28,7 @@ export function DashboardPeriodPicker({ className }: { className?: string }) {/>)}</Popover>- <Popover className="w-0 h-9 md:relative">+ <Popover className="w-0 h-8 md:relative">{({ close }) => (<MainCalendarcalendarButtonRef={mainCalendarButtonRef}@@ -40,10 +38,10 @@ export function DashboardPeriodPicker({ className }: { className?: string }) {</Popover>{isComparing && (<>- <div className="my-auto px-1 text-sm font-medium text-gray-800 dark:text-gray-200">- <span className="px-1">vs.</span>+ <div className="my-auto px-2.5 text-sm font-medium text-gray-800 dark:text-gray-200">+ vs</div>- <Popover className="min-w-36 md:relative lg:w-48">+ <Popover className="md:relative">{({ close }) => (<ComparisonPeriodMenucloseDropdown={close}@@ -51,7 +49,7 @@ export function DashboardPeriodPicker({ className }: { className?: string }) {/>)}</Popover>- <Popover className="w-0 h-9 md:relative">+ <Popover className="w-0 h-8 md:relative">{({ close }) => (<ComparisonCalendarMenucalendarButtonRef={compareCalendarButtonRef}diff --git a/assets/js/dashboard/nav-menu/query-periods/move-period-arrows.tsx b/assets/js/dashboard/nav-menu/query-periods/move-period-arrows.tsxindex 71e93a311f..f5aa35ce05 100644--- a/assets/js/dashboard/nav-menu/query-periods/move-period-arrows.tsx+++ b/assets/js/dashboard/nav-menu/query-periods/move-period-arrows.tsx@@ -53,9 +53,9 @@ function ArrowIcon({<svgdata-testid={testId}className={classNames(- 'feather size-4',+ 'size-3.5',disabled- ? 'text-gray-400 dark:text-gray-600'+ ? 'text-gray-400 dark:text-gray-500': 'text-gray-700 dark:text-gray-300')}xmlns="http://www.w3.org/2000/svg"@@ -72,12 +72,13 @@ function ArrowIcon({)}-export function MovePeriodArrows({ className }: { className?: string }) {- const periodsWithArrows = [- DashboardPeriod.year,- DashboardPeriod.month,- DashboardPeriod.day- ]+export const periodsWithArrows = [+ DashboardPeriod.year,+ DashboardPeriod.month,+ DashboardPeriod.day+]++export function MovePeriodArrows() {const { dashboardState } = useDashboardStateContext()const site = useSiteContext()const dashboardRouteMatch = useMatch(rootRoute.path)@@ -91,24 +92,18 @@ export function MovePeriodArrows({ className }: { className?: string }) {const canGoForward =getDateForShiftedPeriod({ site, dashboardState, direction: 1 }) !== null- const sharedClass =- 'flex items-center px-1 sm:px-2 dark:text-gray-100 transition-colors duration-150'- const enabledClass = 'hover:bg-gray-100 dark:hover:bg-gray-700'- const disabledClass = 'bg-gray-200 dark:bg-gray-850 cursor-not-allowed'+ const arrowClass = (enabled: boolean) =>+ classNames(+ 'flex items-center justify-center px-px h-full rounded-md',+ enabled+ ? 'text-gray-700 dark:text-gray-300'+ : 'text-gray-400 dark:text-gray-600 cursor-not-allowed'+ )return (- <div- className={classNames(- 'flex rounded shadow bg-white mr-2 sm:mr-4 cursor-pointer focus:z-10 dark:bg-gray-750',- className- )}- >+ <div className="flex pr-1"><AppNavigationLink- className={classNames(- sharedClass,- 'rounded-l border-gray-300 dark:border-gray-500 focus:z-10',- { [enabledClass]: canGoBack, [disabledClass]: !canGoBack }- )}+ className={arrowClass(canGoBack)}search={canGoBack? shiftDashboardPeriod({@@ -127,10 +122,7 @@ export function MovePeriodArrows({ className }: { className?: string }) {/></AppNavigationLink><AppNavigationLink- className={classNames(sharedClass, 'rounded-r', {- [enabledClass]: canGoForward,- [disabledClass]: !canGoForward- })}+ className={arrowClass(canGoForward)}search={canGoForward? shiftDashboardPeriod({diff --git a/assets/js/dashboard/nav-menu/query-periods/shared-menu-items.tsx b/assets/js/dashboard/nav-menu/query-periods/shared-menu-items.tsxindex aacf0d5c57..343aa55a8f 100644--- a/assets/js/dashboard/nav-menu/query-periods/shared-menu-items.tsx+++ b/assets/js/dashboard/nav-menu/query-periods/shared-menu-items.tsx@@ -1,7 +1,7 @@import React, { ReactNode, RefObject } from 'react'import classNames from 'classnames'import { popover } from '../../components/popover'-import { ChevronDownIcon } from '@heroicons/react/20/solid'+import { CalendarIcon } from '@heroicons/react/24/outline'import { Popover, Transition } from '@headlessui/react'export const linkClassName = classNames(@@ -10,17 +10,9 @@ export const linkClassName = classNames(popover.items.classNames.hoverLink)-export const datemenuButtonClassName = classNames(- popover.toggleButton.classNames.rounded,- popover.toggleButton.classNames.shadow,- 'justify-between px-2 w-full'-)--export const hiddenCalendarButtonClassName = 'flex h-9 w-0 outline-none'+export const hiddenCalendarButtonClassName = 'flex h-8 w-0 outline-none'-export const DateMenuChevron = () => (- <ChevronDownIcon className="hidden lg:inline-block h-4 w-4 md:h-5 md:w-5 ml-1 md:ml-2 text-gray-500" />-)+export const DateMenuCalendarIcon = () => <CalendarIcon className="size-4" />export interface PopoverMenuProps {closeDropdown: () => voiddiff --git a/assets/js/dashboard/nav-menu/top-bar.tsx b/assets/js/dashboard/nav-menu/top-bar.tsxindex d2df34830e..6229644100 100644--- a/assets/js/dashboard/nav-menu/top-bar.tsx+++ b/assets/js/dashboard/nav-menu/top-bar.tsx@@ -8,6 +8,7 @@ import { FilterMenu } from './filter-menu'import { FiltersBar } from './filters-bar'import { DashboardPeriodPicker } from './query-periods/dashboard-period-picker'import { SegmentMenu } from './segments/segment-menu'+import { DashboardOptionsMenu } from './dashboard-options-menu'interface TopBarProps {showCurrentVisitors: boolean@@ -30,7 +31,7 @@ function TopBarStickyWrapper({ children }: { children: ReactNode }) {<div id="stats-container-top" className="col-span-full" ref={ref} /><divclassName={classNames(- 'col-span-full relative top-0 py-2 sm:py-3 -my-3 sm:-my-4 z-10',+ 'col-span-full relative top-0 py-2 -my-3 sm:-my-4 z-10',!site.embedded &&!inView &&'sticky bg-gray-50 dark:bg-gray-950 before:absolute before:top-0 before:w-screen before:h-full before:bg-inherit before:shadow-[0_4px_2px_-2px_rgb(0_0_0/6%)] before:z-[-1] before:left-[calc(50%-50vw)]'@@ -46,14 +47,15 @@ function TopBarInner({ showCurrentVisitors }: TopBarProps) {const leftActionsRef = useRef<HTMLDivElement>(null)return (- <div className="flex items-center w-full">- <div className="flex items-center gap-x-5 shrink-0" ref={leftActionsRef}>+ <div className="flex min-w-0 flex-nowrap items-center gap-x-1 md:gap-x-2.5 overflow-x-auto md:overflow-visible w-full touch-pan-x md:touch-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden py-1 -my-1 md:py-0 md:my-0">+ <div+ className="flex shrink-0 items-center gap-x-1 md:gap-x-2.5"+ ref={leftActionsRef}+ ><SiteSwitcher />- {showCurrentVisitors && (- <CurrentVisitors tooltipBoundaryRef={leftActionsRef} />- )}+ {showCurrentVisitors && <CurrentVisitors />}</div>- <div className="flex w-full">+ <div className="flex flex-1"><FiltersBaraccessors={{topBar: (filtersBarElement) =>@@ -67,10 +69,11 @@ function TopBarInner({ showCurrentVisitors }: TopBarProps) {}}/></div>- <div className="flex gap-x-4 shrink-0">+ <div className="flex gap-x-1 md:gap-x-2.5 shrink-0"><FilterMenu /><SegmentMenu /><DashboardPeriodPicker />+ <DashboardOptionsMenu /></div></div>)diff --git a/assets/js/dashboard/site-switcher.tsx b/assets/js/dashboard/site-switcher.tsxindex 22a9d667cd..637dd5aa3d 100644--- a/assets/js/dashboard/site-switcher.tsx+++ b/assets/js/dashboard/site-switcher.tsx@@ -8,6 +8,7 @@ import { Cog8ToothIcon, ArrowLeftIcon } from '@heroicons/react/24/outline'import classNames from 'classnames'import { isModifierPressed, isTyping, Keybind, KeybindHint } from './keybinding'import { popover, BlurMenuButtonOnEscape } from './components/popover'+import { GlobeIcon } from './components/icons'import { useQuery } from '@tanstack/react-query'import { Role, useUserContext } from './user-context'import { PlausibleSite, useSiteContext } from './site-context'@@ -39,30 +40,6 @@ const Favicon = ({/>)-const GlobeIcon = ({ className }: { className?: string }) => (- <svg- xmlns="http://www.w3.org/2000/svg"- fill="none"- viewBox="0 0 24 24"- className={className}- >- <path- stroke="currentColor"- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth="1.5"- d="M22 12H2M12 22c5.714-5.442 5.714-14.558 0-20M12 22C6.286 16.558 6.286 7.442 12 2"- />- <path- stroke="currentColor"- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth="1.5"- d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10Z"- />- </svg>-)-const menuItemClassName = classNames(popover.items.classNames.navigationLink,popover.items.classNames.selectedOption,@@ -90,6 +67,26 @@ const getSwitchToSiteURL = (return `/${encodeURIComponent(site.domain)}`}+const SiteSwitcherStatic = () => {+ const currentSite = useSiteContext()++ return (+ <div+ data-testid="site-switcher-static"+ className={classNames(+ popover.toggleButton.classNames.rounded,+ 'gap-x-1.5 pl-0 pr-2.5 font-medium text-gray-700 dark:text-gray-100'+ )}+ title={currentSite.domain}+ >+ <Favicon domain={currentSite.domain} className="block size-4" />+ <span className="truncate hidden sm:block sm:mr-1 lg:mr-0 font-semibold">+ {currentSite.domain}+ </span>+ </div>+ )+}+export const SiteSwitcher = () => {const dashboardRouteMatch = useMatch(rootRoute.path)const { modal } = useRoutelessModalsContext()@@ -106,10 +103,11 @@ export const SiteSwitcher = () => {placeholderData: (previousData) => previousData})- const sitesInDropdown = user.loggedIn- ? sitesQuery.data?.data- : // show only current site in dropdown when viewing public / embedded dashboard- [{ domain: currentSite.domain }]+ if (!user.loggedIn) {+ return <SiteSwitcherStatic />+ }++ const sitesInDropdown = sitesQuery.data?.dataconst canSeeSiteSettings: boolean =user.loggedIn &&@@ -170,28 +168,28 @@ export const SiteSwitcher = () => {<Popover.Buttonref={buttonRef}className={classNames(- 'flex items-center rounded h-9 text-sm leading-5 font-semibold dark:text-gray-100',- 'hover:bg-gray-100 dark:hover:bg-gray-800'+ popover.toggleButton.classNames.rounded,+ popover.toggleButton.classNames.ghost,+ '!pl-1.5')}title={currentSite.domain}>{currentSite.isConsolidatedView ? (<GlobeIcon className="size-4 block mx-1 h-4 w-4 text-indigo-600 dark:text-white" />) : (- <Favicon- domain={currentSite.domain}- className="block h-4 w-4 mx-1"- />+ <Favicon domain={currentSite.domain} className="block size-4" />)}<spandata-testid="site-switcher-current-site"- className={'truncate hidden sm:block sm:mr-1 lg:mr-0'}+ className={+ 'truncate hidden sm:block sm:mr-1 lg:mr-0 font-semibold'+ }>{currentSite.isConsolidatedView? 'All sites': currentSite.domain}</span>- <ChevronDownIcon className="hidden lg:block size-4 ml-2 dark:text-gray-100" />+ <ChevronDownIcon className="hidden lg:block size-4" /></Popover.Button><Transitionas="div"diff --git a/assets/js/dashboard/stats/behaviours/index.js b/assets/js/dashboard/stats/behaviours/index.jsindex 9eefb1742e..85170b227d 100644--- a/assets/js/dashboard/stats/behaviours/index.js+++ b/assets/js/dashboard/stats/behaviours/index.js@@ -3,7 +3,7 @@ import * as storage from '../../util/storage'import ImportedQueryUnsupportedWarning from '../imported-query-unsupported-warning'import Properties from './props'import { FunnelExploration } from '../exploration'-import { FeatureSetupNotice } from '../../components/notice'+import { FeatureSetupNotice } from '../../components/feature-setup-notice'import {hasConversionGoalFilter,getGoalFilter,diff --git a/assets/js/dashboard/stats/current-visitors.js b/assets/js/dashboard/stats/current-visitors.jsindex 79e149dcfb..c2723068e1 100644--- a/assets/js/dashboard/stats/current-visitors.js+++ b/assets/js/dashboard/stats/current-visitors.js@@ -7,11 +7,9 @@ import { useDashboardStateContext } from '../dashboard-state-context'import { useSiteContext } from '../site-context'import { useLastLoadContext } from '../last-load-context'import classNames from 'classnames'+import { popover } from '../components/popover'-export default function CurrentVisitors({- className = '',- tooltipBoundaryRef-}) {+export default function CurrentVisitors({ className = '' }) {const { dashboardState } = useDashboardStateContext()const lastLoadTimestamp = useLastLoadContext()const site = useSiteContext()@@ -50,23 +48,24 @@ export default function CurrentVisitors({</p></div>}- boundary={tooltipBoundaryRef.current}><AppNavigationLinksearch={(prev) => ({ ...prev, period: 'realtime' })}className={classNames(- 'h-9 flex items-center text-xs md:text-sm font-medium text-gray-500 dark:text-gray-300',+ popover.toggleButton.classNames.rounded,+ popover.toggleButton.classNames.ghost,+ 'px-2',className)}><svg- className="inline-block w-2 mr-1 text-green-500 fill-current"+ className="inline-block w-2 text-green-500 fill-current"viewBox="0 0 16 16"xmlns="http://www.w3.org/2000/svg"><circle cx="8" cy="8" r="8" /></svg>- <div className="inline-block">+ <div className="inline-block text-gray-500 dark:text-gray-400">{currentVisitors}<span className="hidden lg:inline">{' '}diff --git a/assets/js/dashboard/stats/graph/fetch-top-stats.test.ts b/assets/js/dashboard/stats/graph/fetch-top-stats.test.tsindex 05d1d86386..00cd269f07 100644--- a/assets/js/dashboard/stats/graph/fetch-top-stats.test.ts+++ b/assets/js/dashboard/stats/graph/fetch-top-stats.test.ts@@ -8,7 +8,12 @@ import { ComparisonMode, DashboardPeriod } from '../../dashboard-time-periods'import { PlausibleSite, siteContextDefaultValue } from '../../site-context'import { StatsQuery } from '../../stats-query'import { remapToApiFilters } from '../../util/filters'-import { chooseMetrics, topStatsQueries } from './fetch-top-stats'+import {+ chooseMetrics,+ topStatsQueries,+ getPartialDayTimeRange,+ formatTopStatsData+} from './fetch-top-stats'const aGoalFilter = ['is', 'goal', ['any goal']] as Filterconst aPageFilter = ['is', 'page', ['/any/page']] as Filter@@ -229,6 +234,92 @@ describe(`${chooseMetrics.name}`, () => {)})+describe(`${getPartialDayTimeRange.name}`, () => {+ it('returns "until HH:MM" for today (partial day with current time as end)', () => {+ expect(+ getPartialDayTimeRange(['2024-01-13T00:00:00', '2024-01-13T14:32:00'])+ ).toBe('until 14:32')+ })++ it('returns "until HH:MM" when date strings include a timezone offset', () => {+ expect(+ getPartialDayTimeRange([+ '2026-01-19T00:00:00+00:00',+ '2026-01-19T14:32:00+00:00'+ ])+ ).toBe('until 14:32')+ })++ it('returns null for a full past day ending at 23:59:59', () => {+ expect(+ getPartialDayTimeRange(['2024-01-12T00:00:00', '2024-01-12T23:59:59'])+ ).toBeNull()+ })++ it('returns null when the date range spans multiple days', () => {+ expect(+ getPartialDayTimeRange(['2024-01-12T00:00:00', '2024-01-13T14:32:00'])+ ).toBeNull()+ })++ it('returns null when the end ISO has no time component', () => {+ expect(getPartialDayTimeRange(['2024-01-13', '2024-01-13'])).toBeNull()+ })+})++function makeTopStatsResponse(+ dateRange: [string, string],+ comparisonDateRange: [string, string] | null+) {+ return {+ query: {+ metrics: ['visitors'] as ['visitors'],+ date_range: dateRange,+ comparison_date_range: comparisonDateRange as [string, string]+ },+ meta: {},+ results: [+ {+ metrics: [100],+ dimensions: [],+ comparison: { metrics: [80], change: [25] }+ }+ ]+ }+}++describe(`${formatTopStatsData.name}`, () => {+ const metrics = [{ key: 'visitors' as const, label: 'Visitors' }]++ it('sets comparisonTimeRange to "until HH:MM" when comparison period is also a partial day (Today vs Previous period)', () => {+ const response = makeTopStatsResponse(+ ['2026-04-21T00:00:00', '2026-04-21T10:25:00'],+ ['2026-04-20T00:00:00', '2026-04-20T10:25:00']+ )+ const { timeRange, comparisonTimeRange } = formatTopStatsData(+ response,+ null,+ metrics+ )+ expect(timeRange).toBe('until 10:25')+ expect(comparisonTimeRange).toBe('until 10:25')+ })++ it('sets comparisonTimeRange to null when comparison period is a full day (Today vs Custom period)', () => {+ const response = makeTopStatsResponse(+ ['2026-04-21T00:00:00', '2026-04-21T10:25:00'],+ ['2026-04-20T00:00:00', '2026-04-20T23:59:59']+ )+ const { timeRange, comparisonTimeRange } = formatTopStatsData(+ response,+ null,+ metrics+ )+ expect(timeRange).toBe('until 10:25')+ expect(comparisonTimeRange).toBeNull()+ })+})+describe(`${topStatsQueries.name}`, () => {test.each(cases)('for %s dashboard, queries are as expected',diff --git a/assets/js/dashboard/stats/graph/fetch-top-stats.ts b/assets/js/dashboard/stats/graph/fetch-top-stats.tsindex 4d2e9364ce..d8392f5095 100644--- a/assets/js/dashboard/stats/graph/fetch-top-stats.ts+++ b/assets/js/dashboard/stats/graph/fetch-top-stats.ts@@ -148,7 +148,7 @@ type TopStatItem = {comparisonValue?: number}-function formatTopStatsData(+export function formatTopStatsData(topStatsResponse: api.QueryApiResponse,currentVisitorsResponse: api.QueryApiResponse | null,metrics: MetricDef[]@@ -193,5 +193,41 @@ function formatTopStatsData(? query.comparison_date_range[1].split('T')[0]: null- return { topStats, meta, from, to, comparingFrom, comparingTo }+ const timeRange = getPartialDayTimeRange(query.date_range)++ const comparisonTimeRange = query.comparison_date_range+ ? getPartialDayTimeRange(query.comparison_date_range as [string, string])+ : null++ return {+ topStats,+ meta,+ from,+ to,+ comparingFrom,+ comparingTo,+ timeRange,+ comparisonTimeRange+ }+}++const END_OF_DAY = '23:59:59'++// Returns "until HH:MM" when the date range is a partial day (period=day for+// today, where the range is trimmed to the current time). Returns null otherwise.+export function getPartialDayTimeRange(+ dateRange: [string, string]+): string | null {+ const [startIso, endIso] = dateRange+ if (!endIso.includes('T')) return null++ const [startDate, endDate] = [startIso, endIso].map(+ (iso) => iso.split('T')[0]+ )+ if (startDate !== endDate) return null++ const endTime = endIso.split('T')[1]+ if (endTime.startsWith(END_OF_DAY)) return null++ return `until ${endTime.substring(0, 5)}`}diff --git a/assets/js/dashboard/stats/graph/graph-interval-context.tsx b/assets/js/dashboard/stats/graph/graph-interval-context.tsxnew file mode 100644index 0000000000..d96ec4b9d7--- /dev/null+++ b/assets/js/dashboard/stats/graph/graph-interval-context.tsx@@ -0,0 +1,46 @@+import React, { createContext, useContext } from 'react'+import { useStoredInterval } from './interval-picker'+import { useSiteContext } from '../../site-context'+import { useDashboardStateContext } from '../../dashboard-state-context'+import { Interval } from './intervals'++type GraphIntervalContextValue = {+ selectedInterval: Interval+ onIntervalClick: (interval: Interval) => void+ availableIntervals: Interval[]+}++const GraphIntervalContext = createContext<GraphIntervalContextValue | null>(+ null+)++export function GraphIntervalProvider({+ children+}: {+ children: React.ReactNode+}) {+ const site = useSiteContext()+ const { dashboardState } = useDashboardStateContext()++ const { selectedInterval, onIntervalClick, availableIntervals } =+ useStoredInterval({+ site,+ to: dashboardState.to,+ from: dashboardState.from,+ period: dashboardState.period,+ comparison: dashboardState.comparison,+ compare_to: dashboardState.compare_to,+ compare_from: dashboardState.compare_from+ })++ return (+ <GraphIntervalContext.Provider+ value={{ selectedInterval, onIntervalClick, availableIntervals }}+ >+ {children}+ </GraphIntervalContext.Provider>+ )+}++export const useGraphIntervalContext = (): GraphIntervalContextValue =>+ useContext(GraphIntervalContext)!diff --git a/assets/js/dashboard/stats/graph/imports-included-context.tsx b/assets/js/dashboard/stats/graph/imports-included-context.tsxnew file mode 100644index 0000000000..6d17e7a15c--- /dev/null+++ b/assets/js/dashboard/stats/graph/imports-included-context.tsx@@ -0,0 +1,72 @@+import React, { createContext, useContext, useMemo, useState } from 'react'+import { NoticeProps } from '../../components/notice'+import { useGraphIntervalContext } from './graph-interval-context'+import { useDashboardStateContext } from '../../dashboard-state-context'++type ImportsIncludedInput = {+ switchVisible: boolean+ switchDisabled: boolean+} | null++export type ImportsIncludedContextValue =+ | { status: 'loading' }+ | { status: 'hidden' }+ | {+ status: 'visible'+ disabled: boolean+ intervalUnsupportedNotice: NoticeProps | null+ }++type ImportsIncludedContextType = {+ value: ImportsIncludedContextValue+ setInput: (input: ImportsIncludedInput) => void+}++const ImportsIncludedContext = createContext<ImportsIncludedContextType | null>(+ null+)++export function ImportsIncludedProvider({+ children+}: {+ children: React.ReactNode+}) {+ const [input, setInput] = useState<ImportsIncludedInput>(null)+ const { selectedInterval } = useGraphIntervalContext()+ const { dashboardState } = useDashboardStateContext()++ const value: ImportsIncludedContextValue = useMemo(() => {+ if (input === null) {+ return { status: 'loading' }+ }+ if (!input.switchVisible) {+ return { status: 'hidden' }+ }+ const intervalUnsupportedNotice =+ ['hour', 'minute'].includes(selectedInterval) &&+ dashboardState.with_imported+ ? {+ title: 'Imported data not shown in graph',+ description:+ 'Available as daily totals only. Switch to a daily view to include it.'+ }+ : null+ return {+ status: 'visible',+ disabled: input.switchDisabled,+ intervalUnsupportedNotice+ }+ }, [input, selectedInterval, dashboardState.with_imported])++ return (+ <ImportsIncludedContext.Provider value={{ value, setInput }}>+ {children}+ </ImportsIncludedContext.Provider>+ )+}++export const useImportsIncludedContext = (): ImportsIncludedContextValue =>+ useContext(ImportsIncludedContext)!.value++export const useSetImportsIncluded = () =>+ useContext(ImportsIncludedContext)!.setInputdiff --git a/assets/js/dashboard/stats/graph/interval-picker.tsx b/assets/js/dashboard/stats/graph/interval-picker.tsxindex c088b00dbb..0fe1b49791 100644--- a/assets/js/dashboard/stats/graph/interval-picker.tsx+++ b/assets/js/dashboard/stats/graph/interval-picker.tsx@@ -1,13 +1,6 @@-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { Popover, Transition } from '@headlessui/react'-import { ChevronDownIcon } from '@heroicons/react/20/solid'-import classNames from 'classnames'+import React, { useCallback, useEffect, useMemo, useState } from 'react'import * as storage from '../../util/storage'-import { isModifierPressed, isTyping, Keybind } from '../../keybinding'-import { useDashboardStateContext } from '../../dashboard-state-context'-import { useMatch } from 'react-router-dom'-import { rootRoute } from '../../router'-import { BlurMenuButtonOnEscape, popover } from '../../components/popover'+import { SegmentedControl } from '../../components/segmented-control'import {Interval,GetIntervalProps,@@ -16,7 +9,7 @@ import {} from './intervals'const INTERVAL_LABELS: Record<Interval, string> = {- [Interval.minute]: 'Minutes',+ [Interval.minute]: 'Min',[Interval.hour]: 'Hours',[Interval.day]: 'Days',[Interval.week]: 'Weeks',@@ -122,83 +115,29 @@ export function IntervalPicker({onIntervalClick: (interval: Interval) => voidoptions: Interval[]}): JSX.Element | null {- const menuElement = useRef<HTMLButtonElement>(null)- const { dashboardState } = useDashboardStateContext()- const dashboardRouteMatch = useMatch(rootRoute.path)-- if (dashboardState.period == 'realtime') {+ if (options.length === 0) {return null}+ const controlOptions = options.map((value) => ({+ value,+ label: INTERVAL_LABELS[value] ?? value+ }))+return (- <>- {!!dashboardRouteMatch && (- <Keybind- targetRef="document"- type="keydown"- keyboardKey="i"- handler={() => {- menuElement.current?.click()- }}- shouldIgnoreWhen={[isModifierPressed, isTyping]}- />- )}- <Popover className="relative inline-block">- {({ close: closeDropdown }) => (- <>- <BlurMenuButtonOnEscape targetRef={menuElement} />- <Popover.Button- ref={menuElement}- className={classNames(- popover.toggleButton.classNames.linkLike,- 'rounded-sm text-sm flex items-center'- )}- >- <span data-testid="current-graph-interval">- {INTERVAL_LABELS[selectedInterval]}- </span>- <ChevronDownIcon className="ml-1 h-4 w-4" aria-hidden="true" />- </Popover.Button>-- <Transition- as="div"- {...popover.transition.props}- className={classNames(- popover.transition.classNames.right,- 'mt-2 w-56'- )}- >- <Popover.Panel- className={classNames(- popover.panel.classNames.roundedSheet,- 'font-normal'- )}- >- {options.map((option) => (- <button- key={option}- onClick={() => {- onIntervalClick(option)- closeDropdown()- }}- data-selected={option == selectedInterval}- className={classNames(- popover.items.classNames.navigationLink,- popover.items.classNames.selectedOption,- popover.items.classNames.hoverLink,- 'w-full text-left'- )}- >- <span data-testid="graph-interval">- {INTERVAL_LABELS[option]}- </span>- </button>- ))}- </Popover.Panel>- </Transition>- </>- )}- </Popover>- </>+ <div className="flex justify-between items-center gap-x-2 w-full pl-4 pr-2 py-1">+ <span className="shrink-0 text-sm font-medium text-gray-700 dark:text-gray-100">+ Graph interval+ </span>+ <SegmentedControl+ ariaLabel="Graph data interval"+ options={controlOptions}+ selected={selectedInterval}+ onSelect={onIntervalClick}+ getTestId={(_value, isSelected) =>+ isSelected ? 'current-graph-interval' : 'graph-interval'+ }+ />+ </div>)}diff --git a/assets/js/dashboard/stats/graph/main-graph.tsx b/assets/js/dashboard/stats/graph/main-graph.tsxindex 5e73b82463..d1a2d6f51a 100644--- a/assets/js/dashboard/stats/graph/main-graph.tsx+++ b/assets/js/dashboard/stats/graph/main-graph.tsx@@ -527,7 +527,7 @@ export const MainGraphContainer = React.forwardRef<{ children: ReactNode }>((props, ref) => {return (- <div className="relative my-4 h-92 w-full" ref={ref}>+ <div className="relative mt-4 mb-3 h-92 w-full" ref={ref}>{props.children}</div>)diff --git a/assets/js/dashboard/stats/graph/notices.tsx b/assets/js/dashboard/stats/graph/notices.tsxdeleted file mode 100644index 42c149849d..0000000000--- a/assets/js/dashboard/stats/graph/notices.tsx+++ /dev/null@@ -1,35 +0,0 @@-import React from 'react'-import { Tooltip } from '../../util/tooltip'--export const NoticesIcon = ({ notices }: { notices: string[] }) => {- if (!notices.length) {- return null- }- return (- <Tooltip- info={- <div className="w-[200px] font-normal flex flex-col gap-y-2">- {notices.map((notice, id) => (- <p key={id}>{notice}</p>- ))}- </div>- }- className="cursor-pointer w-4 h-4"- >- <svg- className="absolute w-4 h-4 dark:text-gray-300 text-gray-700"- xmlns="http://www.w3.org/2000/svg"- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth="2"- d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"- />- </svg>- </Tooltip>- )-}diff --git a/assets/js/dashboard/stats/graph/stats-export.tsx b/assets/js/dashboard/stats/graph/stats-export.tsxdeleted file mode 100644index 8fdfcb4c0d..0000000000--- a/assets/js/dashboard/stats/graph/stats-export.tsx+++ /dev/null@@ -1,95 +0,0 @@-import React, { useState } from 'react'-import * as api from '../../api'-import { useSiteContext } from '../../site-context'-import { useDashboardStateContext } from '../../dashboard-state-context'-import { Tooltip } from '../../util/tooltip'--export default function StatsExport({- selectedInterval-}: {- selectedInterval: string-}) {- const site = useSiteContext()- const { dashboardState } = useDashboardStateContext()- const [exporting, setExporting] = useState(false)-- function startExport() {- setExporting(true)- document.cookie = 'exporting='- pollExportReady()- }-- function pollExportReady() {- if (document.cookie.includes('exporting')) {- setTimeout(pollExportReady, 1000)- } else {- setExporting(false)- }- }-- function renderLoading() {- return (- <svg- className="animate-spin h-4 w-4 text-indigo-500"- xmlns="http://www.w3.org/2000/svg"- fill="none"- viewBox="0 0 24 24"- >- <circle- className="opacity-25"- cx="12"- cy="12"- r="10"- stroke="currentColor"- strokeWidth="4"- ></circle>- <path- className="opacity-75"- fill="currentColor"- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"- ></path>- </svg>- )- }-- function renderExportLink() {- const params = api.dashboardStateToSearchParams(dashboardState, [- { interval: selectedInterval, comparison: undefined }- ])- const endpoint = `/${encodeURIComponent(site.domain)}/export?${params}`-- return (- <a- className="block h-4 w-4"- href={endpoint}- download- onClick={startExport}- >- <svg- className="absolute text-gray-700 feather dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600"- xmlns="http://www.w3.org/2000/svg"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- >- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>- <polyline points="7 10 12 15 17 10"></polyline>- <line x1="12" y1="15" x2="12" y2="3"></line>- </svg>- </a>- )- }-- return (- <Tooltip- info={<div className="font-normal truncate">Click to export stats</div>}- className="w-4 h-4"- >- {exporting && renderLoading()}- {!exporting && renderExportLink()}- </Tooltip>- )-}diff --git a/assets/js/dashboard/stats/graph/top-stats.js b/assets/js/dashboard/stats/graph/top-stats.jsindex 55b268e3a4..b3995404f8 100644--- a/assets/js/dashboard/stats/graph/top-stats.js+++ b/assets/js/dashboard/stats/graph/top-stats.js@@ -2,7 +2,7 @@ import React from 'react'import { Tooltip } from '../../util/tooltip'import { SecondsSinceLastLoad } from '../../util/seconds-since-last-load'import classNames from 'classnames'-import { formatDateRange } from '../../util/date'+import { formatDateRange, formatDayShort, parseUTCDate } from '../../util/date'import { useDashboardStateContext } from '../../dashboard-state-context'import { useSiteContext } from '../../site-context'import { useLastLoadContext } from '../../last-load-context'@@ -46,11 +46,6 @@ export default function TopStats({<div className="whitespace-nowrap">{topStatNumberLong(stat.metric, stat.value)} vs.{' '}{topStatNumberLong(stat.metric, stat.comparisonValue)} {statName}- <ChangeArrow- metric={stat.metric}- change={stat.change}- className="pl-4 text-xs text-gray-100"- /></div>)}@@ -111,17 +106,15 @@ export default function TopStats({)}- function renderStatName(stat) {- const isSelected = stat.graphable && stat.metric === selectedMetric-+ function renderStatName(stat, isSelected) {const [statDisplayName, statExtraName] = stat.name.split(/(\(.+\))/g)const statDisplayNameClass = classNames(- 'text-xs text-gray-500 uppercase dark:text-gray-400 whitespace-nowrap flex w-fit border-b',+ 'text-xs uppercase whitespace-nowrap flex w-fit',{- 'text-indigo-600 dark:text-indigo-500 font-bold tracking-[-.01em] border-indigo-600 dark:border-indigo-500':+ 'text-gray-900 dark:text-gray-100 font-bold tracking-[-.01em]':isSelected,- 'font-semibold group-hover:text-indigo-700 dark:group-hover:text-indigo-500 border-transparent':+ 'font-semibold text-gray-500 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-gray-100':!isSelected})@@ -140,11 +133,13 @@ export default function TopStats({}function renderStat(stat, index) {+ const isSelected = stat.graphable && stat.metric === selectedMetric+const className = classNames(- 'px-4 md:px-6 w-1/2 my-4 lg:w-auto group select-none',+ 'lg:flex-1 px-4 w-1/2 my-2 lg:w-auto group select-none',{'cursor-pointer': stat.graphable,- 'lg:border-l border-gray-300 dark:border-gray-700': index > 0,+ 'lg:border-l border-gray-200 dark:border-gray-750': index > 0,'border-r lg:border-r-0': index % 2 === 0})@@ -156,12 +151,19 @@ export default function TopStats({onClick={stat.graphable ? () => onMetricClick(stat.metric) : () => {}}boundary={tooltipBoundary}>- {renderStatName(stat)}- <div className="my-1 space-y-2">+ <div+ className={classNames(+ 'flex flex-col gap-y-1 p-2 -mx-2 rounded-md hover:bg-gray-100/80 dark:hover:bg-gray-800',+ {+ 'bg-gray-100/70 dark:bg-gray-800': isSelected+ }+ )}+ >+ {renderStatName(stat, isSelected)}<div>- <span className="flex items-center justify-between whitespace-nowrap">+ <span className="flex items-baseline whitespace-nowrap"><p- className="font-bold text-xl dark:text-gray-100"+ className="font-semibold text-[1.2rem] text-gray-900 dark:text-gray-100"id={stat.name === 'Current visitors'? 'current_visitors'@@ -170,31 +172,35 @@ export default function TopStats({>{topStatNumberShort(stat.metric, stat.value)}</p>- {!isComparison && stat.change != null ? (+ {stat.change != null ? (<ChangeArrowmetric={stat.metric}change={stat.change}- className="pl-2 text-xs dark:text-gray-100"+ className="ml-2 text-xs font-medium text-gray-500 dark:text-gray-100"/>) : null}</span>{isComparison ? (- <p className="text-xs dark:text-gray-100">- {formatDateRange(site, data.from, data.to)}+ <p className="text-xs dark:text-gray-100 font-medium">+ {data.timeRange+ ? `${formatDayShort(parseUTCDate(data.from))}, ${data.timeRange}`+ : formatDateRange(site, data.from, data.to)}</p>) : null}</div>{isComparison ? (- <div>+ <div className="mt-1"><pid={`previous-${stat.metric}`}- className="font-bold text-xl text-gray-500 dark:text-gray-400"+ className="font-semibold text-[1.2rem] text-gray-500/80 dark:text-gray-400">{topStatNumberShort(stat.metric, stat.comparisonValue)}</p>- <p className="text-xs text-gray-500 dark:text-gray-400">- {formatDateRange(site, data.comparingFrom, data.comparingTo)}+ <p className="text-xs text-gray-500 dark:text-gray-400 font-medium">+ {data.comparisonTimeRange+ ? `${formatDayShort(parseUTCDate(data.comparingFrom))}, ${data.comparisonTimeRange}`+ : formatDateRange(site, data.comparingFrom, data.comparingTo)}</p></div>) : null}diff --git a/assets/js/dashboard/stats/graph/visitor-graph.tsx b/assets/js/dashboard/stats/graph/visitor-graph.tsxindex 13edd48c8c..d6047ae36f 100644--- a/assets/js/dashboard/stats/graph/visitor-graph.tsx+++ b/assets/js/dashboard/stats/graph/visitor-graph.tsx@@ -3,10 +3,6 @@ import * as storage from '../../util/storage'import TopStats from './top-stats'import { fetchTopStats } from './fetch-top-stats'import { fetchMainGraph } from './fetch-main-graph'-import { IntervalPicker, useStoredInterval } from './interval-picker'-import StatsExport from './stats-export'-import WithImportedSwitch from './with-imported-switch'-import { NoticesIcon } from './notices'import { useDashboardStateContext } from '../../dashboard-state-context'import { PlausibleSite, useSiteContext } from '../../site-context'import { useQuery, useQueryClient } from '@tanstack/react-query'@@ -16,6 +12,8 @@ import { DashboardState } from '../../dashboard-state'import { nowForSite } from '../../util/date'import { getStaleTime } from '../../hooks/api-client'import { MainGraph, MainGraphContainer, useMainGraphWidth } from './main-graph'+import { useGraphIntervalContext } from './graph-interval-context'+import { useSetImportsIncluded } from './imports-included-context'// height of at least one row of top statsconst DEFAULT_TOP_STATS_LOADING_HEIGHT_PX = 85@@ -34,16 +32,7 @@ export default function VisitorGraph({const queryClient = useQueryClient()const startOfDay = nowForSite(site).startOf('day')- const { selectedInterval, onIntervalClick, availableIntervals } =- useStoredInterval({- site: site,- to: dashboardState.to,- from: dashboardState.from,- period: dashboardState.period,- comparison: dashboardState.comparison,- compare_to: dashboardState.compare_to,- compare_from: dashboardState.compare_from- })+ const { selectedInterval } = useGraphIntervalContext()const [selectedMetric, setSelectedMetric] = useState<Metric | null>(getStoredMetric(site)@@ -190,16 +179,25 @@ export default function VisitorGraph({}}, [queryClient, isRealtime])- const importedSwitchVisible = !['no_imported_data', 'out_of_range'].includes(+ const switchVisible = !['no_imported_data', 'out_of_range'].includes(topStatsQuery.data?.meta.imports_skip_reason as string)+ const switchDisabled =+ topStatsQuery.data?.meta.imports_skip_reason === 'unsupported_query'++ const setImportsIncluded = useSetImportsIncluded()++ useEffect(() => {+ if (topStatsQuery.data) {+ setImportsIncluded({ switchVisible, switchDisabled })+ } else {+ setImportsIncluded(null)+ }+ }, [topStatsQuery.data, switchVisible, switchDisabled, setImportsIncluded])- const importedIntervalUnsupportedNotice =- ['hour', 'minute'].includes(selectedInterval) &&- importedSwitchVisible &&- dashboardState.with_imported- ? 'Interval is too short to graph imported data'- : null+ useEffect(() => {+ return () => setImportsIncluded(null)+ }, [setImportsIncluded])const { heightPx } = useGuessTopStatsHeight(site, topStatsBoundary)@@ -215,7 +213,7 @@ export default function VisitorGraph({!showFullLoaderreturn (- <div className="col-span-full relative w-full bg-white rounded-md shadow dark:bg-gray-900">+ <div className="col-span-full relative w-full bg-white rounded-md shadow-sm dark:bg-gray-900"><><divid="top-stats-container"@@ -238,42 +236,7 @@ export default function VisitorGraph({></div>)}</div>- <div className="relative px-2">- {topStatsQuery.data && (- <div className="absolute right-4 -top-8 py-1 flex items-center gap-x-4">- <NoticesIcon- notices={- [importedIntervalUnsupportedNotice].filter(- (n) => !!n- ) as string[]- }- />- {!isRealtime && (- <StatsExport selectedInterval={selectedInterval} />- )}- {importedSwitchVisible && (- <WithImportedSwitch- tooltipMessage={- topStatsQuery.data.meta.imports_skip_reason ===- 'unsupported_query'- ? 'Imported data cannot be included'- : topStatsQuery.data.meta.imports_included- ? 'Click to exclude imported data'- : 'Click to include imported data'- }- disabled={- topStatsQuery.data.meta.imports_skip_reason ===- 'unsupported_query'- }- />- )}- <IntervalPicker- selectedInterval={selectedInterval}- onIntervalClick={onIntervalClick}- options={availableIntervals}- />- </div>- )}+ <div className="relative flex flex-col pl-3 pr-4"><MainGraphContainer ref={mainGraphContainer}>{!!mainGraphQuery.data && !!width && (<>diff --git a/assets/js/dashboard/stats/graph/with-imported-switch.tsx b/assets/js/dashboard/stats/graph/with-imported-switch.tsxdeleted file mode 100644index 1beef3cdae..0000000000--- a/assets/js/dashboard/stats/graph/with-imported-switch.tsx+++ /dev/null@@ -1,40 +0,0 @@-import React from 'react'-import { BarsArrowUpIcon } from '@heroicons/react/20/solid'-import classNames from 'classnames'-import { useDashboardStateContext } from '../../dashboard-state-context'-import { AppNavigationLink } from '../../navigation/use-app-navigate'-import { Tooltip } from '../../util/tooltip'--export default function WithImportedSwitch({- tooltipMessage,- disabled-}: {- tooltipMessage: string- disabled?: boolean-}) {- const { dashboardState } = useDashboardStateContext()- const importsSwitchedOn = dashboardState.with_imported-- const iconClass = classNames('size-4', {- 'dark:text-gray-300 text-gray-700': importsSwitchedOn,- 'dark:text-gray-500 text-gray-400': !importsSwitchedOn- })-- return (- <Tooltip- info={<div className="font-normal truncate">{tooltipMessage}</div>}- className="size-4"- >- <AppNavigationLink- search={- disabled- ? (search) => search- : (search) => ({ ...search, with_imported: !importsSwitchedOn })- }- className="flex items-center justify-center"- >- <BarsArrowUpIcon data-testid="import-switch" className={iconClass} />- </AppNavigationLink>- </Tooltip>- )-}diff --git a/assets/js/dashboard/stats/reports/change-arrow.test.tsx b/assets/js/dashboard/stats/reports/change-arrow.test.tsxindex c226575ccd..6e3a9bc4e7 100644--- a/assets/js/dashboard/stats/reports/change-arrow.test.tsx+++ b/assets/js/dashboard/stats/reports/change-arrow.test.tsx@@ -3,15 +3,19 @@ import { render, screen } from '@testing-library/react'import { ChangeArrow } from './change-arrow'jest.mock('@heroicons/react/24/solid', () => ({- ArrowUpRightIcon: ({ className }: { className: string }) => (- <span className={className}>↑</span>+ ArrowUpRightIcon: ({ className, ...props }: { className: string }) => (+ <span className={className} {...props}>+ ↑+ </span>),- ArrowDownRightIcon: ({ className }: { className: string }) => (- <span className={className}>↓</span>+ ArrowDownRightIcon: ({ className, ...props }: { className: string }) => (+ <span className={className} {...props}>+ ↓+ </span>)}))-it('renders green for positive change', () => {+it('renders up arrow for positive change', () => {render(<ChangeArrow change={1} className="text-xs" metric="visitors" />)const arrowElement = screen.getByTestId('change-arrow')@@ -20,33 +24,34 @@ it('renders green for positive change', () => {expect(arrowElement.children[0]).toHaveClass('text-green-500')})-it('renders red for positive change', () => {+it('renders down arrow for negative change', () => {render(<ChangeArrow change={-10} className="text-xs" metric="visitors" />)const arrowElement = screen.getByTestId('change-arrow')expect(arrowElement).toHaveTextContent('↓ 10%')- expect(arrowElement.children[0]).toHaveClass('text-red-400')+ expect(arrowElement.children[0]).toHaveClass('text-red-500')})-it('renders tilde for no change', () => {+it('renders no arrow for no change', () => {render(<ChangeArrow change={0} className="text-xs" metric="visitors" />)const arrowElement = screen.getByTestId('change-arrow')expect(arrowElement).toHaveTextContent('0%')+ expect(arrowElement.children).toHaveLength(0)})-it('inverts colors for positive bounce_rate change', () => {+it('inverts arrow direction for positive bounce_rate change', () => {render(<ChangeArrow change={15} className="text-xs" metric="bounce_rate" />)const arrowElement = screen.getByTestId('change-arrow')expect(arrowElement).toHaveTextContent('↑ 15%')- expect(arrowElement.children[0]).toHaveClass('text-red-400')+ expect(arrowElement.children[0]).toHaveClass('text-red-500')})-it('inverts colors for negative bounce_rate change', () => {+it('inverts arrow direction for negative bounce_rate change', () => {render(<ChangeArrow change={-3} className="text-xs" metric="bounce_rate" />)const arrowElement = screen.getByTestId('change-arrow')@@ -63,7 +68,7 @@ it('renders with text hidden', () => {const arrowElement = screen.getByTestId('change-arrow')expect(arrowElement).toHaveTextContent('↓')- expect(arrowElement.children[0]).toHaveClass('text-red-400')+ expect(arrowElement.children[0]).toHaveClass('text-red-500')})it('renders no content with text hidden and 0 change', () => {diff --git a/assets/js/dashboard/stats/reports/change-arrow.tsx b/assets/js/dashboard/stats/reports/change-arrow.tsxindex 3156ca6709..d6b8c4ccde 100644--- a/assets/js/dashboard/stats/reports/change-arrow.tsx+++ b/assets/js/dashboard/stats/reports/change-arrow.tsx@@ -18,7 +18,7 @@ export function ChangeArrow({let icon = nullconst arrowClassName = classNames(color(change, metric),- 'mb-0.5 inline-block size-3 stroke-[1px] stroke-current'+ 'mb-0.5 inline-block size-2.5 stroke-[1.5px] stroke-current')if (change > 0) {@@ -42,5 +42,5 @@ export function ChangeArrow({function color(change: number, metric: Metric) {const invert = metric === 'bounce_rate'- return change > 0 != invert ? 'text-green-500' : 'text-red-400'+ return change > 0 != invert ? 'text-green-500' : 'text-red-500'}diff --git a/assets/test-utils/app-context-providers.tsx b/assets/test-utils/app-context-providers.tsxindex 3dd82307e6..1e40a191d8 100644--- a/assets/test-utils/app-context-providers.tsx+++ b/assets/test-utils/app-context-providers.tsx@@ -13,6 +13,8 @@ import { getRouterBasepath } from '../js/dashboard/router'import { RoutelessModalsContextProvider } from '../js/dashboard/navigation/routeless-modals-context'import { SegmentsContextProvider } from '../js/dashboard/filtering/segments-context'import { SavedSegment, SavedSegments } from '../js/dashboard/filtering/segments'+import { GraphIntervalProvider } from '../js/dashboard/stats/graph/graph-interval-context'+import { ImportsIncludedProvider } from '../js/dashboard/stats/graph/imports-included-context'type TestContextProvidersProps = {children: ReactNode@@ -92,7 +94,11 @@ export const TestContextProviders = ({<QueryClientProvider client={queryClient}><RoutelessModalsContextProvider><DashboardStateContextProvider>- {children}+ <GraphIntervalProvider>+ <ImportsIncludedProvider>+ {children}+ </ImportsIncludedProvider>+ </GraphIntervalProvider></DashboardStateContextProvider></RoutelessModalsContextProvider></QueryClientProvider>diff --git a/e2e/tests/dashboard/filtering.spec.ts b/e2e/tests/dashboard/filtering.spec.tsindex 45051ea9c1..a106e02a79 100644--- a/e2e/tests/dashboard/filtering.spec.ts+++ b/e2e/tests/dashboard/filtering.spec.ts@@ -569,7 +569,8 @@ test.describe('location filtering tests', () => {name: 'pageview',country_code: 'EE',subdivision1_code: 'EE-37',- city_geoname_id: 588_409+ city_geoname_id: 588_409,+ browser: 'Chrome'}]})@@ -618,6 +619,18 @@ test.describe('location filtering tests', () => {await test.step('filtering by city', async () => {const cityFilterRow = filterRow(page, 'city')const cityInput = page.getByPlaceholder('Select a City')+ const browserFilterRow = filterRow(page, 'browser')+ const browserInput = page.getByPlaceholder('Select a Browser', {+ exact: true+ })++ // Add a browser filter so city ends up as the 4th pill. This ensures it overflows+ // into "See more" regardless of viewport width.+ await filterButton(page).click()+ await filterItemButton(page, 'Browser').click()+ await browserInput.fill('chrom')+ await suggestedItem(browserFilterRow, 'Chrome').click()+ await applyFilterButton(page).click()await filterButton(page).click()await locationFilterButton(page).click()@@ -627,10 +640,7 @@ test.describe('location filtering tests', () => {await applyFilterButton(page).click()- await page- .getByRole('button', { name: 'See 1 more filter and actions' })- .click()-+ await page.getByRole('button', { name: /See.*more/ }).click()await expect(page.getByRole('link', { name: 'City is Tallinn' })).toBeVisible()@@ -759,7 +769,9 @@ test.describe('operating system filtering tests', () => {{name: 'pageview',operating_system: 'Windows',- operating_system_version: '11'+ operating_system_version: '11',+ browser: 'Chrome',+ browser_version: '14.0.7'},{name: 'pageview',@@ -799,6 +811,28 @@ test.describe('operating system filtering tests', () => {const operatingSystemVersionInput = page.getByPlaceholder('Select an Operating system version')+ const browserFilterRow = filterRow(page, 'browser')+ const browserVersionFilterRow = filterRow(page, 'browser_version')+ const browserInput = page.getByPlaceholder('Select a Browser', {+ exact: true+ })+ const browserVersionInput = page.getByPlaceholder(+ 'Select a Browser Version'+ )++ // Add browser and browser version filters so OS version ends up as the 4th pill.+ // This ensures it overflows into "See more" regardless of viewport width+ await filterButton(page).click()+ await filterItemButton(page, 'Browser').click()+ await browserInput.fill('chrom')+ await suggestedItem(browserFilterRow, 'Chrome').click()+ await applyFilterButton(page).click()++ await filterButton(page).click()+ await filterItemButton(page, 'Browser').click()+ await browserVersionInput.fill('14')+ await suggestedItem(browserVersionFilterRow, '14.0.7').click()+ await applyFilterButton(page).click()await filterButton(page).click()await operatingSystemFilterButton(page).click()@@ -808,10 +842,7 @@ test.describe('operating system filtering tests', () => {await applyFilterButton(page).click()- await page- .getByRole('button', { name: 'See 1 more filter and actions' })- .click()-+ await page.getByRole('button', { name: /See.*more/ }).click()await expect(page.getByRole('link', { name: 'Operating system version is 11' })).toBeVisible()diff --git a/e2e/tests/dashboard/general.spec.ts b/e2e/tests/dashboard/general.spec.tsindex 3be760a2d9..ec2c800d21 100644--- a/e2e/tests/dashboard/general.spec.ts+++ b/e2e/tests/dashboard/general.spec.ts@@ -28,7 +28,7 @@ test('dashboard renders for anonymous viewer', async ({ page, request }) => {await expect(page).toHaveTitle(/Plausible/)- await expect(page.getByRole('button', { name: domain })).toBeVisible()+ await expect(page.getByTestId('site-switcher-static')).toContainText(domain)})test('dashboard renders via shared link', async ({ page, request }) => {@@ -46,7 +46,7 @@ test('dashboard renders via shared link', async ({ page, request }) => {await test.step('public link', async () => {await page.goto(link, { waitUntil: 'commit' })- await expect(page.getByRole('button', { name: domain })).toBeVisible()+ await expect(page.getByTestId('site-switcher-static')).toContainText(domain)await expect(page.locator('#visitors')).toHaveText('1')})@@ -58,12 +58,31 @@ test('dashboard renders via shared link', async ({ page, request }) => {await page.getByRole('button', { name: 'Continue' }).click()- await expect(page.getByRole('button', { name: domain })).toBeVisible()+ await expect(page.getByTestId('site-switcher-static')).toContainText(domain)await expect(page.locator('#visitors')).toHaveText('1')})})+test('site switcher is not shown when viewing without being logged in', async ({+ page,+ request+}) => {+ const { domain } = await setupSite({ page, request })+ await makeSitePublic({ page, domain })+ await populateStats({ request, domain, events: [{ name: 'pageview' }] })+ await logout(page)++ await page.goto('/' + domain, { waitUntil: 'commit' })++ const siteSwitcherStatic = page.getByTestId('site-switcher-static')+ await expect(siteSwitcherStatic).toContainText(domain)+ await expect(siteSwitcherStatic).not.toHaveRole('button')++ await siteSwitcherStatic.click()+ await expect(page.getByTestId('sitemenu')).not.toBeVisible()+})+test('dashboard renders with imported data', async ({ page, request }) => {const { domain } = await setupSite({ page, request })await populateStats({@@ -91,6 +110,7 @@ test('dashboard renders with imported data', async ({ page, request }) => {})await test.step('with imported data excluded', async () => {+ await page.getByTestId('dashboard-options-menu').click()await page.getByTestId('import-switch').click()await expect(page).toHaveURL(/with_imported=false/)diff --git a/e2e/tests/dashboard/segments.spec.ts b/e2e/tests/dashboard/segments.spec.tsindex 80a46432da..4a5699ca0e 100644--- a/e2e/tests/dashboard/segments.spec.ts+++ b/e2e/tests/dashboard/segments.spec.ts@@ -22,7 +22,13 @@ const setupSiteAndStats = async ({request,domain: context.domain,events: [- { name: 'pageview', referrer_source: 'Google', utm_source: 'Adwords' },+ {+ name: 'pageview',+ referrer_source: 'Google',+ utm_source: 'Adwords',+ utm_medium: 'email',+ utm_campaign: 'promo'+ },{ name: 'pageview', referrer_source: 'Facebook', utm_source: 'fb' },{ name: 'pageview', referrer: 'https://theguardian.com' }]@@ -226,14 +232,28 @@ test('creating a segment from a combination of segment and a filter is not allowawait createPersonalSegment(page, 'Traffic from Google')await addUtmSourceFilter(page, 'Adwords')+ // Add UTM medium and campaign filters so Segment ends up as the 4th pill.+ // This ensures it overflows into "See more" regardless of viewport width+ const utmMediumFilterRow = filterRow(page, 'utm_medium')+ const utmCampaignFilterRow = filterRow(page, 'utm_campaign')++ await filterButton(page).click()+ await utmTagsFilterButton(page).click()+ await page.getByPlaceholder('Select a UTM Medium').click()+ await suggestedItem(utmMediumFilterRow, 'email').click()+ await applyFilterButton(page).click()++ await filterButton(page).click()+ await utmTagsFilterButton(page).click()+ await page.getByPlaceholder('Select a UTM Campaign').click()+ await suggestedItem(utmCampaignFilterRow, 'promo').click()+ await applyFilterButton(page).click()+await expect(page.getByRole('link', { name: 'UTM source is Adwords' })).toBeVisible()- await page- .getByRole('button', { name: 'See 1 more filter and actions' })- .click()-+ await page.getByRole('button', { name: /See.*more/ }).click()await expect(page.getByRole('link', { name: 'Segment is Traffic from Google' })).toBeVisible()diff --git a/e2e/tests/dashboard/top-stats.spec.ts b/e2e/tests/dashboard/top-stats.spec.tsindex 424e27fdc1..bac5388fa5 100644--- a/e2e/tests/dashboard/top-stats.spec.ts+++ b/e2e/tests/dashboard/top-stats.spec.ts@@ -244,15 +244,14 @@ test('different graph time intervals are available', async ({'Last 28 days')- const intervalButton = page.getByTestId('current-graph-interval')- const intervalOptions = page.getByTestId('graph-interval')- await expect(intervalButton).toHaveText('Days')- await intervalButton.click()- await expect(intervalOptions).toHaveCount(2)- const intervalOptions28Days = await intervalOptions.allTextContents()+ const optionsMenu = page.getByTestId('dashboard-options-menu')- expect(intervalOptions28Days.indexOf('Days') > -1).toBeTruthy()- expect(intervalOptions28Days.indexOf('Weeks') > -1).toBeTruthy()+ await optionsMenu.click()+ const graphIntervalSegments = page.getByTestId('graph-interval')+ await expect(page.getByTestId('current-graph-interval')).toHaveText('Days')+ await expect(graphIntervalSegments).toHaveCount(1)+ await expect(graphIntervalSegments.filter({ hasText: 'Weeks' })).toBeVisible()+ await optionsMenu.click()await page.getByTestId('current-query-period').click()await page@@ -260,14 +259,11 @@ test('different graph time intervals are available', async ({.getByRole('link', { name: 'Today' }).click()- await expect(intervalButton).toHaveText('Hours')- await intervalButton.click()- // The popover does not appear right away- await expect(intervalOptions).toHaveCount(2)- const intervalOptionsToday = await intervalOptions.allTextContents()-- expect(intervalOptionsToday.indexOf('Hours') > -1).toBeTruthy()- expect(intervalOptionsToday.indexOf('Minutes') > -1).toBeTruthy()+ await optionsMenu.click()+ await expect(page.getByTestId('current-graph-interval')).toHaveText('Hours')+ await expect(graphIntervalSegments).toHaveCount(1)+ await graphIntervalSegments.filter({ hasText: 'Min' }).click()+ await expect(page.getByTestId('current-graph-interval')).toHaveText('Min')})test('navigating dates previous next time periods', async ({diff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.exindex c6b1861c28..a2016e73c7 100644--- a/lib/plausible_web/components/generic.ex+++ b/lib/plausible_web/components/generic.ex@@ -815,11 +815,15 @@ defmodule PlausibleWeb.Components.Generic dodefp icon_class(link_assigns) doclasses = List.wrap(link_assigns[:class]) |> Enum.join(" ")- if String.contains?(classes, "text-sm") or- String.contains?(classes, "text-xs") do- ["size-3"]- else- ["size-4"]+ cond do+ String.contains?(classes, "text-sm") ->+ ["size-3.5"]++ String.contains?(classes, "text-xs") ->+ ["size-3"]++ true ->+ ["size-4"]endenddiff --git a/lib/plausible_web/templates/layout/_header.html.heex b/lib/plausible_web/templates/layout/_header.html.heexindex 48d64ed2c3..ed575265e2 100644--- a/lib/plausible_web/templates/layout/_header.html.heex+++ b/lib/plausible_web/templates/layout/_header.html.heex@@ -1,4 +1,4 @@-<nav class="relative z-20 py-8">+<nav class="relative z-20 py-5"><div class="container print:max-w-full"><nav class="relative flex items-center justify-between sm:h-10 md:justify-center"><div class="flex items-center flex-1 md:absolute md:inset-y-0 md:left-0">@@ -10,7 +10,7 @@logo_path("logo_dark.svg"))}- class="w-32 hidden dark:inline"+ class="w-30 hidden dark:inline"alt="Plausible logo"loading="lazy"/>@@ -21,7 +21,7 @@logo_path("logo_light.svg"))}- class="w-32 inline dark:hidden"+ class="w-30 inline dark:hidden"alt="Plausible logo"loading="lazy"/>@@ -36,7 +36,7 @@Plausible.Auth.is_super_admin?(@conn.assigns[:current_user])}><.styled_link- class="text-sm mr-6"+ class="text-sm font-medium"href={"/cs/sites/site/#{@conn.assigns.site.id}"}new_tab={true}>diff --git a/lib/plausible_web/templates/stats/stats.html.heex b/lib/plausible_web/templates/stats/stats.html.heexindex 34d7ead359..92b97958f2 100644--- a/lib/plausible_web/templates/stats/stats.html.heex+++ b/lib/plausible_web/templates/stats/stats.html.heex@@ -11,7 +11,6 @@</div><% end %>- <div class="pt-6"></div><divid="stats-react-container"style="overflow-anchor: none;"