Skip to content

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

Remove duplication related to nav menu (#4666)

Artur Pata80fa21a86538
diff --git a/assets/js/dashboard/historical.js b/assets/js/dashboard/historical.js
deleted file mode 100644
index 76d0ce49b1..0000000000
--- a/assets/js/dashboard/historical.js
+++ /dev/null
@@ -1,63 +0,0 @@
-import React from 'react';
-
-import QueryPeriodPicker from './datepicker'
-import SiteSwitcher from './site-switcher'
-import Filters from './filters'
-import CurrentVisitors from './stats/current-visitors'
-import VisitorGraph from './stats/graph/visitor-graph'
-import Sources from './stats/sources'
-import Pages from './stats/pages'
-import Locations from './stats/locations';
-import Devices from './stats/devices'
-import Behaviours from './stats/behaviours'
-import { withPinnedHeader } from './pinned-header-hoc';
-import { statsBoxClass } from './index';
-import { useSiteContext } from './site-context';
-import { useQueryContext } from './query-context';
-import { useUserContext } from './user-context';
-
-function Historical({ stuck, importedDataInView, updateImportedDataInView }) {
- const site = useSiteContext();
- const user = useUserContext();
- const { query } = useQueryContext();
- const tooltipBoundary = React.useRef(null)
-
- return (
- <div className="mb-12">
- <div id="stats-container-top"></div>
- <div className={`relative top-0 sm:py-3 py-2 z-10 ${stuck && !site.embedded ? 'sticky fullwidth-shadow bg-gray-50 dark:bg-gray-850' : ''}`}>
- <div className="items-center w-full flex">
- <div className="flex items-center w-full" ref={tooltipBoundary}>
- <SiteSwitcher site={site} loggedIn={user.loggedIn} currentUserRole={user.role} />
- <CurrentVisitors tooltipBoundary={tooltipBoundary.current} />
- <Filters className="flex" />
- </div>
- <QueryPeriodPicker />
- </div>
- </div>
- <VisitorGraph updateImportedDataInView={updateImportedDataInView} />
-
- <div className="w-full md:flex">
- <div className={statsBoxClass}>
- <Sources />
- </div>
- <div className={statsBoxClass}>
- <Pages />
- </div>
- </div>
-
- <div className="w-full md:flex">
- <div className={statsBoxClass}>
- <Locations site={site} query={query} />
- </div>
- <div className={statsBoxClass}>
- <Devices />
- </div>
- </div>
-
- <Behaviours importedDataInView={importedDataInView} />
- </div>
- )
-}
-
-export default withPinnedHeader(Historical, '#stats-container-top');
diff --git a/assets/js/dashboard/index.js b/assets/js/dashboard/index.js
deleted file mode 100644
index 5672722297..0000000000
--- a/assets/js/dashboard/index.js
+++ /dev/null
@@ -1,27 +0,0 @@
-import React, { useState } from 'react';
-
-import Historical from './historical'
-import Realtime from './realtime'
-import { useIsRealtimeDashboard } from './util/filters'
-
-export const statsBoxClass = "stats-item relative w-full mt-6 p-4 flex flex-col bg-white dark:bg-gray-825 shadow-xl rounded"
-
-function Dashboard() {
- const isRealTimeDashboard = useIsRealtimeDashboard();
- const [importedDataInView, setImportedDataInView] = useState(false)
-
- if (isRealTimeDashboard) {
- return (
- <Realtime />
- )
- } else {
- return (
- <Historical
- importedDataInView={importedDataInView}
- updateImportedDataInView={setImportedDataInView}
- />
- )
- }
-}
-
-export default Dashboard
diff --git a/assets/js/dashboard/index.tsx b/assets/js/dashboard/index.tsx
new file mode 100644
index 0000000000..c578524da4
--- /dev/null
+++ b/assets/js/dashboard/index.tsx
@@ -0,0 +1,69 @@
+/** @format */
+
+import React, { useState } from 'react'
+
+import { useIsRealtimeDashboard } from './util/filters'
+import VisitorGraph from './stats/graph/visitor-graph'
+import Sources from './stats/sources'
+import Pages from './stats/pages'
+import Locations from './stats/locations'
+import Devices from './stats/devices'
+import { TopBar } from './nav-menu/top-bar'
+import Behaviours from './stats/behaviours'
+
+function DashboardStats({
+ importedDataInView,
+ updateImportedDataInView
+}: {
+ importedDataInView?: boolean
+ updateImportedDataInView?: (v: boolean) => void
+}) {
+ const statsBoxClass =
+ 'stats-item relative w-full mt-6 p-4 flex flex-col bg-white dark:bg-gray-825 shadow-xl rounded'
+
+ return (
+ <>
+ <VisitorGraph updateImportedDataInView={updateImportedDataInView} />
+ <div className="w-full md:flex">
+ <div className={statsBoxClass}>
+ <Sources />
+ </div>
+ <div className={statsBoxClass}>
+ <Pages />
+ </div>
+ </div>
+
+ <div className="w-full md:flex">
+ <div className={statsBoxClass}>
+ <Locations />
+ </div>
+ <div className={statsBoxClass}>
+ <Devices />
+ </div>
+ </div>
+
+ <Behaviours importedDataInView={importedDataInView} />
+ </>
+ )
+}
+
+function Dashboard() {
+ const isRealTimeDashboard = useIsRealtimeDashboard()
+ const [importedDataInView, setImportedDataInView] = useState(false)
+
+ return (
+ <div className="mb-12">
+ <TopBar showCurrentVisitors={!isRealTimeDashboard} />
+ <DashboardStats
+ importedDataInView={
+ isRealTimeDashboard ? undefined : importedDataInView
+ }
+ updateImportedDataInView={
+ isRealTimeDashboard ? undefined : setImportedDataInView
+ }
+ />
+ </div>
+ )
+}
+
+export default Dashboard
diff --git a/assets/js/dashboard/nav-menu/top-bar.test.tsx b/assets/js/dashboard/nav-menu/top-bar.test.tsx
new file mode 100644
index 0000000000..8a2868859e
--- /dev/null
+++ b/assets/js/dashboard/nav-menu/top-bar.test.tsx
@@ -0,0 +1,109 @@
+/** @format */
+
+import React from 'react'
+import {
+ render,
+ screen,
+ waitFor,
+ fireEvent,
+ waitForElementToBeRemoved
+} from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { TestContextProviders } from '../../../test-utils/app-context-providers'
+import { TopBar } from './top-bar'
+import { MockAPI } from '../../../test-utils/mock-api'
+
+const domain = 'dummy.site'
+const domains = [domain, 'example.com', 'blog.example.com']
+
+let mockAPI: MockAPI
+
+beforeAll(() => {
+ global.IntersectionObserver = jest.fn(
+ () =>
+ ({
+ observe: jest.fn(),
+ unobserve: jest.fn(),
+ disconnect: jest.fn()
+ }) as unknown as IntersectionObserver
+ )
+ mockAPI = new MockAPI().start()
+})
+
+afterAll(() => {
+ mockAPI.stop()
+})
+
+beforeEach(() => {
+ mockAPI.clear()
+ mockAPI.get('/api/sites', { data: domains.map((domain) => ({ domain })) })
+})
+
+test('user can open and close site switcher', async () => {
+ render(<TopBar showCurrentVisitors={false} />, {
+ wrapper: (props) => (
+ <TestContextProviders siteOptions={{ domain }} {...props} />
+ )
+ })
+
+ const toggleSiteSwitcher = screen.getByRole('button', { name: domain })
+ await userEvent.click(toggleSiteSwitcher)
+ expect(screen.queryAllByRole('link').map((el) => el.textContent)).toEqual(
+ [
+ ['example.com', '2'],
+ ['blog.example.com', '3']
+ ].map((a) => a.join(''))
+ )
+ expect(screen.queryAllByRole('menuitem').map((el) => el.textContent)).toEqual(
+ ['Site Settings', 'View All']
+ )
+ await userEvent.click(toggleSiteSwitcher)
+ expect(screen.queryAllByRole('menuitem')).toEqual([])
+})
+
+test('user can open and close filters dropdown', async () => {
+ render(<TopBar showCurrentVisitors={false} />, {
+ wrapper: (props) => (
+ <TestContextProviders siteOptions={{ domain }} {...props} />
+ )
+ })
+
+ const toggleFilters = screen.getByRole('button', { name: /Filter/ })
+ await userEvent.click(toggleFilters)
+ expect(screen.queryAllByRole('menuitem').map((el) => el.textContent)).toEqual(
+ [
+ 'Page',
+ 'Source',
+ 'Location',
+ 'Screen size',
+ 'Browser',
+ 'Operating System',
+ 'UTM tags',
+ 'Goal',
+ 'Hostname'
+ ]
+ )
+ await userEvent.click(toggleFilters)
+ expect(screen.queryAllByRole('menuitem')).toEqual([])
+})
+
+test('current visitors renders when visitors are present and disappears after visitors are null', async () => {
+ mockAPI.get(`/api/stats/${domain}/current-visitors?`, 500)
+ render(<TopBar showCurrentVisitors={true} />, {
+ wrapper: (props) => (
+ <TestContextProviders siteOptions={{ domain }} {...props} />
+ )
+ })
+
+ await waitFor(() => {
+ expect(
+ screen.queryByRole('link', { name: /500 current visitors/ })
+ ).toBeVisible()
+ })
+
+ mockAPI.get(`/api/stats/${domain}/current-visitors?`, null)
+ fireEvent(document, new CustomEvent('tick'))
+ await waitForElementToBeRemoved(() =>
+ screen.queryByRole('link', { name: /current visitors/ })
+ )
+})
diff --git a/assets/js/dashboard/nav-menu/top-bar.tsx b/assets/js/dashboard/nav-menu/top-bar.tsx
new file mode 100644
index 0000000000..615ea00efc
--- /dev/null
+++ b/assets/js/dashboard/nav-menu/top-bar.tsx
@@ -0,0 +1,51 @@
+/** @format */
+
+import React, { useRef } from 'react'
+import SiteSwitcher from '../site-switcher'
+import { useSiteContext } from '../site-context'
+import { useUserContext } from '../user-context'
+import CurrentVisitors from '../stats/current-visitors'
+import QueryPeriodPicker from '../datepicker'
+import Filters from '../filters'
+import classNames from 'classnames'
+import { useInView } from 'react-intersection-observer'
+
+interface TopBarProps {
+ showCurrentVisitors: boolean
+}
+
+export function TopBar({ showCurrentVisitors }: TopBarProps) {
+ const site = useSiteContext()
+ const user = useUserContext()
+ const tooltipBoundary = useRef(null)
+ const { ref, inView } = useInView({ threshold: 0 })
+
+ return (
+ <>
+ <div id="stats-container-top" ref={ref} />
+ <div
+ className={classNames(
+ 'relative top-0 sm:py-3 py-2 z-10',
+ !site.embedded &&
+ !inView &&
+ 'sticky fullwidth-shadow bg-gray-50 dark:bg-gray-850'
+ )}
+ >
+ <div className="items-center w-full flex">
+ <div className="flex items-center w-full" ref={tooltipBoundary}>
+ <SiteSwitcher
+ site={site}
+ loggedIn={user.loggedIn}
+ currentUserRole={user.role}
+ />
+ {showCurrentVisitors && (
+ <CurrentVisitors tooltipBoundary={tooltipBoundary.current} />
+ )}
+ <Filters />
+ </div>
+ <QueryPeriodPicker />
+ </div>
+ </div>
+ </>
+ )
+}
diff --git a/assets/js/dashboard/pinned-header-hoc.js b/assets/js/dashboard/pinned-header-hoc.js
deleted file mode 100644
index 062d4d93b3..0000000000
--- a/assets/js/dashboard/pinned-header-hoc.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import React from 'react';
-
-export const withPinnedHeader = (WrappedComponent, selector) => {
- return class extends React.Component {
- constructor(props) {
- super(props)
- this.state = {
- stuck: false
- }
- }
-
- componentDidMount() {
- if ('IntersectionObserver' in window) {
- this.attachObserver()
- }
- }
-
- attachObserver() {
- this.observer = new IntersectionObserver((entries) => {
- if (entries[0].intersectionRatio === 0)
- this.setState({ stuck: true });
- else if (entries[0].intersectionRatio === 1)
- this.setState({ stuck: false });
- }, {
- threshold: [0, 1]
- });
-
- this.el = document.querySelector(selector)
- this.observer.observe(this.el);
- }
-
- componentWillUnmount() {
- this.observer?.unobserve(this.el);
- }
-
- render() {
- return (
- <WrappedComponent stuck={this.state.stuck}{...this.props}/>
- );
- }
- }
-}
diff --git a/assets/js/dashboard/realtime.js b/assets/js/dashboard/realtime.js
deleted file mode 100644
index aade896ba2..0000000000
--- a/assets/js/dashboard/realtime.js
+++ /dev/null
@@ -1,57 +0,0 @@
-import React from 'react';
-import Datepicker from './datepicker'
-import SiteSwitcher from './site-switcher'
-import Filters from './filters'
-import VisitorGraph from './stats/graph/visitor-graph'
-import Sources from './stats/sources'
-import Pages from './stats/pages'
-import Locations from './stats/locations'
-import Devices from './stats/devices'
-import Behaviours from './stats/behaviours'
-import { withPinnedHeader } from './pinned-header-hoc';
-import { statsBoxClass } from './index';
-import { useSiteContext } from './site-context';
-import { useUserContext } from './user-context';
-import { useQueryContext } from './query-context';
-
-function Realtime({ stuck }) {
- const site = useSiteContext();
- const user = useUserContext();
- const { query } = useQueryContext();
- const navClass = site.embedded ? 'relative' : 'sticky'
-
- return (
- <div className="mb-12">
- <div id="stats-container-top"></div>
- <div className={`${navClass} top-0 sm:py-3 py-2 z-10 ${stuck && !site.embedded ? 'fullwidth-shadow bg-gray-50 dark:bg-gray-850' : ''}`}>
- <div className="items-center w-full flex">
- <div className="flex items-center w-full">
- <SiteSwitcher site={site} loggedIn={user.loggedIn} currentUserRole={user.role} />
- <Filters className="flex" />
- </div>
- <Datepicker />
- </div>
- </div>
- <VisitorGraph />
- <div className="w-full md:flex">
- <div className={statsBoxClass}>
- <Sources />
- </div>
- <div className={statsBoxClass}>
- <Pages />
- </div>
- </div>
- <div className="w-full md:flex">
- <div className={statsBoxClass}>
- <Locations site={site} query={query} />
- </div>
- <div className={statsBoxClass}>
- <Devices />
- </div>
- </div>
- <Behaviours />
- </div>
- )
-}
-
-export default withPinnedHeader(Realtime, '#stats-container-top');
diff --git a/assets/js/dashboard/stats/locations/index.js b/assets/js/dashboard/stats/locations/index.js
index b8ab6d1e75..6bb42f260f 100644
--- a/assets/js/dashboard/stats/locations/index.js
+++ b/assets/js/dashboard/stats/locations/index.js
@@ -10,6 +10,8 @@ import * as metrics from '../reports/metrics';
import { hasGoalFilter, getFiltersByKeyPrefix } from '../../util/filters';
import ImportedQueryUnsupportedWarning from '../imported-query-unsupported-warning';
import { citiesRoute, countriesRoute, regionsRoute } from '../../router';
+import { useQueryContext } from '../../query-context';
+import { useSiteContext } from '../../site-context';
function Countries({ query, site, onClick, afterFetchData }) {
function fetchData() {
@@ -134,7 +136,7 @@ const labelFor = {
'cities': 'Cities',
}
-export default class Locations extends React.Component {
+class Locations extends React.Component {
constructor(props) {
super(props)
this.onCountryFilter = this.onCountryFilter.bind(this)
@@ -249,3 +251,10 @@ export default class Locations extends React.Component {
)
}
}
+
+function LocationsWithContext() {
+ const { query } = useQueryContext();
+ const site = useSiteContext();
+ return <Locations site={site} query={query} />
+}
+export default LocationsWithContext
\ No newline at end of file
diff --git a/assets/test-utils/mock-api.ts b/assets/test-utils/mock-api.ts
new file mode 100644
index 0000000000..e287af2308
--- /dev/null
+++ b/assets/test-utils/mock-api.ts
@@ -0,0 +1,70 @@
+/** @format */
+
+export class MockAPI {
+ private mocked: Map<string, () => Promise<Response>>
+ private fetch: jest.Mock
+ private originalFetch: null | unknown = null
+
+ constructor() {
+ this.mocked = new Map()
+ this.fetch = jest.fn()
+ }
+
+ private setHandler(
+ method: string,
+ url: string,
+ handler: () => Promise<Response>
+ ) {
+ this.mocked.set([method.toLowerCase(), url].join(' '), handler)
+ }
+
+ public get(url: string, response: (() => Promise<Response>) | unknown) {
+ const handler =
+ typeof response === 'function'
+ ? (response as () => Promise<Response>)
+ : () =>
+ new Promise<Response>((resolve) =>
+ resolve({
+ status: 200,
+ ok: true,
+ json: async () => response
+ } as Response)
+ )
+ this.setHandler('get', url, handler)
+ return this
+ }
+
+ private getHandler(method: string, url: string) {
+ return this.mocked.get([method, url].join(' '))
+ }
+
+ public clear() {
+ this.mocked = new Map()
+ this.fetch.mockClear()
+ }
+
+ public start() {
+ this.originalFetch = global.fetch
+ const mockFetch: typeof global.fetch = async (input, init) => {
+ if (typeof input !== 'string') {
+ throw new Error(`Unmocked request ${input.toString()}`)
+ }
+ const method = init?.method ?? 'get'
+
+ const handler = this.getHandler(method, input)
+ if (!handler) {
+ throw new Error(
+ `Unmocked request ${method.toString()} ${input.toString()}`
+ )
+ }
+ return handler()
+ }
+
+ global.fetch = this.fetch.mockImplementation(mockFetch)
+ return this
+ }
+
+ public stop() {
+ global.fetch = this.originalFetch as typeof global.fetch
+ }
+}