Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Full custom metrics support

Blue Mouse57b4727b5e87
diff --git a/app/pages/Project/View/ViewProject.tsx b/app/pages/Project/View/ViewProject.tsx
index 59ad1c05f..5a713b9e1 100644
--- a/app/pages/Project/View/ViewProject.tsx
+++ b/app/pages/Project/View/ViewProject.tsx
@@ -51,7 +51,7 @@ import { withProjectProtected } from 'hoc/projectProtected'
import { periodToCompareDate } from 'utils/compareConvertDate'
-import { getTimeFromSeconds, getStringFromTime, getLocaleDisplayName } from 'utils/generic'
+import { getTimeFromSeconds, getStringFromTime, getLocaleDisplayName, nLocaleFormatter } from 'utils/generic'
import { getItem, setItem, removeItem } from 'utils/localstorage'
import EventsRunningOutBanner from 'components/EventsRunningOutBanner'
import {
@@ -201,7 +201,7 @@ import NoSessionDetails from './components/NoSessionDetails'
import {
ICustoms,
IFilter,
- IMetric,
+ ITrafficMeta,
IParams,
IProjectView,
IProjectViewCustomEvent,
@@ -377,7 +377,7 @@ const ViewProject = ({
data: IParams
customs: ICustoms
properties: IProperties
- meta?: IMetric[]
+ meta?: ITrafficMeta[]
// @ts-expect-error
}>({})
const [overall, setOverall] = useState<Partial<IOverallObject>>({})
@@ -2417,6 +2417,26 @@ const ViewProject = ({
loadAnalytics(true, null, metrics)
}
+ const onRemoveCustomMetric = (metricId: IProjectViewCustomEvent['id']) => {
+ if (activeTab !== PROJECT_TABS.traffic) {
+ return
+ }
+
+ const newMetrics = _filter(customMetrics, (metric) => metric.id !== metricId)
+
+ setCustomMetrics(newMetrics)
+ loadAnalytics(true, null, newMetrics)
+ }
+
+ const resetCustomMetrics = () => {
+ if (activeTab !== PROJECT_TABS.traffic) {
+ return
+ }
+
+ setCustomMetrics([])
+ loadAnalytics(true, null, [])
+ }
+
// this function is used for requesting the data from the API when the exclusive filter is changed
const onChangeExclusive = (column: string, filter: string, isExclusive: boolean) => {
let newFilters
@@ -4653,10 +4673,26 @@ const ViewProject = ({
activePeriodCompare={activePeriodCompare}
/>
{!_isEmpty(panelsData.meta) &&
- _map(panelsData.meta, ({ key, sum, avg }) => (
+ _map(panelsData.meta, ({ key, current, previous }) => (
<React.Fragment key={key}>
- <MetricCard label={t('project.metrics.xAvg', { x: key })} value={avg} />
- <MetricCard label={t('project.metrics.xTotal', { x: key })} value={sum} />
+ <MetricCard
+ label={t('project.metrics.xAvg', { x: key })}
+ value={current.avg}
+ change={current.avg - previous.avg}
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
+ }
+ />
+ <MetricCard
+ label={t('project.metrics.xTotal', { x: key })}
+ value={current.sum}
+ change={current.sum - previous.sum}
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
+ }
+ />
</React.Fragment>
))}
</div>
@@ -4675,7 +4711,11 @@ const ViewProject = ({
tnMapping={tnMapping}
resetFilters={resetActiveTabFilters}
/>
- <CustomMetrics metrics={customMetrics} onRemoveMetric={() => {}} resetMetrics={() => {}} />
+ <CustomMetrics
+ metrics={customMetrics}
+ onRemoveMetric={(id) => onRemoveCustomMetric(id)}
+ resetMetrics={resetCustomMetrics}
+ />
{dataLoading && (
<div className='static mt-4 !bg-transparent' id='loader'>
<div className='loader-head dark:!bg-slate-800'>
diff --git a/app/pages/Project/View/components/AddAViewModal.tsx b/app/pages/Project/View/components/AddAViewModal.tsx
index 2f6fe7fcc..11056bbde 100644
--- a/app/pages/Project/View/components/AddAViewModal.tsx
+++ b/app/pages/Project/View/components/AddAViewModal.tsx
@@ -194,6 +194,8 @@ interface AddAViewModalErrors {
[key: `${string}_${keyof IProjectViewCustomEvent}`]: string | undefined
}
+const MAX_METRICS_IN_VIEW = 3
+
const AddAViewModal = ({
onSubmit,
pid,
@@ -470,12 +472,14 @@ const AddAViewModal = ({
/>
))}
</div>
- <InlineButton
- text={t('project.addAMetric')}
- onClick={() => {
- setCustomEvents((prev) => [...prev, { ...EMPTY_CUSTOM_EVENT, id: Math.random().toString() }])
- }}
- />
+ {customEvents.length < MAX_METRICS_IN_VIEW && (
+ <InlineButton
+ text={t('project.addAMetric')}
+ onClick={() => {
+ setCustomEvents((prev) => [...prev, { ...EMPTY_CUSTOM_EVENT, id: Math.random().toString() }])
+ }}
+ />
+ )}
</div>
}
submitType='regular'
diff --git a/app/pages/Project/View/components/CustomMetrics.tsx b/app/pages/Project/View/components/CustomMetrics.tsx
index c3dccba37..d52a126eb 100644
--- a/app/pages/Project/View/components/CustomMetrics.tsx
+++ b/app/pages/Project/View/components/CustomMetrics.tsx
@@ -1,120 +1,73 @@
-import { FunnelIcon, XMarkIcon } from '@heroicons/react/24/outline'
-import React, { memo } from 'react'
-import cx from 'clsx'
-import _truncate from 'lodash/truncate'
+import { ScaleIcon, XMarkIcon } from '@heroicons/react/24/outline'
+import React, { memo, useMemo } from 'react'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
-import _startsWith from 'lodash/startsWith'
-import _replace from 'lodash/replace'
import { useTranslation } from 'react-i18next'
-import countries from 'utils/isoCountries'
-import { getLocaleDisplayName } from 'utils/generic'
import { IProjectViewCustomEvent } from '../interfaces/traffic'
-interface IFilter {
- column: string
- filter: string
- isExclusive: boolean
- // eslint-disable-next-line no-shadow
- onRemoveFilter: (column: string, filter: string) => void
- // eslint-disable-next-line no-shadow
- onChangeExclusive: (column: string, filter: string, isExclusive: boolean) => void
- tnMapping: Record<string, string>
- canChangeExclusive?: boolean
- removable?: boolean
+interface ICustomMetric {
+ metric: IProjectViewCustomEvent
+ onRemove: () => void
}
-export const Filter = ({
- column,
- filter,
- isExclusive,
- onRemoveFilter,
- onChangeExclusive,
- tnMapping,
- canChangeExclusive,
- removable,
-}: IFilter): JSX.Element => {
- const {
- t,
- i18n: { language },
- } = useTranslation('common')
+const CustomMetric = ({ metric, onRemove }: ICustomMetric): JSX.Element => {
+ const { t } = useTranslation('common')
- let displayColumn = tnMapping[column]
- let displayFilter = filter
+ const displayValue = useMemo(() => {
+ const { customEventName, metaKey, metaValue, metricKey } = metric
- if (column === 'cc') {
- displayFilter = countries.getName(filter, language) as string
- }
-
- if (column === 'pg') {
- displayFilter = filter || t('project.redactedPage')
- }
+ if (metaKey && metaValue) {
+ return t('project.metrics.filterKV', {
+ customEventName,
+ metaKey,
+ metaValue,
+ metricKey,
+ })
+ }
- if (column === 'lc') {
- displayFilter = getLocaleDisplayName(displayFilter, language)
- }
+ if (metaKey) {
+ return t('project.metrics.filterK', {
+ customEventName,
+ metaKey,
+ metricKey,
+ })
+ }
- if (_startsWith(column, 'ev:key:')) {
- const key = _replace(column, /^ev:key:/, '')
- displayColumn = t('project.metamapping.ev.dynamicKey', {
- key,
- })
- }
+ if (metaValue) {
+ return t('project.metrics.filterV', {
+ customEventName,
+ metaValue,
+ metricKey,
+ })
+ }
- if (_startsWith(column, 'tag:key:')) {
- const key = _replace(column, /^tag:key:/, '')
- displayColumn = t('project.metamapping.tag.dynamicKey', {
- key,
+ return t('project.metrics.filterNoKV', {
+ customEventName,
+ metricKey,
})
- }
-
- const truncatedFilter = _truncate(displayFilter)
+ }, [t, metric])
return (
- <span
- title={truncatedFilter === displayFilter ? undefined : displayFilter}
- className={cx(
- 'm-1 inline-flex items-center rounded-md bg-gray-50 py-0.5 pl-2.5 pr-1 text-sm font-medium text-gray-800 dark:bg-slate-800 dark:text-gray-50',
- {
- 'pr-2': !removable,
- },
- )}
- >
- {displayColumn}
- &nbsp;
- {canChangeExclusive ? (
- <span
- className='cursor-pointer border-b-2 border-dotted border-blue-400 text-blue-400'
- onClick={() => onChangeExclusive(column, filter, !isExclusive)}
- >
- {t(`common.${isExclusive ? 'isNot' : 'is'}`)}
- </span>
- ) : (
- <span>{t(`common.${isExclusive ? 'isNot' : 'is'}`)}</span>
- )}
- &nbsp; &quot;
- {truncatedFilter}
- &quot;
- {removable && (
- <button
- onClick={() => onRemoveFilter(column, filter)}
- type='button'
- className='ml-0.5 inline-flex h-4 w-4 flex-shrink-0 items-center justify-center rounded-full text-gray-800 hover:bg-gray-300 hover:text-gray-900 focus:bg-gray-300 focus:text-gray-900 focus:outline-none dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-gray-800 dark:hover:text-gray-300 dark:focus:bg-gray-800 dark:focus:text-gray-300 '
- >
- <span className='sr-only'>Remove filter</span>
- <svg className='h-2 w-2' stroke='currentColor' fill='none' viewBox='0 0 8 8'>
- <path strokeLinecap='round' strokeWidth='1.5' d='M1 1l6 6m0-6L1 7' />
- </svg>
- </button>
- )}
+ <span className='m-1 inline-flex items-center rounded-md bg-gray-50 py-0.5 pl-2.5 pr-1 text-sm font-medium text-gray-800 dark:bg-slate-800 dark:text-gray-50'>
+ {displayValue}
+ <button
+ onClick={onRemove}
+ type='button'
+ className='ml-0.5 inline-flex h-4 w-4 flex-shrink-0 items-center justify-center rounded-full text-gray-800 hover:bg-gray-300 hover:text-gray-900 focus:bg-gray-300 focus:text-gray-900 focus:outline-none dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-gray-800 dark:hover:text-gray-300 dark:focus:bg-gray-800 dark:focus:text-gray-300 '
+ >
+ <span className='sr-only'>Remove filter</span>
+ <svg className='h-2 w-2' stroke='currentColor' fill='none' viewBox='0 0 8 8'>
+ <path strokeLinecap='round' strokeWidth='1.5' d='M1 1l6 6m0-6L1 7' />
+ </svg>
+ </button>
</span>
)
}
interface IFilters {
metrics: IProjectViewCustomEvent[]
- onRemoveMetric: (column: string, filter: string) => void
+ onRemoveMetric: (id: IProjectViewCustomEvent['id']) => void
resetMetrics: () => void
}
@@ -124,13 +77,19 @@ const CustomMetrics = ({ metrics, onRemoveMetric, resetMetrics }: IFilters) => {
}
return (
- <div className='flex items-center justify-between rounded-md bg-slate-200 p-1 shadow dark:border dark:border-slate-800/50 dark:bg-slate-800/25'>
+ <div className='mt-2 flex items-center justify-between rounded-md bg-slate-200 p-1 shadow dark:border dark:border-slate-800/50 dark:bg-slate-800/25'>
<div className=' flex items-center'>
- <FunnelIcon className='box-content size-6 flex-shrink-0 px-1 text-gray-700 dark:text-gray-200' />
+ <ScaleIcon className='box-content size-6 flex-shrink-0 px-1 text-gray-700 dark:text-gray-200' />
<div className='flex flex-wrap'>
- {_map(metrics, (props) => {
- return <div key={JSON.stringify(props)}>{JSON.stringify(props)}</div>
- })}
+ {_map(metrics, (metric) => (
+ <CustomMetric
+ key={metric.id}
+ metric={metric}
+ onRemove={() => {
+ onRemoveMetric(metric.id)
+ }}
+ />
+ ))}
</div>
</div>
<XMarkIcon
diff --git a/app/pages/Project/View/interfaces/traffic.tsx b/app/pages/Project/View/interfaces/traffic.tsx
index f275736fe..955ee0b58 100644
--- a/app/pages/Project/View/interfaces/traffic.tsx
+++ b/app/pages/Project/View/interfaces/traffic.tsx
@@ -43,12 +43,17 @@ export interface IProperties {
[key: string]: number
}
-export interface IMetric {
- key: string
+interface IMetric {
sum: number
avg: number
}
+export interface ITrafficMeta {
+ key: string
+ current: IMetric
+ previous: IMetric
+}
+
export interface ITrafficLogResponse {
params?: IParams
chart?: {
@@ -61,5 +66,5 @@ export interface ITrafficLogResponse {
properties: IProperties
appliedFilters?: IFilter[]
timeBucket?: string[]
- meta?: IMetric[]
+ meta?: ITrafficMeta[]
}
diff --git a/app/utils/generic.ts b/app/utils/generic.ts
index a220f79b2..c24048d95 100644
--- a/app/utils/generic.ts
+++ b/app/utils/generic.ts
@@ -21,6 +21,14 @@ export const nFormatter = (num: any, digits = 1) => {
return item ? _replace((num / item.value).toFixed(digits), rx, '$1') + item.symbol : '0'
}
+export const nLocaleFormatter = (num: number): string => {
+ if (!Intl.NumberFormat) {
+ return num.toString()
+ }
+
+ return new Intl.NumberFormat().format(num)
+}
+
// returns something like [123, 'k'], [5.5, 'M'], [425, null]
export const nFormatterSeparated = (num: any, digits = 1) => {
const item = _find(formatterLookup.slice().reverse(), ({ value }) => num >= value)
diff --git a/public/locales/en.json b/public/locales/en.json
index 595aff29f..5b1171b6b 100644
--- a/public/locales/en.json
+++ b/public/locales/en.json
@@ -803,7 +803,11 @@
"optinalEventValue": {
"title": "Event value (optional)",
"description": "Custom event metadata value to filter (for example, \"GBP\")."
- }
+ },
+ "filterNoKV": "For \"{{customEventName}}\" aggregate \"{{metricKey}}\"",
+ "filterK": "For \"{{customEventName}}\" aggregate \"{{metricKey}}\" where any key is \"{{metaKey}}\"",
+ "filterV": "For \"{{customEventName}}\" aggregate \"{{metricKey}}\" where any value is \"{{metaValue}}\"",
+ "filterKV": "For \"{{customEventName}}\" aggregate \"{{metricKey}}\" where key \"{{metaKey}}\" is \"{{metaValue}}\""
},
"metaValueType": {
"decimal": "Decimal",