Skip to content

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

Refactor ListReport to TS, share props (#5161)

Artur Pata104f584666e4
diff --git a/assets/js/dashboard/components/drilldown-link.tsx b/assets/js/dashboard/components/drilldown-link.tsx
new file mode 100644
index 0000000000..76d218ba5d
--- /dev/null
+++ b/assets/js/dashboard/components/drilldown-link.tsx
@@ -0,0 +1,58 @@
+/** @format */
+
+import React from 'react'
+import {
+ AppNavigationLink,
+ AppNavigationLinkProps
+} from '../navigation/use-app-navigate'
+import classNames from 'classnames'
+import { cleanLabels, replaceFilterByPrefix } from '../util/filters'
+import { plainFilterText } from '../util/filter-text'
+import { useQueryContext } from '../query-context'
+import { Filter, FilterClauseLabels } from '../query'
+
+export type FilterInfo = {
+ prefix: string
+ filter: Filter
+ labels?: FilterClauseLabels
+}
+
+export function DrilldownLink({
+ path,
+ filterInfo,
+ onClick,
+ children,
+ extraClass
+}: Pick<AppNavigationLinkProps, 'path' | 'onClick' | 'children'> & {
+ extraClass?: string
+ filterInfo: FilterInfo | null
+}) {
+ const { query } = useQueryContext()
+ const className = classNames(`${extraClass}`, {
+ 'hover:underline': !!filterInfo
+ })
+
+ if (filterInfo) {
+ const { prefix, filter, labels } = filterInfo
+ const newFilters = replaceFilterByPrefix(query, prefix, filter)
+ const newLabels = cleanLabels(newFilters, query.labels, filter[1], labels)
+
+ return (
+ <AppNavigationLink
+ title={`Add filter: ${plainFilterText({ ...query, labels: newLabels }, filter)}`}
+ className={className}
+ path={path}
+ onClick={onClick}
+ search={(search) => ({
+ ...search,
+ filters: newFilters,
+ labels: newLabels
+ })}
+ >
+ {children}
+ </AppNavigationLink>
+ )
+ } else {
+ return <span className={className}>{children}</span>
+ }
+}
diff --git a/assets/js/dashboard/navigation/use-app-navigate.tsx b/assets/js/dashboard/navigation/use-app-navigate.tsx
index 8fdc736c50..d809404c93 100644
--- a/assets/js/dashboard/navigation/use-app-navigate.tsx
+++ b/assets/js/dashboard/navigation/use-app-navigate.tsx
@@ -71,9 +71,11 @@ export const useAppNavigate = () => {
return navigate
}
+export type AppNavigationLinkProps = AppNavigationTarget & Omit<LinkProps, 'to'>
+
export const AppNavigationLink = forwardRef<
HTMLAnchorElement | null,
- AppNavigationTarget & Omit<LinkProps, 'to'>
+ AppNavigationLinkProps
>(({ path, params, search, ...options }, ref) => {
const getToOptions = useGetNavigateOptions()
diff --git a/assets/js/dashboard/stats/behaviours/conversions.js b/assets/js/dashboard/stats/behaviours/conversions.js
index 7469c819a4..5e32b00e65 100644
--- a/assets/js/dashboard/stats/behaviours/conversions.js
+++ b/assets/js/dashboard/stats/behaviours/conversions.js
@@ -16,7 +16,7 @@ export default function Conversions({ afterFetchData, onGoalFilterClick }) {
return api.get(url.apiPath(site, '/conversions'), query, { limit: 9 })
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: "goal",
filter: ["is", "goal", [listItem.name]],
@@ -38,7 +38,7 @@ export default function Conversions({ afterFetchData, onGoalFilterClick }) {
<ListReport
fetchData={fetchConversions}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Goal"
onClick={onGoalFilterClick}
metrics={chooseMetrics()}
diff --git a/assets/js/dashboard/stats/behaviours/goal-conversions.js b/assets/js/dashboard/stats/behaviours/goal-conversions.js
index f5abc5fbba..8350d1fc14 100644
--- a/assets/js/dashboard/stats/behaviours/goal-conversions.js
+++ b/assets/js/dashboard/stats/behaviours/goal-conversions.js
@@ -43,7 +43,7 @@ function SpecialPropBreakdown({ prop, afterFetchData }) {
return api.get(url.apiPath(site, `/custom-prop-values/${prop}`), query)
}
- function externalLinkDest() {
+ function getExternalLinkUrlFactory() {
if (prop === 'path') {
return (listItem) => url.externalLinkForPage(site.domain, listItem.name)
} else {
@@ -51,7 +51,7 @@ function SpecialPropBreakdown({ prop, afterFetchData }) {
}
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: EVENT_PROPS_PREFIX,
filter: ["is", `${EVENT_PROPS_PREFIX}${prop}`, [listItem['name']]]
@@ -70,11 +70,11 @@ function SpecialPropBreakdown({ prop, afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel={prop}
metrics={chooseMetrics()}
detailsLinkProps={{ path: customPropsRoute.path, params: {propKey: url.maybeEncodeRouteParam(prop)}, search: (search) => search }}
- externalLinkDest={externalLinkDest()}
+ getExternalLinkUrl={getExternalLinkUrlFactory()}
maybeHideDetails={true}
color="bg-red-50"
colMinWidth={90}
diff --git a/assets/js/dashboard/stats/behaviours/props.js b/assets/js/dashboard/stats/behaviours/props.js
index 4a76f44466..f7625dc776 100644
--- a/assets/js/dashboard/stats/behaviours/props.js
+++ b/assets/js/dashboard/stats/behaviours/props.js
@@ -107,7 +107,7 @@ export default function Properties({ afterFetchData }) {
<ListReport
fetchData={fetchProps}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel={propKey}
metrics={chooseMetrics()}
detailsLinkProps={{ path: customPropsRoute.path, params: { propKey }, search: (search) => search }}
@@ -118,7 +118,7 @@ export default function Properties({ afterFetchData }) {
)
}
- const getFilterFor = (listItem) => ({
+ const getFilterInfo = (listItem) => ({
prefix: `${EVENT_PROPS_PREFIX}${propKey}`,
filter: ["is", `${EVENT_PROPS_PREFIX}${propKey}`, [listItem.name]]
})
diff --git a/assets/js/dashboard/stats/devices/index.js b/assets/js/dashboard/stats/devices/index.js
index fcd99216c9..1452ab5bcd 100644
--- a/assets/js/dashboard/stats/devices/index.js
+++ b/assets/js/dashboard/stats/devices/index.js
@@ -57,7 +57,7 @@ function Browsers({ afterFetchData }) {
return api.get(url.apiPath(site, '/browsers'), query)
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: 'browser',
filter: ["is", "browser", [listItem['name']]]
@@ -80,7 +80,7 @@ function Browsers({ afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Browser"
metrics={chooseMetrics()}
renderIcon={renderIcon}
@@ -100,7 +100,7 @@ function BrowserVersions({ afterFetchData }) {
return browserIconFor(listItem.browser)
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
if (getSingleFilter(query, "browser") == '(not set)') {
return null
}
@@ -122,7 +122,7 @@ function BrowserVersions({ afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Browser version"
metrics={chooseMetrics()}
renderIcon={renderIcon}
@@ -170,7 +170,7 @@ function OperatingSystems({ afterFetchData }) {
return api.get(url.apiPath(site, '/operating-systems'), query)
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: 'os',
filter: ["is", "os", [listItem['name']]]
@@ -193,7 +193,7 @@ function OperatingSystems({ afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
renderIcon={renderIcon}
keyLabel="Operating system"
metrics={chooseMetrics()}
@@ -214,7 +214,7 @@ function OperatingSystemVersions({ afterFetchData }) {
return osIconFor(listItem.os)
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
if (getSingleFilter(query, "os") == '(not set)') {
return null
}
@@ -237,7 +237,7 @@ function OperatingSystemVersions({ afterFetchData }) {
fetchData={fetchData}
renderIcon={renderIcon}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Operating System Version"
metrics={chooseMetrics()}
detailsLinkProps={{ path: operatingSystemVersionsRoute.path, search: (search) => search }}
@@ -258,7 +258,7 @@ function ScreenSizes({ afterFetchData }) {
return screenSizeIconFor(listItem.name)
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: 'screen',
filter: ["is", "screen", [listItem['name']]]
@@ -277,7 +277,7 @@ function ScreenSizes({ afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Screen size"
metrics={chooseMetrics()}
renderIcon={renderIcon}
diff --git a/assets/js/dashboard/stats/locations/index.js b/assets/js/dashboard/stats/locations/index.js
index 932609abba..a75006f50c 100644
--- a/assets/js/dashboard/stats/locations/index.js
+++ b/assets/js/dashboard/stats/locations/index.js
@@ -22,7 +22,7 @@ function Countries({ query, site, onClick, afterFetchData }) {
return <span className="mr-2">{country.flag}</span>
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: "country",
filter: ["is", "country", [listItem['code']]],
@@ -41,7 +41,7 @@ function Countries({ query, site, onClick, afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
onClick={onClick}
keyLabel="Country"
metrics={chooseMetrics()}
@@ -61,7 +61,7 @@ function Regions({ query, site, onClick, afterFetchData }) {
return <span className="mr-2">{region.country_flag}</span>
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: "region",
filter: ["is", "region", [listItem['code']]],
@@ -80,7 +80,7 @@ function Regions({ query, site, onClick, afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
onClick={onClick}
keyLabel="Region"
metrics={chooseMetrics()}
@@ -100,7 +100,7 @@ function Cities({ query, site, afterFetchData }) {
return <span className="mr-2">{city.country_flag}</span>
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: "city",
filter: ["is", "city", [listItem['code']]],
@@ -119,7 +119,7 @@ function Cities({ query, site, afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="City"
metrics={chooseMetrics()}
detailsLinkProps={{ path: citiesRoute.path, search: (search) => search }}
diff --git a/assets/js/dashboard/stats/modals/breakdown-modal.tsx b/assets/js/dashboard/stats/modals/breakdown-modal.tsx
index f950c2b5df..1a9bd08ccb 100644
--- a/assets/js/dashboard/stats/modals/breakdown-modal.tsx
+++ b/assets/js/dashboard/stats/modals/breakdown-modal.tsx
@@ -2,7 +2,6 @@
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'
@@ -18,6 +17,8 @@ import { BreakdownResultMeta, DashboardQuery } from '../../query'
import { ColumnConfiguraton } from '../../components/table'
import { BreakdownTable } from './breakdown-table'
import { PlausibleSite, useSiteContext } from '../../site-context'
+import { DrilldownLink, FilterInfo } from '../../components/drilldown-link'
+import { SharedReportProps } from '../reports/list'
export type ReportInfo = {
/** Title of the report to render on the top left. */
@@ -30,6 +31,14 @@ export type ReportInfo = {
defaultOrder?: Order
}
+type BreakdownModalProps = {
+ /** Dimension and title of the breakdown. */
+ reportInfo: ReportInfo
+ /** Function that must return a new query that contains appropriate search filter for searchValue param. */
+ addSearchFilter?: (q: DashboardQuery, searchValue: string) => DashboardQuery
+ searchEnabled?: boolean
+}
+
/**
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.
@@ -48,35 +57,18 @@ export type ReportInfo = {
@see usePaginatedGetAPI
*/
+
export default function BreakdownModal<TListItem extends { name: string }>({
reportInfo,
metrics,
renderIcon,
- getExternalLinkURL,
+ 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
-}) {
+}: Omit<SharedReportProps<TListItem>, 'fetchData'> & BreakdownModalProps) {
const site = useSiteContext()
const { query } = useQueryContext()
const [meta, setMeta] = useState<BreakdownResultMeta | null>(null)
@@ -141,7 +133,7 @@ export default function BreakdownModal<TListItem extends { name: string }>({
<NameCell
item={item}
getFilterInfo={getFilterInfo}
- getExternalLinkURL={getExternalLinkURL}
+ getExternalLinkUrl={getExternalLinkUrl}
renderIcon={renderIcon}
/>
)
@@ -167,8 +159,9 @@ export default function BreakdownModal<TListItem extends { name: string }>({
orderByDictionary,
toggleSortByMetric,
renderIcon,
- getExternalLinkURL,
- meta
+ getExternalLinkUrl,
+ meta,
+ site
]
)
@@ -193,25 +186,25 @@ const NameCell = <TListItem extends { name: string }>({
item,
getFilterInfo,
renderIcon,
- getExternalLinkURL
+ getExternalLinkUrl
}: {
item: TListItem
- getFilterInfo: (item: TListItem) => unknown | null
- renderIcon?: (item: TListItem) => unknown
- getExternalLinkURL?: (listItem: TListItem) => string
+ getFilterInfo: (item: TListItem) => FilterInfo | null
+ renderIcon?: (item: TListItem) => ReactNode
+ getExternalLinkUrl?: (listItem: TListItem) => string
}) => (
<>
{typeof renderIcon === 'function' && renderIcon(item)}
- <FilterLink
+ <DrilldownLink
path={rootRoute.path}
filterInfo={getFilterInfo(item)}
onClick={undefined}
extraClass={undefined}
>
{item.name}
- </FilterLink>
- {typeof getExternalLinkURL === 'function' && (
- <ExternalLinkIcon url={getExternalLinkURL(item)} />
+ </DrilldownLink>
+ {typeof getExternalLinkUrl === 'function' && (
+ <ExternalLinkIcon url={getExternalLinkUrl(item)} />
)}
</>
)
diff --git a/assets/js/dashboard/stats/pages/index.js b/assets/js/dashboard/stats/pages/index.js
index 6f80f1ac77..6d50cdb77a 100644
--- a/assets/js/dashboard/stats/pages/index.js
+++ b/assets/js/dashboard/stats/pages/index.js
@@ -18,11 +18,11 @@ function EntryPages({ afterFetchData }) {
return api.get(url.apiPath(site, '/entry-pages'), query, { limit: 9 })
}
- function externalLinkDest(page) {
+ function getExternalLinkUrl(page) {
return url.externalLinkForPage(site.domain, page.name)
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: 'entry_page',
filter: ["is", "entry_page", [listItem['name']]]
@@ -40,11 +40,11 @@ function EntryPages({ afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Entry page"
metrics={chooseMetrics()}
detailsLinkProps={{ path: entryPagesRoute.path, search: (search) => search }}
- externalLinkDest={externalLinkDest}
+ getExternalLinkUrl={getExternalLinkUrl}
color="bg-orange-50"
/>
)
@@ -57,11 +57,11 @@ function ExitPages({ afterFetchData }) {
return api.get(url.apiPath(site, '/exit-pages'), query, { limit: 9 })
}
- function externalLinkDest(page) {
+ function getExternalLinkUrl(page) {
return url.externalLinkForPage(site.domain, page.name)
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: 'exit_page',
filter: ["is", "exit_page", [listItem['name']]]
@@ -79,11 +79,11 @@ function ExitPages({ afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Exit page"
metrics={chooseMetrics()}
detailsLinkProps={{ path: exitPagesRoute.path, search: (search) => search }}
- externalLinkDest={externalLinkDest}
+ getExternalLinkUrl={getExternalLinkUrl}
color="bg-orange-50"
/>
)
@@ -96,11 +96,11 @@ function TopPages({ afterFetchData }) {
return api.get(url.apiPath(site, '/pages'), query, { limit: 9 })
}
- function externalLinkDest(page) {
+ function getExternalLinkUrl(page) {
return url.externalLinkForPage(site.domain, page.name)
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: 'page',
filter: ["is", "page", [listItem['name']]]
@@ -118,11 +118,11 @@ function TopPages({ afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Page"
metrics={chooseMetrics()}
detailsLinkProps={{ path: topPagesRoute.path, search: (search) => search }}
- externalLinkDest={externalLinkDest}
+ getExternalLinkUrl={getExternalLinkUrl}
color="bg-orange-50"
/>
)
diff --git a/assets/js/dashboard/stats/reports/list.js b/assets/js/dashboard/stats/reports/list.tsx
similarity index 58%
rename from assets/js/dashboard/stats/reports/list.js
rename to assets/js/dashboard/stats/reports/list.tsx
index a4bafc1ed7..c1367379df 100644
--- a/assets/js/dashboard/stats/reports/list.js
+++ b/assets/js/dashboard/stats/reports/list.tsx
@@ -1,23 +1,22 @@
/** @format */
-import React, { useState, useEffect, useCallback } from 'react'
-import { AppNavigationLink } from '../../navigation/use-app-navigate'
+import React, { useState, useEffect, useCallback, ReactNode } from 'react'
+import { AppNavigationLinkProps } from '../../navigation/use-app-navigate'
import FlipMove from 'react-flip-move'
import FadeIn from '../../fade-in'
import MoreLink from '../more-link'
import Bar from '../bar'
import LazyLoader from '../../components/lazy-loader'
-import classNames from 'classnames'
import { trimURL } from '../../util/url'
import {
- cleanLabels,
- replaceFilterByPrefix,
isRealTimeDashboard,
hasConversionGoalFilter
} from '../../util/filters'
-import { plainFilterText } from '../../util/filter-text'
import { useQueryContext } from '../../query-context'
+import { Metric } from './metrics'
+import { DrilldownLink, FilterInfo } from '../../components/drilldown-link'
+import { BreakdownResultMeta } from '../../query'
const MAX_ITEMS = 9
export const MIN_HEIGHT = 380
@@ -27,45 +26,14 @@ const DATA_CONTAINER_HEIGHT =
(ROW_HEIGHT + ROW_GAP_HEIGHT) * (MAX_ITEMS - 1) + ROW_HEIGHT
const COL_MIN_WIDTH = 70
-export function FilterLink({
- path,
- filterInfo,
- onClick,
- children,
- extraClass
+function ExternalLink<T>({
+ item,
+ getExternalLinkUrl
+}: {
+ item: T
+ getExternalLinkUrl?: (item: T) => string
}) {
- const { query } = useQueryContext()
- const className = classNames(`${extraClass}`, {
- 'hover:underline': !!filterInfo
- })
-
- if (filterInfo) {
- const { prefix, filter, labels } = filterInfo
- const newFilters = replaceFilterByPrefix(query, prefix, filter)
- const newLabels = cleanLabels(newFilters, query.labels, filter[1], labels)
-
- return (
- <AppNavigationLink
- title={`Add filter: ${plainFilterText({ ...query, labels: newLabels }, filter)}`}
- className={className}
- path={path}
- onClick={onClick}
- search={(search) => ({
- ...search,
- filters: newFilters,
- labels: newLabels
- })}
- >
- {children}
- </AppNavigationLink>
- )
- } else {
- return <span className={className}>{children}</span>
- }
-}
-
-function ExternalLink({ item, externalLinkDest }) {
- const dest = externalLinkDest && externalLinkDest(item)
+ const dest = getExternalLinkUrl && getExternalLinkUrl(item)
if (dest) {
return (
<a
@@ -89,51 +57,60 @@ function ExternalLink({ item, externalLinkDest }) {
return null
}
+export interface SharedReportProps<
+ TListItem extends Record<string, unknown> = Record<string, unknown>,
+ TResponse = { results: TListItem[]; meta: BreakdownResultMeta }
+> {
+ metrics: Metric[]
+ /** A function that takes a list item and returns the filter
+ * that should be applied when the list item is clicked. All existing filters matching prefix
+ * are removed. If a list item is not supposed to be clickable, this function should
+ * return `null` for that list item. */
+ getFilterInfo: (item: TListItem) => FilterInfo | null
+ /** A function that takes a list item and returns the HTML of an icon */
+ renderIcon?: (item: TListItem) => ReactNode
+ /** A function that takes a list item and returns an external URL
+ * to navigate to. If this prop is given, an additional icon is rendered upon hovering
+ * the entry. */
+ getExternalLinkUrl?: (item: TListItem) => string
+ /** A function that defines the data
+ * to be rendered, and should return a list of objects under a `results` key. Think of
+ * these objects as rows. The number of columns that are **actually rendered** is also
+ * configurable through the `metrics` prop, which also defines the keys under which
+ * column values are read, and how they're rendered. */
+ fetchData: () => Promise<TResponse>
+ afterFetchData?: (response: TResponse) => void
+ afterFetchNextPage?: (response: TResponse) => void
+}
+
+type ListReportProps = {
+ /** What each entry in the list represents (for UI only). */
+ keyLabel: string
+ metrics: Metric[]
+ colMinWidth?: number
+ /** Navigation props to be passed to "More" link, if any. */
+ detailsLinkProps?: AppNavigationLinkProps
+ /** Set this to `true` if the details button should be hidden on
+ * the condition that there are less than MAX_ITEMS entries in the list (i.e. nothing
+ * more to show).
+ */
+ maybeHideDetails?: boolean
+ /** Function with additional action to be taken when a list entry is clicked. */
+ onClick?: () => void
+ /** Color of the comparison bars in light-mode. */
+ color?: string
+}
+
/**
- *
- * REQUIRED PROPS
- *
- * @param {Function} fetchData - A function that defines the data
- * to be rendered, and should return a list of objects under a `results` key. Think of
- * these objects as rows. The number of columns that are **actually rendered** is also
- * configurable through the `metrics` prop, which also defines the keys under which
- * column values are read, and how they're rendered.
- * @param {*} keyLabel - What each entry in the list represents (for UI only).
- * @param {Array.<Metric>} metrics - A list of `Metric` class objects, containing at least the `key,`
- * `renderLabel`, and `renderValue` fields. Optionally, a Metric object can contain
- * the keys `meta.plot` and `meta.hiddenOnMobile` to represent additional behavior
- * for this metric in the ListReport.
- * @param {Function} getFilterFor - A function that takes a list item and returns [prefix, filter, labels]
- * that should be applied when the list item is clicked. All existing filters matching prefix
- * are removed. If a list item is not supposed to be clickable, this function should
- * return `null` for that list item.
- *
- * OPTIONAL PROPS
- *
- * @param {Function} [onClick] - Function with additional action to be taken when a list entry is clicked.
- * @param {Object} [detailsLinkProps] - Navigation props to be passed to "More" link, if any.
- * @param {boolean} [maybeHideDetails] - Set this to `true` if the details button should be hidden on
- * the condition that there are less than MAX_ITEMS entries in the list (i.e. nothing
- * more to show).
- * @param {Function} [externalLinkDest] - A function that takes a list item and returns an external URL
- * to navigate to. If this prop is given, an additional icon is rendered upon hovering
- * the entry.
- * @param {Function} [renderIcon] - A function that takes a list item and returns the
- * HTML of an icon (such as a flag, favicon, or a screen size icon) for a list item.
- * @param {string} [color] - Color of the comparison bars in light-mode.
- * @param {Function} [afterFetchData] - A function to be called directly after `fetchData`. Receives the
- * raw API response as an argument. The return value is ignored by ListReport. Allows
- * hooking into the request lifecycle and doing actions with returned metadata. For
- * example, the parent component might want to control what happens when imported data
- * is included or not.
- *
* @returns {HTMLElement} Table of metrics, in the following format:
* | keyLabel | METRIC_1.renderLabel(query) | METRIC_2.renderLabel(query) | ...
* |--------------------|-----------------------------|-----------------------------| ---
* | LISTITEM_1.name | LISTITEM_1[METRIC_1.key] | LISTITEM_1[METRIC_2.key] | ...
* | LISTITEM_2.name | LISTITEM_2[METRIC_1.key] | LISTITEM_2[METRIC_2.key] | ...
*/
-export default function ListReport({
+export default function ListReport<
+ TListItem extends Record<string, unknown> & { name: string }
+>({
keyLabel,
metrics,
colMinWidth = COL_MIN_WIDTH,
@@ -142,13 +119,17 @@ export default function ListReport({
maybeHideDetails,
onClick,
color,
- getFilterFor,
+ getFilterInfo,
renderIcon,
- externalLinkDest,
+ getExternalLinkUrl,
fetchData
-}) {
+}: Omit<SharedReportProps<TListItem>, 'afterFetchNextPage'> & ListReportProps) {
const { query } = useQueryContext()
- const [state, setState] = useState({ loading: true, list: null, meta: null })
+ const [state, setState] = useState<{
+ loading: boolean
+ list: TListItem[] | null
+ meta: BreakdownResultMeta | null
+ }>({ loading: true, list: null, meta: null })
const [visible, setVisible] = useState(false)
const isRealtime = isRealTimeDashboard(query)
@@ -200,12 +181,14 @@ export default function ListReport({
// metrics based on filters and existing data, this function validates that the metrics
// we want to display are actually there in the API response.
function getAvailableMetrics() {
- return metrics.filter((metric) => {
- return state.list.some((listItem) => listItem[metric.key] != null)
- })
+ return metrics.filter((metric) =>
+ state.list
+ ? state.list.some((listItem) => listItem[metric.key] != null)
+ : false
+ )
}
- function hiddenOnMobileClass(metric) {
+ function hiddenOnMobileClass(metric: Metric) {
if (metric.meta.hiddenOnMobile) {
return 'hidden md:block'
} else {
@@ -220,10 +203,21 @@ export default function ListReport({
<div style={{ height: ROW_HEIGHT }}>{renderReportHeader()}</div>
<div style={{ minHeight: DATA_CONTAINER_HEIGHT }}>
- {renderReportBody()}
+ <FlipMove className="flex-grow">
+ {state.list.slice(0, MAX_ITEMS).map(renderRow)}
+ </FlipMove>
</div>
- {maybeRenderDetailsLink()}
+ {!!detailsLinkProps &&
+ !state.loading &&
+ !(maybeHideDetails && !(state.list.length >= MAX_ITEMS)) && (
+ <MoreLink
+ onClick={undefined}
+ className={'mt-2'}
+ linkProps={detailsLinkProps}
+ list={state.list}
+ />
+ )}
</div>
)
}
@@ -251,15 +245,7 @@ export default function ListReport({
)
}
- function renderReportBody() {
- return (
- <FlipMove className="flex-grow">
- {state.list.slice(0, MAX_ITEMS).map(renderRow)}
- </FlipMove>
- )
- }
-
- function renderRow(listItem) {
+ function renderRow(listItem: TListItem) {
return (
<div key={listItem.name} style={{ minHeight: ROW_HEIGHT }}>
<div className="flex w-full" style={{ marginTop: ROW_GAP_HEIGHT }}>
@@ -270,21 +256,22 @@ export default function ListReport({
)
}
- function renderBarFor(listItem) {
+ function renderBarFor(listItem: TListItem) {
const lightBackground = color || 'bg-green-50'
- const metricToPlot = metrics.find((metric) => metric.meta.plot).key
+ const metricToPlot = metrics.find((metric) => metric.meta.plot)?.key
return (
<div className="flex-grow w-full overflow-hidden">
<Bar
+ maxWidthDeduction={undefined}
count={listItem[metricToPlot]}
all={state.list}
bg={`${lightBackground} dark:bg-gray-500 dark:bg-opacity-15`}
plot={metricToPlot}
>
<div className="flex justify-start px-2 py-1.5 group text-sm dark:text-gray-300 relative z-9 break-all w-full">
- <FilterLink
- filterInfo={getFilterFor(listItem)}
+ <DrilldownLink
+ filterInfo={getFilterInfo(listItem)}
onClick={onClick}
extraClass="max-w-max w-full flex items-center md:overflow-hidden"
>
@@ -293,21 +280,24 @@ export default function ListReport({
<span className="w-full md:truncate">
{trimURL(listItem.name, colMinWidth)}
</span>
- </FilterLink>
- <ExternalLink item={listItem} externalLinkDest={externalLinkDest} />
+ </DrilldownLink>
+ <ExternalLink
+ item={listItem}
+ getExternalLinkUrl={getExternalLinkUrl}
+ />
</div>
</Bar>
</div>
)
}
- function maybeRenderIconFor(listItem) {
+ function maybeRenderIconFor(listItem: TListItem) {
if (renderIcon) {
return renderIcon(listItem)
}
}
- function renderMetricValuesFor(listItem) {
+ function renderMetricValuesFor(listItem: TListItem) {
return getAvailableMetrics().map((metric) => {
return (
<div
@@ -349,22 +339,6 @@ export default function ListReport({
)
}
- function maybeRenderDetailsLink() {
- const moreResultsAvailable = state.list.length >= MAX_ITEMS
- const hideDetails = maybeHideDetails && !moreResultsAvailable
-
- const showDetails = !!detailsLinkProps && !state.loading && !hideDetails
- return (
- showDetails && (
- <MoreLink
- className={'mt-2'}
- linkProps={detailsLinkProps}
- list={state.list}
- />
- )
- )
- }
-
return (
<LazyLoader onVisible={onVisible}>
<div className="w-full" style={{ minHeight: `${MIN_HEIGHT}px` }}>
diff --git a/assets/js/dashboard/stats/sources/referrer-list.js b/assets/js/dashboard/stats/sources/referrer-list.js
index d21324d8ef..38f881f4f1 100644
--- a/assets/js/dashboard/stats/sources/referrer-list.js
+++ b/assets/js/dashboard/stats/sources/referrer-list.js
@@ -28,12 +28,12 @@ export default function Referrers({ source }) {
setSkipImportedReason(apiResponse.skip_imported_reason)
}
- function externalLinkDest(referrer) {
+ function getExternalLinkUrl(referrer) {
if (referrer.name === NO_REFERRER) { return null }
return `https://${referrer.name}`
}
- function getFilterFor(referrer) {
+ function getFilterInfo(referrer) {
if (referrer.name === NO_REFERRER) { return null }
return {
@@ -69,11 +69,11 @@ export default function Referrers({ source }) {
<ListReport
fetchData={fetchReferrers}
afterFetchData={afterFetchReferrers}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Referrer"
metrics={chooseMetrics()}
detailsLinkProps={{ path: referrersDrilldownRoute.path, params: {referrer: url.maybeEncodeRouteParam(source)}, search: (search) => search }}
- externalLinkDest={externalLinkDest}
+ getExternalLinkUrl={getExternalLinkUrl}
renderIcon={renderIcon}
color="bg-blue-50"
/>
diff --git a/assets/js/dashboard/stats/sources/source-list.js b/assets/js/dashboard/stats/sources/source-list.js
index 5b750ee6e2..97340c2276 100644
--- a/assets/js/dashboard/stats/sources/source-list.js
+++ b/assets/js/dashboard/stats/sources/source-list.js
@@ -31,7 +31,7 @@ function AllSources({ afterFetchData }) {
return api.get(url.apiPath(site, '/sources'), query, { limit: 9 })
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: 'source',
filter: ["is", "source", [listItem['name']]]
@@ -59,7 +59,7 @@ function AllSources({ afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Source"
metrics={chooseMetrics()}
detailsLinkProps={{ path: sourcesRoute.path, search: (search) => search }}
@@ -77,7 +77,7 @@ function Channels({ onClick, afterFetchData }) {
return api.get(url.apiPath(site, '/channels'), query, { limit: 9 })
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: 'channel',
filter: ["is", "channel", [listItem['name']]]
@@ -95,7 +95,7 @@ function Channels({ onClick, afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel="Channel"
onClick={onClick}
metrics={chooseMetrics()}
@@ -122,7 +122,7 @@ function UTMSources({ tab, afterFetchData }) {
return api.get(url.apiPath(site, utmTag.endpoint), query, { limit: 9 })
}
- function getFilterFor(listItem) {
+ function getFilterInfo(listItem) {
return {
prefix: tab,
filter: ["is", tab, [listItem['name']]]
@@ -140,7 +140,7 @@ function UTMSources({ tab, afterFetchData }) {
<ListReport
fetchData={fetchData}
afterFetchData={afterFetchData}
- getFilterFor={getFilterFor}
+ getFilterInfo={getFilterInfo}
keyLabel={utmTag.label}
metrics={chooseMetrics()}
detailsLinkProps={{ path: route?.path, search: (search) => search }}