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
Allow sorting breakdown lists by some metrics (#4513)
Artur Pata9fcb76d8e6fc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fa59728637..444b05231f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,7 @@ All notable changes to this project will be documented in this file.- Typescript support for `/assets`- Testing framework for `/assets`- Automatic HTTPS plausible/analytics#4491+- Make details views on dashboard sortable### Removed- Deprecate `ECTO_IPV6` and `ECTO_CH_IPV6` env vars in CE plausible/analytics#4245diff --git a/assets/js/dashboard/components/search-input.tsx b/assets/js/dashboard/components/search-input.tsxnew file mode 100644index 0000000000..8618a773a1--- /dev/null+++ b/assets/js/dashboard/components/search-input.tsx@@ -0,0 +1,53 @@+/** @format */++import React, { ChangeEventHandler, useCallback, useRef } from 'react'+import { isModifierPressed, Keybind } from '../keybinding'+import { useDebounce } from '../custom-hooks'+import classNames from 'classnames'++export const SearchInput = ({+ onSearch,+ className+}: {+ className?: string+ onSearch: (value: string) => void+}) => {+ const searchBoxRef = useRef<HTMLInputElement>(null)++ const onSearchInputChange: ChangeEventHandler<HTMLInputElement> = useCallback(+ (event) => {+ onSearch(event.target.value)+ },+ [onSearch]+ )+ const debouncedOnSearchInputChange = useDebounce(onSearchInputChange)++ const blurSearchBox = useCallback((event: KeyboardEvent) => {+ const searchBox = searchBoxRef.current+ if (searchBox?.contains(event.target as HTMLElement)) {+ searchBox.blur()+ event.stopPropagation()+ }+ }, [])++ return (+ <>+ <Keybind+ keyboardKey="Escape"+ type="keyup"+ handler={blurSearchBox}+ shouldIgnoreWhen={[isModifierPressed]}+ />+ <input+ ref={searchBoxRef}+ type="text"+ placeholder="Search"+ className={classNames(+ 'shadow-sm dark:bg-gray-900 dark:text-gray-100 focus:ring-indigo-500 focus:border-indigo-500 block sm:text-sm border-gray-300 dark:border-gray-500 rounded-md dark:bg-gray-800 w-48',+ className+ )}+ onChange={debouncedOnSearchInputChange}+ />+ </>+ )+}diff --git a/assets/js/dashboard/components/sort-button.tsx b/assets/js/dashboard/components/sort-button.tsxnew file mode 100644index 0000000000..94aedb5ba8--- /dev/null+++ b/assets/js/dashboard/components/sort-button.tsx@@ -0,0 +1,44 @@+/** @format */++import React, { ReactNode } from 'react'+import { cycleSortDirection, SortDirection } from '../hooks/use-order-by'+import classNames from 'classnames'++export const SortButton = ({+ children,+ toggleSort,+ sortDirection+}: {+ children: ReactNode+ toggleSort: () => void+ sortDirection: SortDirection | null+}) => {+ const next = cycleSortDirection(sortDirection)+ return (+ <button+ onClick={toggleSort}+ title={next.hint}+ className={classNames('group', 'hover:underline', 'relative')}+ >+ {children}+ <span+ className={classNames(+ 'absolute',+ 'rounded inline-block h-4 w-4',+ 'ml-1',+ {+ [SortDirection.asc]: 'rotate-180',+ [SortDirection.desc]: 'rotate-0'+ }[sortDirection ?? next.direction],+ !sortDirection && 'opacity-0',+ !sortDirection && 'group-hover:opacity-100',+ sortDirection &&+ 'group-hover:bg-gray-100 dark:group-hover:bg-gray-900',+ 'transition'+ )}+ >+ ↓+ </span>+ </button>+ )+}diff --git a/assets/js/dashboard/components/table.tsx b/assets/js/dashboard/components/table.tsxnew file mode 100644index 0000000000..3e6eeee376--- /dev/null+++ b/assets/js/dashboard/components/table.tsx@@ -0,0 +1,151 @@+/** @format */++import classNames from 'classnames'+import React, { ReactNode } from 'react'+import { SortDirection } from '../hooks/use-order-by'+import { SortButton } from './sort-button'++export type ColumnConfiguraton<T extends Record<string, unknown>> = {+ /** Unique column ID, used for sorting purposes and to get the value of the cell using rowItem[key] */+ key: keyof T+ /** Column title */+ label: ReactNode+ /** If defined, the column is considered sortable. @see SortButton */+ onSort?: () => void+ sortDirection?: SortDirection+ /** CSS class string. @example "w-24 md:w-32" */+ width: string+ /** Aligns column content. */+ align?: 'left' | 'right'+ /**+ * Function used to transform the value found at item[key] for the cell. Superseded by renderItem if present. @example 1120 => "1.1k"+ */+ renderValue?: (value: unknown) => ReactNode+ /** Function used to create richer cells */+ renderItem?: (item: T) => ReactNode+}++export const TableHeaderCell = ({+ children,+ className,+ align+}: {+ children: ReactNode+ className: string+ align?: 'left' | 'right'+}) => {+ return (+ <th+ className={classNames(+ 'p-2 text-xs font-bold text-gray-500 dark:text-gray-400 tracking-wide',+ className+ )}+ align={align}+ >+ {children}+ </th>+ )+}++export const TableCell = ({+ children,+ className,+ align+}: {+ children: ReactNode+ className: string+ align?: 'left' | 'right'+}) => {+ return (+ <td className={classNames('p-2 font-medium', className)} align={align}>+ {children}+ </td>+ )+}++export const ItemRow = <T extends Record<string, string | number | ReactNode>>({+ rowIndex,+ pageIndex,+ item,+ columns+}: {+ rowIndex: number+ pageIndex?: number+ item: T+ columns: ColumnConfiguraton<T>[]+}) => {+ return (+ <tr className="text-sm dark:text-gray-200">+ {columns.map(({ key, width, align, renderValue, renderItem }) => (+ <TableCell+ key={`${(pageIndex ?? null) === null ? '' : `page_${pageIndex}_`}row_${rowIndex}_${String(key)}`}+ className={width}+ align={align}+ >+ {renderItem+ ? renderItem(item)+ : renderValue+ ? renderValue(item[key])+ : (item[key] ?? '')}+ </TableCell>+ ))}+ </tr>+ )+}++export const Table = <T extends Record<string, string | number | ReactNode>>({+ data,+ columns+}: {+ columns: ColumnConfiguraton<T>[]+ data: T[] | { pages: T[][] }+}) => {+ return (+ <table className="w-max overflow-x-auto md:w-full table-striped table-fixed">+ <thead>+ <tr className="text-xs font-bold text-gray-500 dark:text-gray-400">+ {columns.map((column) => (+ <TableHeaderCell+ key={`header_${String(column.key)}`}+ className={classNames('p-2 tracking-wide', column.width)}+ align={column.align}+ >+ {column.onSort ? (+ <SortButton+ toggleSort={column.onSort}+ sortDirection={column.sortDirection ?? null}+ >+ {column.label}+ </SortButton>+ ) : (+ column.label+ )}+ </TableHeaderCell>+ ))}+ </tr>+ </thead>+ <tbody>+ {Array.isArray(data)+ ? data.map((item, rowIndex) => (+ <ItemRow+ item={item}+ columns={columns}+ rowIndex={rowIndex}+ key={rowIndex}+ />+ ))+ : data.pages.map((page, pageIndex) =>+ page.map((item, rowIndex) => (+ <ItemRow+ item={item}+ columns={columns}+ rowIndex={rowIndex}+ pageIndex={pageIndex}+ key={`page_${pageIndex}_row_${rowIndex}`}+ />+ ))+ )}+ </tbody>+ </table>+ )+}diff --git a/assets/js/dashboard/datepicker.tsx b/assets/js/dashboard/datepicker.tsxindex 829c0e24bc..dbed663dda 100644--- a/assets/js/dashboard/datepicker.tsx+++ b/assets/js/dashboard/datepicker.tsx@@ -9,7 +9,13 @@ import {import classNames from 'classnames'import { useQueryContext } from './query-context'import { useSiteContext } from './site-context'-import { Keybind, KeybindHint, NavigateKeybind } from './keybinding'+import {+ isModifierPressed,+ isTyping,+ Keybind,+ KeybindHint,+ NavigateKeybind+} from './keybinding'import {AppNavigationLink,useAppNavigate@@ -429,6 +435,7 @@ export default function QueryPeriodPicker() {keyboardKey={keyboardKey}type="keydown"handler={onClick || closeMenu}+ shouldIgnoreWhen={[isModifierPressed, isTyping]}/>) : (<NavigateKeybinddiff --git a/assets/js/dashboard/hooks/api-client.js b/assets/js/dashboard/hooks/api-client.jsdeleted file mode 100644index 903244e3a9..0000000000--- a/assets/js/dashboard/hooks/api-client.js+++ /dev/null@@ -1,83 +0,0 @@-import { useEffect } from "react"-import { useQueryClient, useInfiniteQuery } from "@tanstack/react-query"-import * as api from "../api"--const LIMIT = 100--/**- * A wrapper for the React Query library. Constructs the necessary options- * (including pagination config) to pass into the `useInfiniteQuery` hook.- *- * ### Required props- *- * @param {Array} key - The key under which the global "query" instance will live.- * Should be passed as a list of two elements - `[endpoint, { query }]`. The object- * can also contain additional values (such as `search`) to be used by:- * 1) React Query, to determine the uniqueness of the query instance- * 2) the `getRequestParams` function to build the request params.- *- * @param {Function} getRequestParams - A function that takes the `key` prop as an- * argument, and returns `[query, params]` which will be used by `queryFn` that- * actually calls the API.- *- * ### Optional props- *- * @param {Function} [afterFetchData] - A function to call after data has been fetched.- * Receives the API response as an argument.- *- * @param {Function} [afterFetchNextPage] - A function to call after the next page has- * been fetched. Receives the API response as an argument.- */--export function useAPIClient(props) {- const {key, getRequestParams, afterFetchData, afterFetchNextPage} = props- const [endpoint] = key- const queryClient = useQueryClient()-- const queryFn = async ({ pageParam, queryKey }) => {- const [query, params] = getRequestParams(queryKey)- params.limit = LIMIT- params.page = pageParam-- const response = await api.get(endpoint, query, params)-- if (pageParam === 1 && typeof afterFetchData === 'function') {- afterFetchData(response)- }-- if (pageParam > 1 && typeof afterFetchNextPage === 'function') {- afterFetchNextPage(response)- }-- return response.results- }-- // During the cleanup phase, make sure only the first page of results- // is cached under any `queryKey` containing this endpoint.- useEffect(() => {- const key = [endpoint]- return () => {- queryClient.setQueriesData(key, (data) => {- if (data?.pages?.length) {- return {- pages: data.pages.slice(0, 1),- pageParams: data.pageParams.slice(0, 1),- }- }- })- }- }, [queryClient, endpoint])-- const getNextPageParam = (lastPageResults, _, lastPageIndex) => {- return lastPageResults.length === LIMIT ? lastPageIndex + 1 : null- }- const defaultInitialPageParam = 1- const initialPageParam = props.initialPageParam === undefined ? defaultInitialPageParam : props.initialPageParam-- return useInfiniteQuery({- queryKey: key,- queryFn,- getNextPageParam,- initialPageParam- })-}\ No newline at end of filediff --git a/assets/js/dashboard/hooks/api-client.ts b/assets/js/dashboard/hooks/api-client.tsnew file mode 100644index 0000000000..b4472fa5ca--- /dev/null+++ b/assets/js/dashboard/hooks/api-client.ts@@ -0,0 +1,102 @@+/** @format */++import { useEffect } from 'react'+import {+ useQueryClient,+ useInfiniteQuery,+ QueryFilters+} from '@tanstack/react-query'+import * as api from '../api'+import { DashboardQuery } from '../query'++const LIMIT = 100++/** full endpoint URL */+type Endpoint = string++type PaginatedQueryKeyBase = [Endpoint, { query: DashboardQuery }]++type GetRequestParams<TKey extends PaginatedQueryKeyBase> = (+ k: TKey+) => [Record<string, unknown>, Record<string, unknown>]++/**+ * Hook that fetches the first page from the defined GET endpoint on mount,+ * then subsequent pages when component calls fetchNextPage.+ * Stores fetched pages locally, but only the first page of the results.+ */+export function usePaginatedGetAPI<+ TResponse extends { results: unknown[] },+ TKey extends PaginatedQueryKeyBase = PaginatedQueryKeyBase+>({+ key,+ getRequestParams,+ afterFetchData,+ afterFetchNextPage,+ initialPageParam = 1+}: {+ key: TKey+ getRequestParams: GetRequestParams<TKey>+ afterFetchData?: (response: TResponse) => void+ afterFetchNextPage?: (response: TResponse) => void+ initialPageParam?: number+}) {+ const [endpoint] = key+ const queryClient = useQueryClient()++ useEffect(() => {+ const onDismountCleanToPageOne = () => {+ const queryKeyToClean = [endpoint] as QueryFilters+ queryClient.setQueriesData(queryKeyToClean, cleanToPageOne)+ }+ return onDismountCleanToPageOne+ }, [queryClient, endpoint])++ return useInfiniteQuery({+ queryKey: key,+ queryFn: async ({ pageParam, queryKey }): Promise<TResponse['results']> => {+ const [query, params] = getRequestParams(queryKey)++ const response: TResponse = await api.get(endpoint, query, {+ ...params,+ limit: LIMIT,+ page: pageParam+ })++ if (+ pageParam === initialPageParam &&+ typeof afterFetchData === 'function'+ ) {+ afterFetchData(response)+ }++ if (+ pageParam > initialPageParam &&+ typeof afterFetchNextPage === 'function'+ ) {+ afterFetchNextPage(response)+ }++ return response.results+ },+ getNextPageParam: (lastPageResults, _, lastPageIndex) => {+ return lastPageResults.length === LIMIT ? lastPageIndex + 1 : null+ },+ initialPageParam,+ placeholderData: (previousData) => previousData+ })+}++export const cleanToPageOne = <+ T extends { pages: unknown[]; pageParams: unknown[] }+>(+ data?: T+) => {+ if (data?.pages?.length) {+ return {+ pages: data.pages.slice(0, 1),+ pageParams: data.pageParams.slice(0, 1)+ }+ }+ return data+}diff --git a/assets/js/dashboard/hooks/use-order-by.test.ts b/assets/js/dashboard/hooks/use-order-by.test.tsnew file mode 100644index 0000000000..71ba2f5743--- /dev/null+++ b/assets/js/dashboard/hooks/use-order-by.test.ts@@ -0,0 +1,165 @@+/** @format */++import { Metric } from '../stats/reports/metrics'+import {+ OrderBy,+ SortDirection,+ cycleSortDirection,+ findOrderIndex,+ getOrderByStorageKey,+ getStoredOrderBy,+ maybeStoreOrderBy,+ rearrangeOrderBy,+ validateOrderBy+} from './use-order-by'++describe(`${findOrderIndex.name}`, () => {+ /* prettier-ignore */+ const cases: [OrderBy, Pick<Metric, 'key'>, number][] = [+ [[], { key: 'anything' }, -1],+ [[['visitors', SortDirection.asc]], { key: 'anything' }, -1],+ [[['bounce_rate', SortDirection.desc], ['visitors', SortDirection.asc]], {key: 'bounce_rate'}, 0],+ [[['bounce_rate', SortDirection.desc], ['visitors', SortDirection.asc]], {key: 'visitors'}, 1]+ ]++ test.each(cases)(+ `[%#] in order by %p, the index of metric %p is %p`,+ (orderBy, metric, expectedIndex) => {+ expect(findOrderIndex(orderBy, metric)).toEqual(expectedIndex)+ }+ )+})++describe(`${cycleSortDirection.name}`, () => {+ test.each([+ [+ null,+ {+ direction: SortDirection.desc,+ hint: 'Press to sort column in descending order'+ }+ ],+ [+ SortDirection.desc,+ {+ direction: SortDirection.asc,+ hint: 'Press to sort column in ascending order'+ }+ ],+ [+ SortDirection.asc,+ {+ direction: SortDirection.desc,+ hint: 'Press to sort column in descending order'+ }+ ]+ ])(+ 'for current direction %p returns %p',+ (currentDirection, expectedOutput) => {+ expect(cycleSortDirection(currentDirection)).toEqual(expectedOutput)+ }+ )+})++describe(`${rearrangeOrderBy.name}`, () => {+ const cases: [Pick<Metric, 'key'>, OrderBy, OrderBy][] = [+ [+ { key: 'visitors' },+ [['visitors', SortDirection.asc]],+ [['visitors', SortDirection.desc]]+ ],+ [+ { key: 'visitors' },+ [['visitors', SortDirection.desc]],+ [['visitors', SortDirection.asc]]+ ],+ [+ { key: 'visit_duration' },+ [['visitors', SortDirection.asc]],+ [['visit_duration', SortDirection.desc]]+ ]+ ]+ it.each(cases)(+ `[%#] clicking on %p yields expected order`,+ (metric, currentOrderBy, expectedOrderBy) => {+ expect(rearrangeOrderBy(currentOrderBy, metric)).toEqual(expectedOrderBy)+ }+ )+})++describe(`${validateOrderBy.name}`, () => {+ test.each([+ [false, '', []],+ [false, [], []],+ [false, [['a']], [{ key: 'a' }]],+ [false, [['a', 'b']], [{ key: 'a' }]],+ [+ false,+ [+ ['a', 'desc'],+ ['a', 'asc']+ ],+ [{ key: 'a' }]+ ],+ [true, [['a', 'desc']], [{ key: 'a' }]]+ ])(+ '[%#] returns %p given input %p and sortable metrics %p',+ (expected, input, sortableMetrics) => {+ expect(validateOrderBy(input, sortableMetrics)).toBe(expected)+ }+ )+})++describe(`storing detailed report preferred order`, () => {+ const domain = 'any-domain'+ const reportInfo = { dimensionLabel: 'Goal' }++ it('does not store invalid value', () => {+ maybeStoreOrderBy({+ orderBy: [['foo', SortDirection.desc]],+ domain,+ reportInfo,+ metrics: [{ key: 'foo', sortable: false }]+ })+ expect(localStorage.getItem(getOrderByStorageKey(domain, reportInfo))).toBe(+ null+ )+ })++ it('falls back to fallbackValue if metric has become unsortable between storing and retrieving', () => {+ maybeStoreOrderBy({+ orderBy: [['c', SortDirection.desc]],+ domain,+ reportInfo,+ metrics: [{ key: 'c', sortable: true }]+ })+ const inStorage = localStorage.getItem(+ getOrderByStorageKey(domain, reportInfo)+ )+ expect(inStorage).toBe('[["c","desc"]]')+ expect(+ getStoredOrderBy({+ domain,+ reportInfo,+ metrics: [{ key: 'c', sortable: false }],+ fallbackValue: [['visitors', SortDirection.desc]]+ })+ ).toEqual([['visitors', SortDirection.desc]])+ })++ it('retrieves stored value correctly', () => {+ const input = [['any-column', SortDirection.asc]]+ localStorage.setItem(+ getOrderByStorageKey(domain, reportInfo),+ JSON.stringify(input)+ )+ expect(+ getStoredOrderBy({+ domain,+ reportInfo,+ metrics: [{ key: 'any-column', sortable: true }],+ fallbackValue: [['visitors', SortDirection.desc]]+ })+ ).toEqual(input)+ })+})diff --git a/assets/js/dashboard/hooks/use-order-by.ts b/assets/js/dashboard/hooks/use-order-by.tsnew file mode 100644index 0000000000..d9c2773b56--- /dev/null+++ b/assets/js/dashboard/hooks/use-order-by.ts@@ -0,0 +1,202 @@+/** @format */++import { useCallback, useEffect, useMemo, useState } from 'react'+import { Metric } from '../stats/reports/metrics'+import { getDomainScopedStorageKey, getItem, setItem } from '../util/storage'+import { useSiteContext } from '../site-context'+import { ReportInfo } from '../stats/modals/breakdown-modal'++export enum SortDirection {+ asc = 'asc',+ desc = 'desc'+}++export type Order = [Metric['key'], SortDirection]++export type OrderBy = Order[]++export const getSortDirectionLabel = (sortDirection: SortDirection): string =>+ ({+ [SortDirection.asc]: 'Sorted in ascending order',+ [SortDirection.desc]: 'Sorted in descending order'+ })[sortDirection]++export function useOrderBy({+ metrics,+ defaultOrderBy+}: {+ metrics: Pick<Metric, 'key'>[]+ defaultOrderBy: OrderBy+}) {+ const [orderBy, setOrderBy] = useState<OrderBy>([])+ const orderByDictionary: Record<Metric['key'], SortDirection> = useMemo(+ () =>+ orderBy.length+ ? Object.fromEntries(orderBy)+ : Object.fromEntries(defaultOrderBy),+ [orderBy, defaultOrderBy]+ )++ const toggleSortByMetric = useCallback(+ (metric: Pick<Metric, 'key'>) => {+ if (!metrics.find(({ key }) => key === metric.key)) {+ return+ }+ setOrderBy((currentOrderBy) =>+ rearrangeOrderBy(+ currentOrderBy.length ? currentOrderBy : defaultOrderBy,+ metric+ )+ )+ },+ [metrics, defaultOrderBy]+ )++ return {+ orderBy: orderBy.length ? orderBy : defaultOrderBy,+ orderByDictionary,+ toggleSortByMetric+ }+}++export function cycleSortDirection(+ currentSortDirection: SortDirection | null+): { direction: SortDirection; hint: string } {+ if (currentSortDirection === SortDirection.desc) {+ return {+ direction: SortDirection.asc,+ hint: 'Press to sort column in ascending order'+ }+ }++ return {+ direction: SortDirection.desc,+ hint: 'Press to sort column in descending order'+ }+}++export function findOrderIndex(orderBy: OrderBy, metric: Pick<Metric, 'key'>) {+ return orderBy.findIndex(([metricKey]) => metricKey === metric.key)+}++export function rearrangeOrderBy(+ currentOrderBy: OrderBy,+ metric: Pick<Metric, 'key'>+): OrderBy {+ const orderIndex = findOrderIndex(currentOrderBy, metric)+ if (orderIndex < 0) {+ const sortDirection = cycleSortDirection(null).direction as SortDirection+ return [[metric.key, sortDirection]]+ }+ const previousOrder = currentOrderBy[orderIndex]+ const sortDirection = cycleSortDirection(previousOrder[1]).direction+ if (sortDirection === null) {+ return []+ }+ return [[metric.key, sortDirection]]+}++export function getOrderByStorageKey(+ domain: string,+ reportInfo: Pick<ReportInfo, 'dimensionLabel'>+) {+ const storageKey = getDomainScopedStorageKey(+ `order_${reportInfo.dimensionLabel}_by`,+ domain+ )+ return storageKey+}++export function validateOrderBy(+ orderBy: unknown,+ metrics: Pick<Metric, 'key'>[]+): orderBy is OrderBy {+ if (!Array.isArray(orderBy)) {+ return false+ }+ if (orderBy.length !== 1) {+ return false+ }+ if (!Array.isArray(orderBy[0])) {+ return false+ }+ if (+ orderBy[0].length === 2 &&+ metrics.findIndex((m) => m.key === orderBy[0][0]) > -1 &&+ [SortDirection.asc, SortDirection.desc].includes(orderBy[0][1])+ ) {+ return true+ }+ return false+}++export function getStoredOrderBy({+ domain,+ reportInfo,+ metrics,+ fallbackValue+}: {+ domain: string+ reportInfo: Pick<ReportInfo, 'dimensionLabel'>+ metrics: Pick<Metric, 'key' | 'sortable'>[]+ fallbackValue: OrderBy+}): OrderBy {+ try {+ const storedItem = getItem(getOrderByStorageKey(domain, reportInfo))+ const parsed = JSON.parse(storedItem)+ if (+ validateOrderBy(+ parsed,+ metrics.filter((m) => m.sortable)+ )+ ) {+ return parsed+ } else {+ throw new Error('Invalid stored order_by value')+ }+ } catch (_e) {+ return fallbackValue+ }+}++export function maybeStoreOrderBy({+ domain,+ reportInfo,+ metrics,+ orderBy+}: {+ domain: string+ reportInfo: Pick<ReportInfo, 'dimensionLabel'>+ metrics: Pick<Metric, 'key' | 'sortable'>[]+ orderBy: OrderBy+}) {+ if (+ validateOrderBy(+ orderBy,+ metrics.filter((m) => m.sortable)+ )+ ) {+ setItem(getOrderByStorageKey(domain, reportInfo), JSON.stringify(orderBy))+ }+}++export function useRememberOrderBy({+ effectiveOrderBy,+ metrics,+ reportInfo+}: {+ effectiveOrderBy: OrderBy+ metrics: Pick<Metric, 'key' | 'sortable'>[]+ reportInfo: Pick<ReportInfo, 'dimensionLabel'>+}) {+ const site = useSiteContext()++ useEffect(() => {+ maybeStoreOrderBy({+ domain: site.domain,+ metrics,+ reportInfo,+ orderBy: effectiveOrderBy+ })+ }, [site, reportInfo, effectiveOrderBy, metrics])+}diff --git a/assets/js/dashboard/keybinding.tsx b/assets/js/dashboard/keybinding.tsxindex d05a1f892c..cf3caa138f 100644--- a/assets/js/dashboard/keybinding.tsx+++ b/assets/js/dashboard/keybinding.tsx@@ -20,29 +20,39 @@ import {* @return {boolean} Whether the event should be ignored or not.**/-export function shouldIgnoreKeypress(event: KeyboardEvent) {++export const isModifierPressed = (event: KeyboardEvent): boolean =>+ event.ctrlKey || event.metaKey || event.altKey || event.keyCode == 229++export const isTyping = (event: KeyboardEvent): boolean => {const targetElement = event.target as Element | undefined- const modifierPressed =- event.ctrlKey || event.metaKey || event.altKey || event.keyCode == 229- const isTyping =+ return (event.isComposing ||targetElement?.tagName == 'INPUT' ||targetElement?.tagName == 'TEXTAREA'-- return modifierPressed || isTyping+ )}-/**- * Returns whether the given keybinding has been pressed and should be- * processed. Events can be ignored based on `shouldIgnoreKeypress(event)`.- *- * @param {string} keyboardKey - The target key to checked, e.g. `"i"`.- * @return {boolean} Whether the event should be processed or not.- *- */-export function isKeyPressed(event: KeyboardEvent, keyboardKey: string) {- const keyPressed = event.key.toLowerCase() == keyboardKey.toLowerCase()- return keyPressed && !shouldIgnoreKeypress(event)+export function isKeyPressed(+ event: KeyboardEvent,+ {+ keyboardKey,+ shouldIgnoreWhen+ }: {+ keyboardKey: string+ shouldIgnoreWhen?: Array<(event: KeyboardEvent) => boolean>+ }+): boolean {+ if (event.key.toLowerCase() !== keyboardKey.toLowerCase()) {+ return false+ }+ if (+ shouldIgnoreWhen?.length &&+ shouldIgnoreWhen.some((shouldIgnore) => shouldIgnore(event))+ ) {+ return false+ }+ return true}type KeyboardEventType = keyof Pick<@@ -53,19 +63,21 @@ type KeyboardEventType = keyof Pick<export function Keybind({keyboardKey,type,- handler+ handler,+ shouldIgnoreWhen = []}: {keyboardKey: stringtype: KeyboardEventType- handler: () => void+ handler: (event: KeyboardEvent) => void+ shouldIgnoreWhen?: Array<(event: KeyboardEvent) => boolean>}) {const wrappedHandler = useCallback((event: KeyboardEvent) => {- if (isKeyPressed(event, keyboardKey)) {- handler()+ if (isKeyPressed(event, { keyboardKey, shouldIgnoreWhen })) {+ handler(event)}},- [keyboardKey, handler]+ [keyboardKey, handler, shouldIgnoreWhen])useEffect(() => {@@ -89,7 +101,7 @@ export function NavigateKeybind({navigateProps}: {keyboardKey: string- type: 'keyup' | 'keydown' | 'keypress'+ type: KeyboardEventTypenavigateProps: AppNavigationTarget}) {const navigate = useAppNavigate()@@ -97,7 +109,14 @@ export function NavigateKeybind({navigate({ ...navigateProps })}, [navigateProps, navigate])- return <Keybind keyboardKey={keyboardKey} type={type} handler={handler} />+ return (+ <Keybind+ keyboardKey={keyboardKey}+ type={type}+ handler={handler}+ shouldIgnoreWhen={[isModifierPressed, isTyping]}+ />+ )}export function KeybindHint({ children }: { children: ReactNode }) {diff --git a/assets/js/dashboard/stats/graph/interval-picker.js b/assets/js/dashboard/stats/graph/interval-picker.jsindex bce3dfa3b5..1da51c4711 100644--- a/assets/js/dashboard/stats/graph/interval-picker.js+++ b/assets/js/dashboard/stats/graph/interval-picker.js@@ -3,7 +3,7 @@ import { Menu, Transition } from '@headlessui/react';import { ChevronDownIcon } from '@heroicons/react/20/solid';import classNames from 'classnames';import * as storage from '../../util/storage';-import { isKeyPressed } from '../../keybinding';+import { isKeyPressed, isModifierPressed, isTyping } from '../../keybinding';import { useQueryContext } from '../../query-context';import { useSiteContext } from '../../site-context';@@ -73,7 +73,7 @@ function storeInterval(period, domain, interval) {function useIKeybinding(ref) {const handleKeyPress = useCallback((event) => {- if (isKeyPressed(event, "i")) {+ if (isKeyPressed(event, { keyboardKey: "i", shouldIgnoreWhen: [isTyping, isModifierPressed] })) {ref.current?.click()}}, [ref])diff --git a/assets/js/dashboard/stats/locations/map.tsx b/assets/js/dashboard/stats/locations/map.tsxindex ba1df544cb..76e80baac4 100644--- a/assets/js/dashboard/stats/locations/map.tsx+++ b/assets/js/dashboard/stats/locations/map.tsx@@ -40,8 +40,7 @@ const WorldMap = ({const navigate = useAppNavigate()const { mode } = useTheme()const site = useSiteContext()- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const { query } = useQueryContext() as { query: any }+ const { query } = useQueryContext()const svgRef = useRef<SVGSVGElement | null>(null)const [tooltip, setTooltip] = useState<{x: numberdiff --git a/assets/js/dashboard/stats/modals/breakdown-modal.js b/assets/js/dashboard/stats/modals/breakdown-modal.jsdeleted file mode 100644index 91bdac3bda..0000000000--- a/assets/js/dashboard/stats/modals/breakdown-modal.js+++ /dev/null@@ -1,272 +0,0 @@-import React, { useState, useEffect, useRef } from "react";--import { FilterLink } from "../reports/list";-import { useQueryContext } from "../../query-context";-import { useDebounce } from "../../custom-hooks";-import { useAPIClient } from "../../hooks/api-client";-import { rootRoute } from "../../router";--export const MIN_HEIGHT_PX = 500--// The main function component for rendering the "Details" reports on the dashboard,-// i.e. a breakdown by a single (non-time) dimension, with a given set of metrics.--// BreakdownModal is expected to be rendered inside a `<Modal>`, which has it's own-// specific URL pathname (e.g. /plausible.io/sources). During the lifecycle of a-// BreakdownModal, the `query` object is not expected to change.--// ### Search As You Type--// Debounces API requests when a search input changes and applies a `contains` filter-// on the given breakdown dimension (see the required `addSearchFilter` prop)--// ### Filter Links--// Dimension values can act as links back to the dashboard, where that specific value-// will be filtered by. (see the `getFilterInfo` required prop)--// ### Pagination--// By default, the component fetches `LIMIT` results. When exactly this number of-// results is received, a "Load More" button is rendered for fetching the next page-// of results.--// ### Required Props--// * `reportInfo` - a map with the following required keys:--// * `title` - the title of the report to render on the top left--// * `endpoint` - the full pathname of the API endpoint to query. E.g.-// `api/stats/plausible.io/sources`--// * `dimensionLabel` - a string to render as the dimension column header.--// * `metrics` - a list of `Metric` class objects which represent the columns-// rendered in the report--// * `getFilterInfo` - a function that takes a `listItem` and returns a map with-// the necessary information to be able to link to a dashboard where that item-// is filtered by. If a list item is not supposed to be a filter link, this-// function should return `null` for that item.--// ### Optional Props--// * `renderIcon` - a function that renders an icon for the given list item.--// * `getExternalLinkURL` - a function that takes a list litem, and returns a-// valid link href for this item. If the item is not supposed to be a link,-// the function should return `null` for that item. Otherwise, if the returned-// value exists, a small pop-out icon will be rendered whenever the list item-// is hovered. When the icon is clicked, opens the external link in a new tab.--// * `searchEnabled` - a boolean that determines if the search feature is enabled.-// When true, the `addSearchFilter` function is expected. Is true by default.--// * `addSearchFilter` - a function that takes a query object and a search string-// as arguments, and returns a new `query` with an additional search filter.--// * `afterFetchData` - a callback function taking an API response as an argument.-// If this function is passed via props, it will be called after a successful-// API response from the `fetchData` function.--// * `afterFetchNextPage` - a function with the same behaviour as `afterFetchData`,-// but will be called after a successful next page load in `fetchNextPage`.-export default function BreakdownModal({- reportInfo,- metrics,- renderIcon,- getExternalLinkURL,- searchEnabled = true,- afterFetchData,- afterFetchNextPage,- addSearchFilter,- getFilterInfo-}) {- const searchBoxRef = useRef(null)- const { query } = useQueryContext();-- const [search, setSearch] = useState('')-- const {- data,- hasNextPage,- fetchNextPage,- isFetchingNextPage,- isFetching,- isPending- } = useAPIClient({- key: [reportInfo.endpoint, {query, search}],- getRequestParams: (key) => {- const [_endpoint, {query, search}] = key-- let queryWithSearchFilter = {...query}-- if (searchEnabled && search !== '') {- queryWithSearchFilter = addSearchFilter(query, search)- }-- return [queryWithSearchFilter, {detailed: true}]- },- afterFetchData,- afterFetchNextPage- })--- useEffect(() => {- if (!searchEnabled) { return }-- const searchBox = searchBoxRef.current-- const handleKeyUp = (event) => {- if (event.key === 'Escape') {- event.target.blur()- event.stopPropagation()- }- }-- searchBox.addEventListener('keyup', handleKeyUp);-- return () => {- searchBox.removeEventListener('keyup', handleKeyUp);- }- }, [searchEnabled])-- function maybeRenderIcon(item) {- if (typeof renderIcon === 'function') {- return renderIcon(item)- }- }-- function maybeRenderExternalLink(item) {- if (typeof getExternalLinkURL === 'function') {- const linkUrl = getExternalLinkURL(item)-- if (!linkUrl) { return null }-- return (- <a target="_blank" href={linkUrl} rel="noreferrer" className="hidden group-hover:block">- <svg className="inline h-4 w-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>- </a>- )- }- }-- function renderRow(item) {- return (- <tr className="text-sm dark:text-gray-200" key={item.name}>- <td className="w-48 md:w-80 break-all p-2 flex items-center">- {maybeRenderIcon(item)}- <FilterLink- path={rootRoute.path}- filterInfo={getFilterInfo(item)}- >- {item.name}- </FilterLink>- {maybeRenderExternalLink(item)}- </td>- {metrics.map((metric) => {- return (- <td key={metric.key} className="p-2 w-24 font-medium" align="right">- {metric.renderValue(item[metric.key])}- </td>- )- })}- </tr>- )- }-- function renderInitialLoadingSpinner() {- return (- <div className="w-full h-full flex flex-col justify-center" style={{ minHeight: `${MIN_HEIGHT_PX}px` }}>- <div className="mx-auto loading"><div></div></div>- </div>- )- }-- function renderSmallLoadingSpinner() {- return (- <div className="loading sm"><div></div></div>- )- }-- function renderLoadMoreButton() {- if (isPending) return null- if (!isFetching && !hasNextPage) return null-- return (- <div className="flex flex-col w-full my-4 items-center justify-center h-10">- {!isFetching && <button onClick={fetchNextPage} type="button" className="button">Load more</button>}- {isFetchingNextPage && renderSmallLoadingSpinner()}- </div>- )- }-- function handleInputChange(e) {- setSearch(e.target.value)- }-- const debouncedHandleInputChange = useDebounce(handleInputChange)-- function renderSearchInput() {- return (- <input- ref={searchBoxRef}- type="text"- placeholder="Search"- className="shadow-sm dark:bg-gray-900 dark:text-gray-100 focus:ring-indigo-500 focus:border-indigo-500 block sm:text-sm border-gray-300 dark:border-gray-500 rounded-md dark:bg-gray-800 w-48"- onChange={debouncedHandleInputChange}- />- )- }-- function renderModalBody() {- if (data?.pages?.length) {- return (- <main className="modal__content">- <table className="w-max overflow-x-auto md:w-full table-striped table-fixed">- <thead>- <tr>- <th- className="p-2 w-48 md:w-80 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400"- align="left"- >- {reportInfo.dimensionLabel}- </th>-- {metrics.map((metric) => {- return (- <th key={metric.key} className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">- {metric.renderLabel(query)}- </th>- )- })}- </tr>- </thead>- <tbody>- {data.pages.map((p) => p.map(renderRow))}- </tbody>- </table>- </main>- )- }- }-- return (- <div className="w-full h-full">- <div className="flex justify-between items-center">- <div className="flex items-center gap-x-2">- <h1 className="text-xl font-bold dark:text-gray-100">{reportInfo.title}</h1>- {!isPending && isFetching && renderSmallLoadingSpinner()}- </div>- {searchEnabled && renderSearchInput()}- </div>- <div className="my-4 border-b border-gray-300"></div>- <div style={{ minHeight: `${MIN_HEIGHT_PX}px` }}>- {isPending && renderInitialLoadingSpinner()}- {!isPending && renderModalBody()}- {renderLoadMoreButton()}- </div>- </div>- )-}diff --git a/assets/js/dashboard/stats/modals/breakdown-modal.tsx b/assets/js/dashboard/stats/modals/breakdown-modal.tsxnew file mode 100644index 0000000000..24b686a2f7--- /dev/null+++ b/assets/js/dashboard/stats/modals/breakdown-modal.tsx@@ -0,0 +1,230 @@+/** @format */++import React, { useState, ReactNode, useMemo } from 'react'++import { FilterLink } from '../reports/list'+import { useQueryContext } from '../../query-context'+import { usePaginatedGetAPI } from '../../hooks/api-client'+import { rootRoute } from '../../router'+import {+ getStoredOrderBy,+ Order,+ OrderBy,+ useOrderBy,+ useRememberOrderBy+} from '../../hooks/use-order-by'+import { Metric } from '../reports/metrics'+import { DashboardQuery } from '../../query'+import { ColumnConfiguraton } from '../../components/table'+import { BreakdownTable } from './breakdown-table'+import { useSiteContext } from '../../site-context'++export type ReportInfo = {+ /** Title of the report to render on the top left. */+ title: string+ /** Full pathname of the API endpoint to query. @example `/api/stats/plausible.io/sources` */+ endpoint: string+ /** Used as the leftmost column header. */+ dimensionLabel: string+ /** What this report will be initially sorted by. @example ["visitors", "desc"] */+ defaultOrder?: Order+}++/**+ BreakdownModal is for rendering the "Details" reports on the dashboard,+ i.e. a breakdown by a single (non-time) dimension, with a given set of metrics.++ BreakdownModal is expected to be rendered inside a `<Modal>`, which has it's own+ specific URL pathname (e.g. /plausible.io/sources). During the lifecycle of a+ BreakdownModal, the `query` object is not expected to change.++ ### Search As You Type+ @see BreakdownTable++ ### Filter Links+ @see NameCell++ ### Pagination+ @see usePaginatedGetAPI++*/+export default function BreakdownModal<TListItem extends { name: string }>({+ reportInfo,+ metrics,+ renderIcon,+ getExternalLinkURL,+ searchEnabled = true,+ afterFetchData,+ afterFetchNextPage,+ addSearchFilter,+ getFilterInfo+}: {+ /** Dimension and title of the breakdown. */+ reportInfo: ReportInfo+ /** Columns to show in the table. */+ metrics: Metric[]+ /** Function to make the cells in the first column drill down the dashboard. @see NameCell */+ getFilterInfo: (listItem: TListItem) => unknown | null+ /** Function to make the cells in the first column richer. @see NameCell */+ renderIcon?: (listItem: TListItem) => ReactNode+ /** Function to make the cells more interactive. @see NameCell */+ getExternalLinkURL?: (listItem: TListItem) => string+ /** Callback to allow parent to update itself, called with the API response for the first page. */+ afterFetchData?: (response: { results: TListItem[] }) => void+ /** Callback to allow parent to update itself, called with the API response of subsequent pages. */+ afterFetchNextPage?: (response: { results: TListItem[] }) => void+ /** Function that must return a new query that contains appropriate search filter for searchValue param. */+ addSearchFilter?: (q: DashboardQuery, searchValue: string) => DashboardQuery+ searchEnabled?: boolean+}) {+ const site = useSiteContext()+ const { query } = useQueryContext()++ const [search, setSearch] = useState('')+ const defaultOrderBy = getStoredOrderBy({+ domain: site.domain,+ reportInfo,+ metrics,+ fallbackValue: reportInfo.defaultOrder ? [reportInfo.defaultOrder] : []+ })+ const { orderBy, orderByDictionary, toggleSortByMetric } = useOrderBy({+ metrics,+ defaultOrderBy+ })+ useRememberOrderBy({+ effectiveOrderBy: orderBy,+ metrics,+ reportInfo+ })+ const apiState = usePaginatedGetAPI<+ { results: Array<TListItem> },+ [string, { query: DashboardQuery; search: string; orderBy: OrderBy }]+ >({+ key: [reportInfo.endpoint, { query, search, orderBy }],+ getRequestParams: (key) => {+ const [_endpoint, { query, search }] = key++ let queryWithSearchFilter = { ...query }++ if (+ searchEnabled &&+ typeof addSearchFilter === 'function' &&+ search !== ''+ ) {+ queryWithSearchFilter = addSearchFilter(query, search)+ }++ return [+ queryWithSearchFilter,+ {+ detailed: true,+ order_by: JSON.stringify(orderBy)+ }+ ]+ },+ afterFetchData,+ afterFetchNextPage+ })++ const columns: ColumnConfiguraton<TListItem>[] = useMemo(+ () => [+ {+ label: reportInfo.dimensionLabel,+ key: 'name',+ width: 'w-48 md:w-80 flex items-center break-all',+ align: 'left',+ renderItem: (item) => (+ <NameCell+ item={item}+ getFilterInfo={getFilterInfo}+ getExternalLinkURL={getExternalLinkURL}+ renderIcon={renderIcon}+ />+ )+ },+ ...metrics.map(+ (m): ColumnConfiguraton<TListItem> => ({+ label: m.renderLabel(query),+ key: m.key,+ width: m.width,+ align: 'right',+ renderValue: m.renderValue,+ onSort: m.sortable ? () => toggleSortByMetric(m) : undefined,+ sortDirection: orderByDictionary[m.key]+ })+ )+ ],+ [+ reportInfo.dimensionLabel,+ metrics,+ getFilterInfo,+ query,+ orderByDictionary,+ toggleSortByMetric,+ renderIcon,+ getExternalLinkURL+ ]+ )++ return (+ <BreakdownTable<TListItem>+ title={reportInfo.title}+ {...apiState}+ onSearch={setSearch}+ columns={columns}+ />+ )+}++/**+ * Most interactive cell in the breakdown table.+ * May have an icon.+ * If `getFilterInfo(item)` does not return null,+ * drills down the dashboard to that particular item.+ * May have a tiny icon button to navigate to the actual resource.+ * */+const NameCell = <TListItem extends { name: string }>({+ item,+ getFilterInfo,+ renderIcon,+ getExternalLinkURL+}: {+ item: TListItem+ getFilterInfo: (item: TListItem) => unknown | null+ renderIcon?: (item: TListItem) => unknown+ getExternalLinkURL?: (listItem: TListItem) => string+}) => (+ <>+ {typeof renderIcon === 'function' && renderIcon(item)}+ <FilterLink+ path={rootRoute.path}+ filterInfo={getFilterInfo(item)}+ onClick={undefined}+ extraClass={undefined}+ >+ {item.name}+ </FilterLink>+ {typeof getExternalLinkURL === 'function' && (+ <ExternalLinkIcon url={getExternalLinkURL(item)} />+ )}+ </>+)++const ExternalLinkIcon = ({ url }: { url?: string }) =>+ url ? (+ <a+ target="_blank"+ href={url}+ rel="noreferrer"+ className="hidden group-hover:block"+ >+ <svg+ className="inline h-4 w-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400"+ fill="currentColor"+ viewBox="0 0 20 20"+ >+ <path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path>+ <path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path>+ </svg>+ </a>+ ) : nulldiff --git a/assets/js/dashboard/stats/modals/breakdown-table.tsx b/assets/js/dashboard/stats/modals/breakdown-table.tsxnew file mode 100644index 0000000000..31b6e0cbab--- /dev/null+++ b/assets/js/dashboard/stats/modals/breakdown-table.tsx@@ -0,0 +1,119 @@+/** @format */++import React, { ReactNode } from 'react'++import { SearchInput } from '../../components/search-input'+import { ColumnConfiguraton, Table } from '../../components/table'+import RocketIcon from './rocket-icon'+import { QueryStatus } from '@tanstack/react-query'++const MIN_HEIGHT_PX = 500++export const BreakdownTable = <TListItem extends { name: string }>({+ title,+ isPending,+ isFetching,+ onSearch,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ columns,+ data,+ status,+ error,+ displayError+}: {+ title: ReactNode+ onSearch?: (input: string) => void+ isPending: boolean+ isFetching: boolean+ hasNextPage: boolean+ isFetchingNextPage: boolean+ fetchNextPage: () => void+ columns: ColumnConfiguraton<TListItem>[]+ data?: { pages: TListItem[][] }+ status?: QueryStatus+ error?: Error | null+ /** Controls whether the component displays API request errors or ignores them. */+ displayError?: boolean+}) => (+ <div className="w-full h-full">+ <div className="flex justify-between items-center">+ <div className="flex items-center gap-x-2">+ <h1 className="text-xl font-bold dark:text-gray-100">{title}</h1>+ {!isPending && isFetching && <SmallLoadingSpinner />}+ </div>+ {!!onSearch && (+ <SearchInput+ onSearch={onSearch}+ className={+ displayError && status === 'error' ? 'pointer-events-none' : ''+ }+ />+ )}+ </div>+ <div className="my-4 border-b border-gray-300"></div>+ <div style={{ minHeight: `${MIN_HEIGHT_PX}px` }}>+ {displayError && status === 'error' && <ErrorMessage error={error} />}+ {isPending && <InitialLoadingSpinner />}+ {data && <Table<TListItem> data={data} columns={columns} />}+ {!isPending && !isFetching && hasNextPage && (+ <LoadMore+ onClick={() => fetchNextPage()}+ isFetchingNextPage={isFetchingNextPage}+ />+ )}+ </div>+ </div>+)++const InitialLoadingSpinner = () => (+ <div+ className="w-full h-full flex flex-col justify-center"+ style={{ minHeight: `${MIN_HEIGHT_PX}px` }}+ >+ <div className="mx-auto loading">+ <div />+ </div>+ </div>+)++const SmallLoadingSpinner = () => (+ <div className="loading sm">+ <div />+ </div>+)++const ErrorMessage = ({ error }: { error?: unknown }) => (+ <div+ className="grid grid-rows-2 text-gray-700 dark:text-gray-300"+ style={{ height: `${MIN_HEIGHT_PX}px` }}+ >+ <div className="text-center self-end">+ <RocketIcon />+ </div>+ <div className="text-lg text-center">+ {error+ ? (error as { message: string }).message+ : 'Error loading data. Refresh the page to try again'}+ </div>+ </div>+)++const LoadMore = ({+ onClick,+ isFetchingNextPage+}: {+ onClick: () => void+ isFetchingNextPage: boolean+}) => (+ <div className="flex flex-col w-full my-4 items-center justify-center h-10">+ {isFetchingNextPage ? (+ <SmallLoadingSpinner />+ ) : (+ <button onClick={onClick} type="button" className="button">+ Load more+ </button>+ )}+ </div>+)diff --git a/assets/js/dashboard/stats/modals/conversions.js b/assets/js/dashboard/stats/modals/conversions.jsindex fe9df2ec6f..3514bd852d 100644--- a/assets/js/dashboard/stats/modals/conversions.js+++ b/assets/js/dashboard/stats/modals/conversions.js@@ -16,7 +16,8 @@ function ConversionsModal() {title: 'Goal Conversions',dimension: 'goal',endpoint: url.apiPath(site, '/conversions'),- dimensionLabel: "Goal"+ dimensionLabel: "Goal",+ defaultOrder: []}const getFilterInfo = useCallback((listItem) => {diff --git a/assets/js/dashboard/stats/modals/devices/browser-versions-modal.js b/assets/js/dashboard/stats/modals/devices/browser-versions-modal.jsindex f9ba699468..369b4dce9f 100644--- a/assets/js/dashboard/stats/modals/devices/browser-versions-modal.js+++ b/assets/js/dashboard/stats/modals/devices/browser-versions-modal.js@@ -7,6 +7,7 @@ import { useQueryContext } from "../../../query-context";import { useSiteContext } from "../../../site-context";import { browserIconFor } from "../../devices";import chooseMetrics from './choose-metrics';+import { SortDirection } from "../../../hooks/use-order-by";function BrowserVersionsModal() {const { query } = useQueryContext();@@ -16,7 +17,8 @@ function BrowserVersionsModal() {title: 'Browser Versions',dimension: 'browser_version',endpoint: url.apiPath(site, '/browser-versions'),- dimensionLabel: 'Browser version'+ dimensionLabel: 'Browser version',+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {diff --git a/assets/js/dashboard/stats/modals/devices/browsers-modal.js b/assets/js/dashboard/stats/modals/devices/browsers-modal.jsindex dc0598baae..1160b8ebf5 100644--- a/assets/js/dashboard/stats/modals/devices/browsers-modal.js+++ b/assets/js/dashboard/stats/modals/devices/browsers-modal.js@@ -7,6 +7,7 @@ import { useQueryContext } from "../../../query-context";import { useSiteContext } from "../../../site-context";import { browserIconFor } from "../../devices";import chooseMetrics from './choose-metrics';+import { SortDirection } from "../../../hooks/use-order-by";function BrowsersModal() {const { query } = useQueryContext();@@ -16,7 +17,8 @@ function BrowsersModal() {title: 'Browsers',dimension: 'browser',endpoint: url.apiPath(site, '/browsers'),- dimensionLabel: 'Browser'+ dimensionLabel: 'Browser',+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {diff --git a/assets/js/dashboard/stats/modals/devices/choose-metrics.js b/assets/js/dashboard/stats/modals/devices/choose-metrics.jsindex a9f5cbb85f..9deebb8f99 100644--- a/assets/js/dashboard/stats/modals/devices/choose-metrics.js+++ b/assets/js/dashboard/stats/modals/devices/choose-metrics.js@@ -5,14 +5,14 @@ export default function chooseMetrics(query) {if (hasGoalFilter(query)) {return [metrics.createTotalVisitors(),- metrics.createVisitors({ renderLabel: (_query) => 'Conversions' }),+ metrics.createVisitors({ renderLabel: (_query) => 'Conversions', width: 'w-28' }),metrics.createConversionRate()]}if (isRealTimeDashboard(query)) {return [- metrics.createVisitors({ renderLabel: (_query) => 'Current visitors' }),+ metrics.createVisitors({ renderLabel: (_query) => 'Current visitors', width: 'w-36' }),metrics.createPercentage()]}diff --git a/assets/js/dashboard/stats/modals/devices/operating-system-versions-modal.js b/assets/js/dashboard/stats/modals/devices/operating-system-versions-modal.jsindex 3e94ea2930..6c7d5c72cc 100644--- a/assets/js/dashboard/stats/modals/devices/operating-system-versions-modal.js+++ b/assets/js/dashboard/stats/modals/devices/operating-system-versions-modal.js@@ -7,6 +7,7 @@ import { useQueryContext } from "../../../query-context";import { useSiteContext } from "../../../site-context";import { osIconFor } from "../../devices";import chooseMetrics from './choose-metrics';+import { SortDirection } from "../../../hooks/use-order-by";function OperatingSystemVersionsModal() {const { query } = useQueryContext();@@ -16,7 +17,8 @@ function OperatingSystemVersionsModal() {title: 'Operating System Versions',dimension: 'os_version',endpoint: url.apiPath(site, '/operating-system-versions'),- dimensionLabel: 'Operating system version'+ dimensionLabel: 'Operating system version',+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {diff --git a/assets/js/dashboard/stats/modals/devices/operating-systems-modal.js b/assets/js/dashboard/stats/modals/devices/operating-systems-modal.jsindex 9ae5c4074b..2a92795648 100644--- a/assets/js/dashboard/stats/modals/devices/operating-systems-modal.js+++ b/assets/js/dashboard/stats/modals/devices/operating-systems-modal.js@@ -7,6 +7,7 @@ import { useQueryContext } from "../../../query-context";import { useSiteContext } from "../../../site-context";import { osIconFor } from "../../devices";import chooseMetrics from './choose-metrics';+import { SortDirection } from "../../../hooks/use-order-by";function OperatingSystemsModal() {const { query } = useQueryContext();@@ -16,7 +17,8 @@ function OperatingSystemsModal() {title: 'Operating Systems',dimension: 'os',endpoint: url.apiPath(site, '/operating-systems'),- dimensionLabel: 'Operating system'+ dimensionLabel: 'Operating system',+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {diff --git a/assets/js/dashboard/stats/modals/devices/screen-sizes.js b/assets/js/dashboard/stats/modals/devices/screen-sizes.jsindex dc64589463..30e6cd447c 100644--- a/assets/js/dashboard/stats/modals/devices/screen-sizes.js+++ b/assets/js/dashboard/stats/modals/devices/screen-sizes.js@@ -6,6 +6,7 @@ import { useQueryContext } from "../../../query-context";import { useSiteContext } from "../../../site-context";import { screenSizeIconFor } from "../../devices";import chooseMetrics from './choose-metrics';+import { SortDirection } from "../../../hooks/use-order-by";function ScreenSizesModal() {const { query } = useQueryContext();@@ -15,7 +16,8 @@ function ScreenSizesModal() {title: 'Screen Sizes',dimension: 'screen',endpoint: url.apiPath(site, '/screen-sizes'),- dimensionLabel: 'Screen size'+ dimensionLabel: 'Screen size',+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {diff --git a/assets/js/dashboard/stats/modals/entry-pages.js b/assets/js/dashboard/stats/modals/entry-pages.jsindex f1d3068b3d..6d5a72d693 100644--- a/assets/js/dashboard/stats/modals/entry-pages.js+++ b/assets/js/dashboard/stats/modals/entry-pages.js@@ -7,6 +7,7 @@ import * as metrics from '../reports/metrics'import * as url from '../../util/url';import { useQueryContext } from "../../query-context";import { useSiteContext } from "../../site-context";+import { SortDirection } from "../../hooks/use-order-by";function EntryPagesModal() {const { query } = useQueryContext();@@ -16,7 +17,8 @@ function EntryPagesModal() {title: 'Entry Pages',dimension: 'entry_page',endpoint: url.apiPath(site, '/entry-pages'),- dimensionLabel: 'Entry page'+ dimensionLabel: 'Entry page',+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {@@ -34,20 +36,20 @@ function EntryPagesModal() {if (hasGoalFilter(query)) {return [metrics.createTotalVisitors(),- metrics.createVisitors({ renderLabel: (_query) => 'Conversions' }),+ metrics.createVisitors({ renderLabel: (_query) => 'Conversions', width: 'w-28' }),metrics.createConversionRate()]}if (isRealTimeDashboard(query)) {return [- metrics.createVisitors({ renderLabel: (_query) => 'Current visitors' })+ metrics.createVisitors({ renderLabel: (_query) => 'Current visitors', width: 'w-36' })]}return [metrics.createVisitors({ renderLabel: (_query) => "Visitors" }),- metrics.createVisits({ renderLabel: (_query) => "Total Entrances" }),+ metrics.createVisits({ renderLabel: (_query) => "Total Entrances", width: 'w-36' }),metrics.createVisitDuration()]}diff --git a/assets/js/dashboard/stats/modals/exit-pages.js b/assets/js/dashboard/stats/modals/exit-pages.jsindex bd4bd2e5b5..2be05f0168 100644--- a/assets/js/dashboard/stats/modals/exit-pages.js+++ b/assets/js/dashboard/stats/modals/exit-pages.js@@ -7,6 +7,7 @@ import * as metrics from '../reports/metrics'import * as url from '../../util/url';import { useQueryContext } from "../../query-context";import { useSiteContext } from "../../site-context";+import { SortDirection } from "../../hooks/use-order-by";function ExitPagesModal() {const { query } = useQueryContext();@@ -16,7 +17,8 @@ function ExitPagesModal() {title: 'Exit Pages',dimension: 'exit_page',endpoint: url.apiPath(site, '/exit-pages'),- dimensionLabel: 'Page url'+ dimensionLabel: 'Page url',+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {@@ -34,20 +36,20 @@ function ExitPagesModal() {if (hasGoalFilter(query)) {return [metrics.createTotalVisitors(),- metrics.createVisitors({ renderLabel: (_query) => 'Conversions' }),+ metrics.createVisitors({ renderLabel: (_query) => 'Conversions', width: 'w-28' }),metrics.createConversionRate()]}if (query.period === 'realtime') {return [- metrics.createVisitors({ renderLabel: (_query) => 'Current visitors' })+ metrics.createVisitors({ renderLabel: (_query) => 'Current visitors', width: 'w-36'})]}return [- metrics.createVisitors({ renderLabel: (_query) => "Visitors" }),- metrics.createVisits({ renderLabel: (_query) => "Total Exits" }),+ metrics.createVisitors({ renderLabel: (_query) => "Visitors", sortable: true }),+ metrics.createVisits({ renderLabel: (_query) => "Total Exits", sortable: true }),metrics.createExitRate()]}diff --git a/assets/js/dashboard/stats/modals/filter-modal.js b/assets/js/dashboard/stats/modals/filter-modal.jsindex 1d5e558e78..9139b849a4 100644--- a/assets/js/dashboard/stats/modals/filter-modal.js+++ b/assets/js/dashboard/stats/modals/filter-modal.js@@ -4,7 +4,7 @@ import { useParams } from 'react-router-dom';import Modal from './modal';import { EVENT_PROPS_PREFIX, FILTER_GROUP_TO_MODAL_TYPE, formatFilterGroup, FILTER_OPERATIONS, getFilterGroup, FILTER_MODAL_TO_FILTER_GROUP, cleanLabels } from '../../util/filters';import { useQueryContext } from '../../query-context';-import { shouldIgnoreKeypress } from '../../keybinding';+import { isModifierPressed, isTyping } from '../../keybinding';import FilterModalGroup from "./filter-modal-group";import { rootRoute } from '../../router';import { useAppNavigate } from '../../navigation/use-app-navigate';@@ -62,7 +62,7 @@ class FilterModal extends React.Component {}handleKeydown(e) {- if (shouldIgnoreKeypress(e)) return+ if (isTyping(e) || isModifierPressed(e)) returnif (e.target.tagName === 'BODY' && e.key === 'Enter') {this.handleSubmit()diff --git a/assets/js/dashboard/stats/modals/google-keywords.js b/assets/js/dashboard/stats/modals/google-keywords.jsdeleted file mode 100644index 498489c144..0000000000--- a/assets/js/dashboard/stats/modals/google-keywords.js+++ /dev/null@@ -1,193 +0,0 @@-import React, { useState, useEffect, useRef } from "react";--import Modal from './modal'-import RocketIcon from './rocket-icon'-import { useQueryContext } from "../../query-context";-import { useSiteContext } from "../../site-context";-import { useAPIClient } from "../../hooks/api-client";-import { useDebounce } from "../../custom-hooks";-import { createVisitors, Metric, renderNumberWithTooltip } from "../reports/metrics";-import numberFormatter, { percentageFormatter } from "../../util/number-formatter";-import classNames from "classnames";-import { MIN_HEIGHT_PX } from "./breakdown-modal";--function GoogleKeywordsModal() {- const searchBoxRef = useRef(null)- const { query } = useQueryContext()- const site = useSiteContext()- const endpoint = `/api/stats/${encodeURIComponent(site.domain)}/referrers/Google`-- const [search, setSearch] = useState('')-- const metrics = [- createVisitors({renderLabel: (_query) => 'Visitors'}),- new Metric({key: 'impressions', renderLabel: (_query) => 'Impressions', renderValue: renderNumberWithTooltip}),- new Metric({key: 'ctr', renderLabel: (_query) => 'CTR', renderValue: percentageFormatter}),- new Metric({key: 'position', renderLabel: (_query) => 'Position', renderValue: numberFormatter})- ]-- const {- data,- hasNextPage,- fetchNextPage,- isFetchingNextPage,- isFetching,- isPending,- error,- status- } = useAPIClient({- key: [endpoint, {query, search}],- getRequestParams: (key) => {- const [_endpoint, {query, search}] = key- const params = { detailed: true }-- return [query, search === '' ? params : {...params, search}]- },- initialPageParam: 0- })-- useEffect(() => {- const searchBox = searchBoxRef.current-- const handleKeyUp = (event) => {- if (event.key === 'Escape') {- event.target.blur()- event.stopPropagation()- }- }-- searchBox.addEventListener('keyup', handleKeyUp);-- return () => {- searchBox.removeEventListener('keyup', handleKeyUp);- }- }, [])-- function renderRow(item) {- return (- <tr className="text-sm dark:text-gray-200" key={item.name}>- <td className="p-2">{item.name}</td>- {metrics.map((metric) => {- return (- <td key={metric.key} className="p-2 w-32 font-medium" align="right">- {metric.renderValue(item[metric.key])}- </td>- )- })}- </tr>- )- }-- function renderInitialLoadingSpinner() {- return (- <div className="w-full h-full flex flex-col justify-center" style={{ minHeight: `${MIN_HEIGHT_PX}px` }}>- <div className="mx-auto loading"><div></div></div>- </div>- )- }-- function renderSmallLoadingSpinner() {- return (- <div className="loading sm"><div></div></div>- )- }-- function renderLoadMoreButton() {- if (isPending) return null- if (!isFetching && !hasNextPage) return null-- return (- <div className="flex flex-col w-full my-4 items-center justify-center h-10">- {!isFetching && <button onClick={fetchNextPage} type="button" className="button">Load more</button>}- {isFetchingNextPage && renderSmallLoadingSpinner()}- </div>- )- }-- function handleInputChange(e) {- setSearch(e.target.value)- }-- const debouncedHandleInputChange = useDebounce(handleInputChange)-- function renderSearchInput() {- const searchBoxClass = classNames('shadow-sm dark:bg-gray-900 dark:text-gray-100 focus:ring-indigo-500 focus:border-indigo-500 block sm:text-sm border-gray-300 dark:border-gray-500 rounded-md dark:bg-gray-800 w-48', {- 'pointer-events-none' : status === 'error'- })- return (- <input- ref={searchBoxRef}- type="text"- placeholder={"Search"}- className={searchBoxClass}- onChange={debouncedHandleInputChange}- />- )- }-- function renderModalBody() {- if (data?.pages?.length) {- return (- <main className="modal__content">- <table className="w-max overflow-x-auto md:w-full table-striped table-fixed">- <thead>- <tr>- <th- className="p-2 w-48 md:w-56 lg:w-1/3 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400"- align="left"- >- Search term- </th>- {metrics.map((metric) => {- return (- <th key={metric.key} className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">- {metric.renderLabel(query)}- </th>- )- })}- </tr>- </thead>- <tbody>- {data.pages.map((p) => p.map(renderRow))}- </tbody>- </table>- </main>- )- }- }-- function renderError() {- return (- <div- className="grid grid-rows-2 text-gray-700 dark:text-gray-300"- style={{ height: `${MIN_HEIGHT_PX}px` }}- >- <div className="text-center self-end"><RocketIcon /></div>- <div className="text-lg text-center">{error.message}</div>- </div>- )- }-- return (- <Modal >- <div className="w-full h-full">- <div className="flex justify-between items-center">- <div className="flex items-center gap-x-2">- <h1 className="text-xl font-bold dark:text-gray-100">Google Search Terms</h1>- {!isPending && isFetching && renderSmallLoadingSpinner()}- </div>- {renderSearchInput()}- </div>- <div className="my-4 border-b border-gray-300"></div>- <div style={{ minHeight: `${MIN_HEIGHT_PX}px` }}>- {status === 'error' && renderError()}- {isPending && renderInitialLoadingSpinner()}- {!isPending && renderModalBody()}- {renderLoadMoreButton()}- </div>- </div>- </Modal>- )-}--export default GoogleKeywordsModaldiff --git a/assets/js/dashboard/stats/modals/google-keywords.tsx b/assets/js/dashboard/stats/modals/google-keywords.tsxnew file mode 100644index 0000000000..5ee7bddfdb--- /dev/null+++ b/assets/js/dashboard/stats/modals/google-keywords.tsx@@ -0,0 +1,109 @@+/** @format */++import React, { useMemo, useState } from 'react'++import Modal from './modal'+import { useQueryContext } from '../../query-context'+import { useSiteContext } from '../../site-context'+import { usePaginatedGetAPI } from '../../hooks/api-client'+import {+ createVisitors,+ Metric,+ renderNumberWithTooltip+} from '../reports/metrics'+import numberFormatter, {+ percentageFormatter+} from '../../util/number-formatter'+import { apiPath } from '../../util/url'+import { DashboardQuery } from '../../query'+import { ColumnConfiguraton } from '../../components/table'+import { BreakdownTable } from './breakdown-table'++type GoogleKeywordItem = {+ visitors: string+ name: string+ impressions: number+ ctr: number+ position: number+}++const metrics = [+ createVisitors({ renderLabel: () => 'Visitors', sortable: false }),+ new Metric({+ width: 'w-28',+ key: 'impressions',+ renderLabel: () => 'Impressions',+ renderValue: renderNumberWithTooltip,+ sortable: false+ }),+ new Metric({+ width: 'w-16',+ key: 'ctr',+ renderLabel: () => 'CTR',+ renderValue: percentageFormatter,+ sortable: false+ }),+ new Metric({+ width: 'w-28',+ key: 'position',+ renderLabel: () => 'Position',+ renderValue: numberFormatter,+ sortable: false+ })+]++function GoogleKeywordsModal() {+ const { query } = useQueryContext()+ const site = useSiteContext()+ const endpoint = apiPath(site, '/referrers/Google')++ const [search, setSearch] = useState('')++ const apiState = usePaginatedGetAPI<+ { results: GoogleKeywordItem[] },+ [string, { query: DashboardQuery; search: string }]+ >({+ key: [endpoint, { query, search }],+ getRequestParams: (key) => {+ const [_endpoint, { query, search }] = key+ const params = { detailed: true }++ return [query, search === '' ? params : { ...params, search }]+ },+ initialPageParam: 0+ })++ const columns: ColumnConfiguraton<GoogleKeywordItem>[] = useMemo(+ () => [+ {+ label: 'Search term',+ key: 'name',+ width: 'w-48 md:w-56 lg:w-1/3',+ align: 'left'+ },+ ...metrics.map(+ (m): ColumnConfiguraton<GoogleKeywordItem> => ({+ label: m.renderLabel(query),+ key: m.key,+ width: m.width,+ align: 'right'+ })+ )+ ],+ [query]+ )++ return (+ <Modal>+ <BreakdownTable+ title="Google Search Terms"+ displayError={true}+ onSearch={setSearch}+ {...apiState}+ columns={columns}+ />+ </Modal>+ )+}++export default GoogleKeywordsModaldiff --git a/assets/js/dashboard/stats/modals/locations-modal.js b/assets/js/dashboard/stats/modals/locations-modal.jsindex d607663f8c..615f6e9e3d 100644--- a/assets/js/dashboard/stats/modals/locations-modal.js+++ b/assets/js/dashboard/stats/modals/locations-modal.js@@ -8,11 +8,12 @@ import * as url from "../../util/url";import { useQueryContext } from "../../query-context";import { useSiteContext } from "../../site-context";import { addFilter } from "../../query";+import { SortDirection } from "../../hooks/use-order-by";const VIEWS = {- countries: { title: 'Top Countries', dimension: 'country', endpoint: '/countries', dimensionLabel: 'Country' },- regions: { title: 'Top Regions', dimension: 'region', endpoint: '/regions', dimensionLabel: 'Region' },- cities: { title: 'Top Cities', dimension: 'city', endpoint: '/cities', dimensionLabel: 'City' },+ countries: { title: 'Top Countries', dimension: 'country', endpoint: '/countries', dimensionLabel: 'Country', defaultOrder: ["visitors", SortDirection.desc] },+ regions: { title: 'Top Regions', dimension: 'region', endpoint: '/regions', dimensionLabel: 'Region', defaultOrder: ["visitors", SortDirection.desc] },+ cities: { title: 'Top Cities', dimension: 'city', endpoint: '/cities', dimensionLabel: 'City', defaultOrder: ["visitors", SortDirection.desc] },}function LocationsModal({ currentView }) {@@ -38,14 +39,14 @@ function LocationsModal({ currentView }) {if (hasGoalFilter(query)) {return [metrics.createTotalVisitors(),- metrics.createVisitors({ renderLabel: (_query) => 'Conversions' }),+ metrics.createVisitors({ renderLabel: (_query) => 'Conversions', width: 'w-28' }),metrics.createConversionRate()]}if (query.period === 'realtime') {return [- metrics.createVisitors({ renderLabel: (_query) => 'Current visitors' })+ metrics.createVisitors({ renderLabel: (_query) => 'Current visitors', width: 'w-36' })]}diff --git a/assets/js/dashboard/stats/modals/pages.js b/assets/js/dashboard/stats/modals/pages.jsindex 5d59e0d078..533880d5a7 100644--- a/assets/js/dashboard/stats/modals/pages.js+++ b/assets/js/dashboard/stats/modals/pages.js@@ -7,6 +7,7 @@ import * as metrics from '../reports/metrics'import * as url from '../../util/url';import { useQueryContext } from "../../query-context";import { useSiteContext } from "../../site-context";+import { SortDirection } from "../../hooks/use-order-by";function PagesModal() {const { query } = useQueryContext();@@ -16,7 +17,8 @@ function PagesModal() {title: 'Top Pages',dimension: 'page',endpoint: url.apiPath(site, '/pages'),- dimensionLabel: 'Page url'+ dimensionLabel: 'Page url',+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {@@ -34,14 +36,14 @@ function PagesModal() {if (hasGoalFilter(query)) {return [metrics.createTotalVisitors(),- metrics.createVisitors({renderLabel: (_query) => 'Conversions'}),+ metrics.createVisitors({renderLabel: (_query) => 'Conversions', width: 'w-28'}),metrics.createConversionRate()]}if (isRealTimeDashboard(query)) {return [- metrics.createVisitors({renderLabel: (_query) => 'Current visitors'})+ metrics.createVisitors({renderLabel: (_query) => 'Current visitors', width: 'w-36'})]}diff --git a/assets/js/dashboard/stats/modals/props.js b/assets/js/dashboard/stats/modals/props.jsindex 2e4a885305..47965337b9 100644--- a/assets/js/dashboard/stats/modals/props.js+++ b/assets/js/dashboard/stats/modals/props.js@@ -10,6 +10,7 @@ import * as metrics from "../reports/metrics";import * as url from "../../util/url";import { useQueryContext } from "../../query-context";import { useSiteContext } from "../../site-context";+import { SortDirection } from "../../hooks/use-order-by";function PropsModal() {const { query } = useQueryContext();@@ -23,7 +24,8 @@ function PropsModal() {title: specialTitleWhenGoalFilter(query, 'Custom Property Breakdown'),dimension: propKey,endpoint: url.apiPath(site, `/custom-prop-values/${propKey}`),- dimensionLabel: propKey+ dimensionLabel: propKey,+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {diff --git a/assets/js/dashboard/stats/modals/referrer-drilldown.js b/assets/js/dashboard/stats/modals/referrer-drilldown.jsindex 5e008c6942..016f3e1df2 100644--- a/assets/js/dashboard/stats/modals/referrer-drilldown.js+++ b/assets/js/dashboard/stats/modals/referrer-drilldown.js@@ -9,6 +9,7 @@ import * as url from "../../util/url";import { addFilter } from "../../query";import { useQueryContext } from "../../query-context";import { useSiteContext } from "../../site-context";+import { SortDirection } from '../../hooks/use-order-by';function ReferrerDrilldownModal() {const { referrer } = useParams();@@ -19,7 +20,8 @@ function ReferrerDrilldownModal() {title: "Referrer Drilldown",dimension: 'referrer',endpoint: url.apiPath(site, `/referrers/${referrer}`),- dimensionLabel: "Referrer"+ dimensionLabel: "Referrer",+ defaultOrder: ["visitors", SortDirection.desc]}const getFilterInfo = useCallback((listItem) => {@@ -37,14 +39,14 @@ function ReferrerDrilldownModal() {if (hasGoalFilter(query)) {return [metrics.createTotalVisitors(),- metrics.createVisitors({ renderLabel: (_query) => 'Conversions' }),+ metrics.createVisitors({ renderLabel: (_query) => 'Conversions', width: 'w-28' }),metrics.createConversionRate()]}if (isRealTimeDashboard(query)) {return [- metrics.createVisitors({ renderLabel: (_query) => 'Current visitors' })+ metrics.createVisitors({ renderLabel: (_query) => 'Current visitors', width: 'w-36' })]}diff --git a/assets/js/dashboard/stats/modals/sources.js b/assets/js/dashboard/stats/modals/sources.jsindex edf2d06d01..90242a4beb 100644--- a/assets/js/dashboard/stats/modals/sources.js+++ b/assets/js/dashboard/stats/modals/sources.js@@ -7,10 +7,11 @@ import * as url from "../../util/url";import { addFilter } from "../../query";import { useQueryContext } from "../../query-context";import { useSiteContext } from "../../site-context";+import { SortDirection } from "../../hooks/use-order-by";const VIEWS = {sources: {- info: { title: 'Top Sources', dimension: 'source', endpoint: '/sources', dimensionLabel: 'Source' },+ info: { title: 'Top Sources', dimension: 'source', endpoint: '/sources', dimensionLabel: 'Source', defaultOrder: ["visitors", SortDirection.desc] },renderIcon: (listItem) => {return (<img@@ -22,19 +23,19 @@ const VIEWS = {}},utm_mediums: {- info: { title: 'Top UTM Mediums', dimension: 'utm_medium', endpoint: '/utm_mediums', dimensionLabel: 'UTM Medium' }+ info: { title: 'Top UTM Mediums', dimension: 'utm_medium', endpoint: '/utm_mediums', dimensionLabel: 'UTM Medium', defaultOrder: ["visitors", SortDirection.desc] }},utm_sources: {- info: { title: 'Top UTM Sources', dimension: 'utm_source', endpoint: '/utm_sources', dimensionLabel: 'UTM Source' }+ info: { title: 'Top UTM Sources', dimension: 'utm_source', endpoint: '/utm_sources', dimensionLabel: 'UTM Source', defaultOrder: ["visitors", SortDirection.desc] }},utm_campaigns: {- info: { title: 'Top UTM Campaigns', dimension: 'utm_campaign', endpoint: '/utm_campaigns', dimensionLabel: 'UTM Campaign' }+ info: { title: 'Top UTM Campaigns', dimension: 'utm_campaign', endpoint: '/utm_campaigns', dimensionLabel: 'UTM Campaign', defaultOrder: ["visitors", SortDirection.desc] }},utm_contents: {- info: { title: 'Top UTM Contents', dimension: 'utm_content', endpoint: '/utm_contents', dimensionLabel: 'UTM Content' }+ info: { title: 'Top UTM Contents', dimension: 'utm_content', endpoint: '/utm_contents', dimensionLabel: 'UTM Content', defaultOrder: ["visitors", SortDirection.desc] }},utm_terms: {- info: { title: 'Top UTM Terms', dimension: 'utm_term', endpoint: '/utm_terms', dimensionLabel: 'UTM Term' }+ info: { title: 'Top UTM Terms', dimension: 'utm_term', endpoint: '/utm_terms', dimensionLabel: 'UTM Term', defaultOrder: ["visitors", SortDirection.desc] }},}@@ -60,14 +61,14 @@ function SourcesModal({ currentView }) {if (hasGoalFilter(query)) {return [metrics.createTotalVisitors(),- metrics.createVisitors({ renderLabel: (_query) => 'Conversions' }),+ metrics.createVisitors({ renderLabel: (_query) => 'Conversions', width: 'w-28' }),metrics.createConversionRate()]}if (isRealTimeDashboard(query)) {return [- metrics.createVisitors({ renderLabel: (_query) => 'Current visitors' })+ metrics.createVisitors({ renderLabel: (_query) => 'Current visitors', width: 'w-36' })]}diff --git a/assets/js/dashboard/stats/pages/index.js b/assets/js/dashboard/stats/pages/index.jsindex 79394a4275..7430c702e6 100644--- a/assets/js/dashboard/stats/pages/index.js+++ b/assets/js/dashboard/stats/pages/index.js@@ -31,7 +31,7 @@ function EntryPages({ afterFetchData }) {function chooseMetrics() {return [- metrics.createVisitors({ defaultLabel: 'Unique Entrances', meta: { plot: true } }),+ metrics.createVisitors({ defaultLabel: 'Unique Entrances', width: 'w-36', meta: { plot: true } }),hasGoalFilter(query) && metrics.createConversionRate(),].filter(metric => !!metric)}@@ -70,7 +70,7 @@ function ExitPages({ afterFetchData }) {function chooseMetrics() {return [- metrics.createVisitors({ defaultLabel: 'Unique Exits', meta: { plot: true } }),+ metrics.createVisitors({ defaultLabel: 'Unique Exits', width: 'w-36', meta: { plot: true } }),hasGoalFilter(query) && metrics.createConversionRate(),].filter(metric => !!metric)}diff --git a/assets/js/dashboard/stats/reports/metrics.js b/assets/js/dashboard/stats/reports/metrics.jsindex 74fc7b0d2d..350f737d16 100644--- a/assets/js/dashboard/stats/reports/metrics.js+++ b/assets/js/dashboard/stats/reports/metrics.js@@ -52,6 +52,8 @@ export class Metric {this.renderValue = props.renderValuethis.renderLabel = props.renderLabelthis.meta = props.meta || {}+ this.sortable = props.sortable+ this.width = props.width ?? 'w-24'}}@@ -87,77 +89,77 @@ export const createVisitors = (props) => {}}- return new Metric({...props, key: "visitors", renderValue, renderLabel})+ return new Metric({width: 'w-24', sortable: true, ...props, key: "visitors", renderValue, renderLabel})}export const createConversionRate = (props) => {const renderValue = percentageFormatterconst renderLabel = (_query) => "CR"- return new Metric({...props, key: "conversion_rate", renderLabel, renderValue})+ return new Metric({width: 'w-16', ...props, key: "conversion_rate", renderLabel, renderValue, sortable: true})}export const createPercentage = (props) => {const renderValue = (value) => valueconst renderLabel = (_query) => "%"- return new Metric({...props, key: "percentage", renderLabel, renderValue})+ return new Metric({width: 'w-16', ...props, key: "percentage", renderLabel, renderValue, sortable: true})}export const createEvents = (props) => {const renderValue = typeof props.renderValue === 'function' ? props.renderValue : renderNumberWithTooltip- return new Metric({...props, key: "events", renderValue: renderValue})+ return new Metric({width: 'w-24', ...props, key: "events", renderValue: renderValue, sortable: true})}export const createTotalRevenue = (props) => {const renderValue = (value) => <Money formatted={value} />const renderLabel = (_query) => "Revenue"- return new Metric({...props, key: "total_revenue", renderValue, renderLabel})+ return new Metric({width: 'w-24', ...props, key: "total_revenue", renderValue, renderLabel, sortable: true})}export const createAverageRevenue = (props) => {const renderValue = (value) => <Money formatted={value} />const renderLabel = (_query) => "Average"- return new Metric({...props, key: "average_revenue", renderValue, renderLabel})+ return new Metric({width: 'w-24', ...props, key: "average_revenue", renderValue, renderLabel, sortable: true})}export const createTotalVisitors = (props) => {const renderValue = renderNumberWithTooltipconst renderLabel = (_query) => "Total Visitors"- return new Metric({...props, key: "total_visitors", renderValue, renderLabel})+ return new Metric({width: 'w-28', ...props, key: "total_visitors", renderValue, renderLabel, sortable: false})}export const createVisits = (props) => {const renderValue = renderNumberWithTooltip- return new Metric({...props, key: "visits", renderValue})+ return new Metric({width: 'w-24', sortable: true, ...props, key: "visits", renderValue })}export const createVisitDuration = (props) => {const renderValue = durationFormatterconst renderLabel = (_query) => "Visit Duration"- return new Metric({...props, key: "visit_duration", renderValue, renderLabel})+ return new Metric({width: 'w-36', ...props, key: "visit_duration", renderValue, renderLabel, sortable: true})}export const createBounceRate = (props) => {const renderValue = (value) => `${value}%`const renderLabel = (_query) => "Bounce Rate"- return new Metric({...props, key: "bounce_rate", renderValue, renderLabel})+ return new Metric({width: 'w-32', ...props, key: "bounce_rate", renderValue, renderLabel, sortable: true})}export const createPageviews = (props) => {const renderValue = renderNumberWithTooltipconst renderLabel = (_query) => "Pageviews"- return new Metric({...props, key: "pageviews", renderValue, renderLabel})+ return new Metric({width: 'w-28', ...props, key: "pageviews", renderValue, renderLabel, sortable: true})}export const createTimeOnPage = (props) => {const renderValue = durationFormatterconst renderLabel = (_query) => "Time on Page"- return new Metric({...props, key: "time_on_page", renderValue, renderLabel})+ return new Metric({width: 'w-32', ...props, key: "time_on_page", renderValue, renderLabel, sortable: false})}export const createExitRate = (props) => {const renderValue = percentageFormatterconst renderLabel = (_query) => "Exit Rate"- return new Metric({...props, key: "exit_rate", renderValue, renderLabel})+ return new Metric({width: 'w-28', ...props, key: "exit_rate", renderValue, renderLabel, sortable: false})}export function renderNumberWithTooltip(value) {diff --git a/lib/plausible/stats/breakdown.ex b/lib/plausible/stats/breakdown.exindex be636e1231..41542d65ed 100644--- a/lib/plausible/stats/breakdown.ex+++ b/lib/plausible/stats/breakdown.ex@@ -13,8 +13,15 @@ defmodule Plausible.Stats.Breakdown doimport Ecto.Queryalias Plausible.Stats.{Query, QueryOptimizer, QueryResult, SQL}- def breakdown(site, %Query{dimensions: [dimension]} = query, metrics, pagination, _opts \\ []) do+ def breakdown(+ site,+ %Query{dimensions: [dimension], order_by: order_by} = query,+ metrics,+ pagination,+ _opts \\ []+ ) dotransformed_metrics = transform_metrics(metrics, dimension)+ transformed_order_by = transform_order_by(order_by || [], dimension)query_with_metrics =Query.set(@@ -22,7 +29,7 @@ defmodule Plausible.Stats.Breakdown dometrics: transformed_metrics,# Concat client requested order with default order, overriding only if client explicitly requests itorder_by:- Enum.concat(query.order_by || [], infer_order_by(transformed_metrics, dimension))+ Enum.concat(transformed_order_by, infer_order_by(transformed_metrics, dimension))|> Enum.uniq_by(&elem(&1, 0)),dimensions: transform_dimensions(dimension),filters: query.filters ++ dimension_filters(dimension),@@ -162,6 +169,15 @@ defmodule Plausible.Stats.Breakdown do|> Map.new()end+ defp maybe_remap_to_group_conversion_rate(metric, dimension) do+ case {metric, dimension} do+ {:conversion_rate, "event:props:" <> _} -> :conversion_rate+ {:conversion_rate, "event:goal"} -> :conversion_rate+ {:conversion_rate, _} -> :group_conversion_rate+ _ -> metric+ end+ end+defp transform_metrics(metrics, dimension) dometrics =if is_nil(metric_to_order_by(metrics)) do@@ -170,13 +186,12 @@ defmodule Plausible.Stats.Breakdown dometricsend- Enum.map(metrics, fn metric ->- case {metric, dimension} do- {:conversion_rate, "event:props:" <> _} -> :conversion_rate- {:conversion_rate, "event:goal"} -> :conversion_rate- {:conversion_rate, _} -> :group_conversion_rate- _ -> metric- end+ Enum.map(metrics, fn metric -> maybe_remap_to_group_conversion_rate(metric, dimension) end)+ end++ defp transform_order_by(order_by, dimension) do+ Enum.map(order_by, fn {metric, direction} ->+ {maybe_remap_to_group_conversion_rate(metric, dimension), direction}end)enddiff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.exindex 8fa9a895eb..37e08b78e5 100644--- a/lib/plausible_web/controllers/api/stats_controller.ex+++ b/lib/plausible_web/controllers/api/stats_controller.ex@@ -926,6 +926,7 @@ defmodule PlausibleWeb.Api.StatsController dototal_pageviews_query =query+ |> struct!(order_by: [])|> Query.remove_top_level_filters(["visit:exit_page"])|> Query.add_filter([:is, "event:page", pages])|> Query.set(dimensions: ["event:page"])diff --git a/test/plausible_web/controllers/api/stats_controller/countries_test.exs b/test/plausible_web/controllers/api/stats_controller/countries_test.exsindex c9307a7ce1..4f400fe5e7 100644--- a/test/plausible_web/controllers/api/stats_controller/countries_test.exs+++ b/test/plausible_web/controllers/api/stats_controller/countries_test.exs@@ -114,6 +114,56 @@ defmodule PlausibleWeb.Api.StatsController.CountriesTest do]end+ test "handles conversion_rate sort directive", %{conn: conn, site: site} do+ populate_stats(site, [+ build(:pageview,+ user_id: 1,+ country_code: "EE"+ ),+ build(:event, user_id: 1, name: "Signup"),+ build(:pageview,+ user_id: 2,+ country_code: "EE"+ ),+ build(:pageview,+ user_id: 3,+ country_code: "GB"+ ),+ build(:event, user_id: 3, name: "Signup")+ ])++ insert(:goal, site: site, event_name: "Signup")++ filters = Jason.encode!(%{"goal" => "Signup"})++ conn =+ get(+ conn,+ "/api/stats/#{site.domain}/countries?period=day&filters=#{filters}&order_by=#{Jason.encode!([["conversion_rate", "desc"]])}"+ )++ assert json_response(conn, 200)["results"] == [+ %{+ "code" => "GB",+ "alpha_3" => "GBR",+ "name" => "United Kingdom",+ "flag" => "🇬🇧",+ "total_visitors" => 1,+ "visitors" => 1,+ "conversion_rate" => 100.0+ },+ %{+ "code" => "EE",+ "alpha_3" => "EST",+ "name" => "Estonia",+ "flag" => "🇪🇪",+ "total_visitors" => 2,+ "visitors" => 1,+ "conversion_rate" => 50.0+ }+ ]+ end+test "returns top countries with :is filter on custom pageview props", %{conn: conn,site: sitediff --git a/test/plausible_web/controllers/api/stats_controller/pages_test.exs b/test/plausible_web/controllers/api/stats_controller/pages_test.exsindex b4d8994ef9..f47b6499bd 100644--- a/test/plausible_web/controllers/api/stats_controller/pages_test.exs+++ b/test/plausible_web/controllers/api/stats_controller/pages_test.exs@@ -1825,6 +1825,40 @@ defmodule PlausibleWeb.Api.StatsController.PagesTest do]end+ test "returns top exit pages by ascending visits", %{conn: conn, site: site} do+ populate_stats(site, [+ build(:pageview,+ pathname: "/page1",+ timestamp: ~N[2021-01-01 00:00:00]+ ),+ build(:pageview,+ pathname: "/page1",+ timestamp: ~N[2021-01-01 00:00:00]+ ),+ build(:pageview,+ pathname: "/page1",+ user_id: @user_id,+ timestamp: ~N[2021-01-01 00:00:00]+ ),+ build(:pageview,+ pathname: "/page2",+ user_id: @user_id,+ timestamp: ~N[2021-01-01 00:15:00]+ )+ ])++ conn =+ get(+ conn,+ "/api/stats/#{site.domain}/exit-pages?period=day&date=2021-01-01&order_by=#{Jason.encode!([["visits", "asc"]])}"+ )++ assert json_response(conn, 200)["results"] == [+ %{"name" => "/page2", "visitors" => 1, "visits" => 1, "exit_rate" => 100},+ %{"name" => "/page1", "visitors" => 2, "visits" => 2, "exit_rate" => 66}+ ]+ end+test "returns top exit pages by visitors filtered by hostname",%{conn: conn, site: site} dopopulate_stats(site, [