Skip to content

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

Fix special reports (#5985)

Artur Pata0d3ba515fe6b
diff --git a/assets/js/dashboard/components/notice.js b/assets/js/dashboard/components/notice.js
index e3e3520d2f..df5b007d36 100644
--- a/assets/js/dashboard/components/notice.js
+++ b/assets/js/dashboard/components/notice.js
@@ -1,5 +1,5 @@
import React from 'react'
-import { sectionTitles } from '../stats/behaviours'
+import { MODES } from '../stats/behaviours/modes-context'
import * as api from '../api'
import { useSiteContext } from '../site-context'
@@ -11,7 +11,7 @@ export function FeatureSetupNotice({
onHideAction
}) {
const site = useSiteContext()
- const sectionTitle = sectionTitles[feature]
+ const sectionTitle = MODES[feature].title
const requestHideSection = () => {
if (
diff --git a/assets/js/dashboard/stats/behaviours/index.js b/assets/js/dashboard/stats/behaviours/index.js
index f76670733c..93d99ea674 100644
--- a/assets/js/dashboard/stats/behaviours/index.js
+++ b/assets/js/dashboard/stats/behaviours/index.js
@@ -1,10 +1,6 @@
import React, { useState, useEffect, useCallback } from 'react'
import * as storage from '../../util/storage'
import ImportedQueryUnsupportedWarning from '../imported-query-unsupported-warning'
-import GoalConversions, {
- specialTitleWhenGoalFilter,
- SPECIAL_GOALS
-} from './goal-conversions'
import Properties from './props'
import { FeatureSetupNotice } from '../../components/notice'
import {
@@ -24,6 +20,15 @@ import { Pill } from '../../components/pill'
import * as api from '../../api'
import * as url from '../../util/url'
import { conversionsRoute, customPropsRoute } from '../../router'
+import {
+ Mode,
+ getFirstPreferenceFromEnabledModes,
+ ModesContextProvider,
+ useModesContext
+} from './modes-context'
+import { SpecialGoalPropBreakdown } from './special-goal-prop-breakdown'
+import Conversions from './conversions'
+import { getSpecialGoal, isPageViewGoal, isSpecialGoal } from '../../util/goals'
/*global BUILD_EXTRA*/
/*global require*/
@@ -38,68 +43,90 @@ function maybeRequire() {
const Funnel = maybeRequire().default
-export const CONVERSIONS = 'conversions'
-export const PROPS = 'props'
-export const FUNNELS = 'funnels'
+function singleGoalFilterApplied(query) {
+ const goalFilter = getGoalFilter(query)
+ if (goalFilter) {
+ const [operation, _filterKey, clauses] = goalFilter
+ return operation === FILTER_OPERATIONS.is && clauses.length === 1
+ } else {
+ return false
+ }
+}
+
+const STORAGE_KEYS = {
+ getForTab: ({ site }) =>
+ storage.getDomainScopedStorageKey('behavioursTab', site.domain),
+ getForFunnel: ({ site }) =>
+ storage.getDomainScopedStorageKey('behavioursTabFunnel', site.domain),
+ getForPropKey: ({ site }) =>
+ storage.getDomainScopedStorageKey('prop_key', site.domain),
+ getForPropKeyForGoal: ({ goalName, site }) => {
+ return storage.getDomainScopedStorageKey(
+ `${goalName}__prop_key)`,
+ site.domain
+ )
+ }
+}
+
+function getPropKeyFromStorage({ site, query }) {
+ if (singleGoalFilterApplied(query)) {
+ const [_operation, _dimension, [goalName]] = getGoalFilter(query)
+ const storedForGoal = storage.getItem(
+ STORAGE_KEYS.getForPropKeyForGoal({ goalName, site })
+ )
+ if (storedForGoal) {
+ return storedForGoal
+ }
+ }
-export const sectionTitles = {
- [CONVERSIONS]: 'Goal conversions',
- [PROPS]: 'Custom properties',
- [FUNNELS]: 'Funnels'
+ return storage.getItem(STORAGE_KEYS.getForPropKey({ site }))
}
-export default function Behaviours({ importedDataInView }) {
+function storePropKey({ site, propKey, query }) {
+ if (singleGoalFilterApplied(query)) {
+ const [_operation, _dimension, [goalName]] = getGoalFilter(query)
+ storage.setItem(
+ STORAGE_KEYS.getForPropKeyForGoal({ goalName, site }),
+ propKey
+ )
+ } else {
+ storage.setItem(STORAGE_KEYS.getForPropKey({ site }), propKey)
+ }
+}
+
+function getDefaultSelectedFunnel({ site }) {
+ const stored = storage.getItem(STORAGE_KEYS.getForFunnel({ site }))
+ const storedExists = stored && site.funnels.some((f) => f.name === stored)
+
+ if (storedExists) {
+ return stored
+ } else if (site.funnels.length > 0) {
+ const firstAvailable = site.funnels[0].name
+ storage.setItem(STORAGE_KEYS.getForFunnel({ site }), firstAvailable)
+ return firstAvailable
+ }
+}
+
+function Behaviours({ importedDataInView, setMode, mode }) {
const { query } = useQueryContext()
+ const goalFilter = getGoalFilter(query)
+ const specialGoal = goalFilter ? getSpecialGoal(goalFilter) : null
const site = useSiteContext()
const user = useUserContext()
+ const { enabledModes, disableMode } = useModesContext()
const adminAccess = ['owner', 'admin', 'editor', 'super_admin'].includes(
user.role
)
- const tabKey = storage.getDomainScopedStorageKey('behavioursTab', site.domain)
- const funnelKey = storage.getDomainScopedStorageKey(
- 'behavioursTabFunnel',
- site.domain
- )
- const propKeyStorageName = `prop_key__${site.domain}`
- const propKeyStorageNameForGoal = () => {
- const [_operation, _filterKey, [goal]] = getGoalFilter(query)
- return `${goal}__prop_key__${site.domain}`
- }
- const [enabledModes, setEnabledModes] = useState(getEnabledModes())
- const [mode, setMode] = useState(defaultMode())
const [loading, setLoading] = useState(true)
- const [selectedFunnel, setSelectedFunnel] = useState(defaultSelectedFunnel())
- const [propertyKeys, setPropertyKeys] = useState([])
- // Initialize selectedPropKey from storage immediately to show dropdown on page refresh
- const [selectedPropKey, setSelectedPropKey] = useState(() => {
- // Inline storage logic to avoid dependency on functions defined later
- const goalFilter = getGoalFilter(query)
- let stored = null
-
- if (goalFilter) {
- const [operation, _filterKey, clauses] = goalFilter
- if (operation === FILTER_OPERATIONS.is && clauses.length === 1) {
- const [goal] = clauses
- const goalStorageKey = `${goal}__prop_key__${site.domain}`
- stored = storage.getItem(goalStorageKey)
- }
- }
-
- if (!stored) {
- stored = storage.getItem(propKeyStorageName)
- }
-
- return stored || null
- })
-
- // Optimistically add selectedPropKey to propertyKeys on mount so dropdown shows immediately
- useEffect(() => {
- if (selectedPropKey && propertyKeys.length === 0) {
- setPropertyKeys([selectedPropKey])
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [])
+ const [selectedFunnel, setSelectedFunnel] = useState(
+ getDefaultSelectedFunnel({ site })
+ )
+ const initialSelectedPropKey = getPropKeyFromStorage({ site, query }) || null
+ const [selectedPropKey, setSelectedPropKey] = useState(initialSelectedPropKey)
+ const [propertyKeys, setPropertyKeys] = useState(
+ selectedPropKey !== null ? [selectedPropKey] : []
+ )
const [showingPropsForGoalFilter, setShowingPropsForGoalFilter] =
useState(false)
@@ -107,100 +134,73 @@ export default function Behaviours({ importedDataInView }) {
const [skipImportedReason, setSkipImportedReason] = useState(null)
const [moreLinkState, setMoreLinkState] = useState(MoreLinkState.LOADING)
- const onGoalFilterClick = useCallback((e) => {
- const goalName = e.target.innerHTML
- const isSpecialGoal = Object.keys(SPECIAL_GOALS).includes(goalName)
- const isPageviewGoal = goalName.startsWith('Visit ')
-
- if (
- !isSpecialGoal &&
- !isPageviewGoal &&
- enabledModes.includes(PROPS) &&
- site.hasProps
- ) {
- setShowingPropsForGoalFilter(true)
- setMode(PROPS)
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [])
+ const onGoalFilterClick = useCallback(
+ (e) => {
+ const goalName = e.target.innerHTML
+ const isSpecial = isSpecialGoal(goalName)
+ const isPageview = isPageViewGoal(goalName)
+
+ if (
+ !isSpecial &&
+ !isPageview &&
+ enabledModes.includes(Mode.PROPS) &&
+ site.hasProps
+ ) {
+ setShowingPropsForGoalFilter(true)
+ setMode(Mode.PROPS)
+ }
+ },
+ [enabledModes, setMode, site.hasProps]
+ )
useEffect(() => {
const justRemovedGoalFilter = !hasConversionGoalFilter(query)
- if (mode === PROPS && justRemovedGoalFilter && showingPropsForGoalFilter) {
+ if (
+ mode === Mode.PROPS &&
+ justRemovedGoalFilter &&
+ showingPropsForGoalFilter
+ ) {
setShowingPropsForGoalFilter(false)
- setMode(CONVERSIONS)
+ setMode(Mode.CONVERSIONS)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hasConversionGoalFilter(query)])
- useEffect(() => {
- setMode(defaultMode())
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [enabledModes])
-
useEffect(() => setLoading(true), [query, mode])
useEffect(() => {
- if (mode === PROPS && !selectedPropKey) {
+ if (mode === Mode.PROPS && !selectedPropKey) {
setMoreLinkState(MoreLinkState.HIDDEN)
} else {
setMoreLinkState(MoreLinkState.LOADING)
}
}, [query, mode, selectedPropKey])
- function disableMode(mode) {
- setEnabledModes(
- enabledModes.filter((m) => {
- return m !== mode
- })
- )
- }
-
function setFunnelFactory(selectedFunnelName) {
return () => {
- storage.setItem(tabKey, FUNNELS)
- storage.setItem(funnelKey, selectedFunnelName)
- setMode(FUNNELS)
+ storage.setItem(STORAGE_KEYS.getForTab({ site }), Mode.FUNNELS)
+ storage.setItem(STORAGE_KEYS.getForFunnel({ site }), selectedFunnelName)
+ setMode(Mode.FUNNELS)
setSelectedFunnel(selectedFunnelName)
}
}
function setPropKeyFactory(selectedPropKeyName) {
return () => {
- storage.setItem(tabKey, PROPS)
- const storageName = singleGoalFilterApplied()
- ? propKeyStorageNameForGoal()
- : propKeyStorageName
- storage.setItem(storageName, selectedPropKeyName)
- setMode(PROPS)
+ storage.setItem(STORAGE_KEYS.getForTab({ site }), Mode.PROPS)
+ storePropKey({ site, propKey: selectedPropKeyName, query })
+ setMode(Mode.PROPS)
setSelectedPropKey(selectedPropKeyName)
}
}
- function singleGoalFilterApplied() {
- const goalFilter = getGoalFilter(query)
- if (goalFilter) {
- const [operation, _filterKey, clauses] = goalFilter
- return operation === FILTER_OPERATIONS.is && clauses.length === 1
- } else {
- return false
- }
- }
-
- function getPropKeyFromStorage() {
- if (singleGoalFilterApplied()) {
- const storedForGoal = storage.getItem(propKeyStorageNameForGoal())
- if (storedForGoal) {
- return storedForGoal
- }
- }
-
- return storage.getItem(propKeyStorageName)
- }
-
useEffect(() => {
// Fetch property keys when PROPS mode is enabled (not just when active)
// This ensures the dropdown appears immediately on page refresh
- if (enabledModes.includes(PROPS) && site.hasProps && site.propsAvailable) {
+ if (
+ enabledModes.includes(Mode.PROPS) &&
+ site.hasProps &&
+ site.propsAvailable
+ ) {
api
.get(url.apiPath(site, '/suggestions/prop_key'), query, {
q: ''
@@ -209,7 +209,7 @@ export default function Behaviours({ importedDataInView }) {
const propKeyValues = propKeys.map((entry) => entry.value)
setPropertyKeys(propKeyValues)
if (propKeyValues.length > 0) {
- const stored = getPropKeyFromStorage()
+ const stored = getPropKeyFromStorage({ site, query })
const storedExists = stored && propKeyValues.includes(stored)
if (storedExists) {
@@ -217,10 +217,7 @@ export default function Behaviours({ importedDataInView }) {
} else {
const firstAvailable = propKeyValues[0]
setSelectedPropKey(firstAvailable)
- const storageName = singleGoalFilterApplied()
- ? propKeyStorageNameForGoal()
- : propKeyStorageName
- storage.setItem(storageName, firstAvailable)
+ storePropKey({ site, propKey: firstAvailable, query })
}
} else {
setSelectedPropKey(null)
@@ -236,26 +233,11 @@ export default function Behaviours({ importedDataInView }) {
setPropertyKeys([])
setSelectedPropKey(null)
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [query, enabledModes, site.hasProps, site.propsAvailable])
-
- function defaultSelectedFunnel() {
- const stored = storage.getItem(funnelKey)
- const storedExists = stored && site.funnels.some((f) => f.name === stored)
-
- if (storedExists) {
- return stored
- } else if (site.funnels.length > 0) {
- const firstAvailable = site.funnels[0].name
-
- storage.setItem(funnelKey, firstAvailable)
- return firstAvailable
- }
- }
+ }, [site, query, enabledModes])
function setTabFactory(tab) {
return () => {
- storage.setItem(tabKey, tab)
+ storage.setItem(STORAGE_KEYS.getForTab({ site }), tab)
setMode(tab)
}
}
@@ -272,16 +254,25 @@ export default function Behaviours({ importedDataInView }) {
function renderConversions() {
if (site.hasGoals) {
- return (
- <GoalConversions
- onGoalFilterClick={onGoalFilterClick}
- afterFetchData={afterFetchData}
- />
- )
+ if (specialGoal) {
+ return (
+ <SpecialGoalPropBreakdown
+ prop={specialGoal.prop}
+ afterFetchData={afterFetchData}
+ />
+ )
+ } else {
+ return (
+ <Conversions
+ onGoalFilterClick={onGoalFilterClick}
+ afterFetchData={afterFetchData}
+ />
+ )
+ }
} else if (adminAccess) {
return (
<FeatureSetupNotice
- feature={CONVERSIONS}
+ feature={Mode.CONVERSIONS}
title={'Measure how often visitors complete specific actions'}
info={
'Goals allow you to track registrations, button clicks, form completions, external link clicks, file downloads, 404 error pages and more.'
@@ -290,7 +281,7 @@ export default function Behaviours({ importedDataInView }) {
action: 'Set up goals',
link: `/${encodeURIComponent(site.domain)}/settings/goals`
}}
- onHideAction={onHideAction(CONVERSIONS)}
+ onHideAction={() => disableMode(Mode.CONVERSIONS)}
/>
)
} else {
@@ -317,13 +308,13 @@ export default function Behaviours({ importedDataInView }) {
return (
<FeatureSetupNotice
- feature={FUNNELS}
+ feature={Mode.FUNNELS}
title={'Follow the visitor journey from entry to conversion'}
info={
'Funnels allow you to analyze the user flow through your website, uncover possible issues, optimize your site and increase the conversion rate.'
}
callToAction={callToAction}
- onHideAction={onHideAction(FUNNELS)}
+ onHideAction={() => disableMode(Mode.FUNNELS)}
/>
)
} else {
@@ -350,13 +341,13 @@ export default function Behaviours({ importedDataInView }) {
return (
<FeatureSetupNotice
- feature={PROPS}
+ feature={Mode.PROPS}
title={'Send custom data to create your own metrics'}
info={
"You can attach custom properties when sending a pageview or event. This allows you to create custom metrics and analyze stats we don't track automatically."
}
callToAction={callToAction}
- onHideAction={onHideAction(PROPS)}
+ onHideAction={() => disableMode(Mode.PROPS)}
/>
)
} else {
@@ -380,50 +371,31 @@ export default function Behaviours({ importedDataInView }) {
)
}
- function onHideAction(mode) {
- return () => {
- disableMode(mode)
- }
- }
-
function renderContent() {
switch (mode) {
- case CONVERSIONS:
+ case Mode.CONVERSIONS:
return renderConversions()
- case PROPS:
+ case Mode.PROPS:
return renderProps()
- case FUNNELS:
+ case Mode.FUNNELS:
return renderFunnels()
}
}
- function defaultMode() {
- if (enabledModes.length === 0) {
- return null
- }
-
- const storedMode = storage.getItem(tabKey)
- if (storedMode && enabledModes.includes(storedMode)) {
- return storedMode
- }
-
- if (enabledModes.includes(CONVERSIONS)) {
- return CONVERSIONS
- }
- if (enabledModes.includes(PROPS)) {
- return PROPS
- }
- return FUNNELS
- }
-
- function moreLinkProps() {
+ function getMoreLinkProps() {
switch (mode) {
- case CONVERSIONS:
- return {
- path: conversionsRoute.path,
- search: (search) => search
- }
- case PROPS:
+ case Mode.CONVERSIONS:
+ return specialGoal
+ ? {
+ path: customPropsRoute.path,
+ params: { propKey: url.maybeEncodeRouteParam(specialGoal.prop) },
+ search: (search) => search
+ }
+ : {
+ path: conversionsRoute.path,
+ search: (search) => search
+ }
+ case Mode.PROPS:
if (!selectedPropKey) {
return null
}
@@ -437,26 +409,6 @@ export default function Behaviours({ importedDataInView }) {
}
}
- function getEnabledModes() {
- let enabledModes = []
-
- for (const feature of Object.keys(sectionTitles)) {
- const isOptedOut = site[feature + 'OptedOut']
- const isAvailable = site[feature + 'Available'] !== false
-
- // If the feature is not supported by the site owner's subscription,
- // it only makes sense to display the feature tab to the owner itself
- // as only they can upgrade to make the feature available.
- const callToActionIsMissing = !isAvailable && user.role !== 'owner'
-
- if (!isOptedOut && !callToActionIsMissing) {
- enabledModes.push(feature)
- }
- }
-
- return enabledModes
- }
-
function isEnabled(mode) {
return enabledModes.includes(mode)
}
@@ -466,14 +418,14 @@ export default function Behaviours({ importedDataInView }) {
}
function renderImportedQueryUnsupportedWarning() {
- if (mode === CONVERSIONS) {
+ if (mode === Mode.CONVERSIONS) {
return (
<ImportedQueryUnsupportedWarning
loading={loading}
skipImportedReason={skipImportedReason}
/>
)
- } else if (mode === PROPS) {
+ } else if (mode === Mode.PROPS) {
return (
<ImportedQueryUnsupportedWarning
loading={loading}
@@ -500,61 +452,57 @@ export default function Behaviours({ importedDataInView }) {
<ReportHeader>
<div className="flex gap-x-2">
<TabWrapper>
- {isEnabled(CONVERSIONS) && (
- <TabButton
- active={mode === CONVERSIONS}
- onClick={setTabFactory(CONVERSIONS)}
- >
- {specialTitleWhenGoalFilter(query, 'Goals')}
- </TabButton>
- )}
- {isEnabled(PROPS) &&
- ((propertyKeys.length > 0 || selectedPropKey) &&
- site.propsAvailable ? (
- <DropdownTabButton
- className="md:relative"
- transitionClassName="md:left-auto md:w-88 md:origin-top-right"
- active={mode === PROPS}
- options={
- propertyKeys.length > 0
- ? propertyKeys.map((key) => ({
- label: key,
- onClick: setPropKeyFactory(key),
- selected: mode === PROPS && selectedPropKey === key
- }))
- : selectedPropKey
- ? [
- {
- label: selectedPropKey,
- onClick: setPropKeyFactory(selectedPropKey),
- selected: true
- }
- ]
- : []
- }
- searchable={true}
+ {isEnabled(Mode.CONVERSIONS) &&
+ (specialGoal ? (
+ <TabButton
+ active={mode === Mode.CONVERSIONS}
+ onClick={setTabFactory(Mode.CONVERSIONS)}
>
- Properties
- </DropdownTabButton>
+ {specialGoal.title}
+ </TabButton>
) : (
<TabButton
- active={mode === PROPS}
- onClick={setTabFactory(PROPS)}
+ active={mode === Mode.CONVERSIONS}
+ onClick={setTabFactory(Mode.CONVERSIONS)}
>
- Properties
+ Goals
</TabButton>
))}
- {isEnabled(FUNNELS) &&
+ {isEnabled(Mode.PROPS) &&
+ !!propertyKeys.length &&
+ site.propsAvailable ? (
+ <DropdownTabButton
+ className="md:relative"
+ transitionClassName="md:left-auto md:w-88 md:origin-top-right"
+ active={mode === Mode.PROPS}
+ options={propertyKeys.map((key) => ({
+ label: key,
+ onClick: setPropKeyFactory(key),
+ selected: selectedPropKey === key
+ }))}
+ searchable={true}
+ >
+ Properties
+ </DropdownTabButton>
+ ) : (
+ <TabButton
+ active={mode === Mode.PROPS}
+ onClick={setTabFactory(Mode.PROPS)}
+ >
+ Properties
+ </TabButton>
+ )}
+ {isEnabled(Mode.FUNNELS) &&
Funnel &&
(site.funnels.length > 0 && site.funnelsAvailable ? (
<DropdownTabButton
className="md:relative"
transitionClassName="md:left-auto md:w-88 md:origin-top-right"
- active={mode === FUNNELS}
+ active={mode === Mode.FUNNELS}
options={site.funnels.map(({ name }) => ({
label: name,
onClick: setFunnelFactory(name),
- selected: mode === FUNNELS && selectedFunnel === name
+ selected: mode === Mode.FUNNELS && selectedFunnel === name
}))}
searchable={true}
>
@@ -562,8 +510,8 @@ export default function Behaviours({ importedDataInView }) {
</DropdownTabButton>
) : (
<TabButton
- active={mode === FUNNELS}
- onClick={setTabFactory(FUNNELS)}
+ active={mode === Mode.FUNNELS}
+ onClick={setTabFactory(Mode.FUNNELS)}
>
Funnels
</TabButton>
@@ -572,11 +520,44 @@ export default function Behaviours({ importedDataInView }) {
{isRealtime() && <Pill className="-mt-1">last 30min</Pill>}
{renderImportedQueryUnsupportedWarning()}
</div>
- {mode !== FUNNELS && (
- <MoreLink state={moreLinkState} linkProps={moreLinkProps()} />
+ {mode !== Mode.FUNNELS && (
+ <MoreLink state={moreLinkState} linkProps={getMoreLinkProps()} />
)}
</ReportHeader>
{renderContent()}
</ReportLayout>
)
}
+
+function BehavioursOuter({ importedDataInView }) {
+ const site = useSiteContext()
+ const { enabledModes } = useModesContext()
+ const [mode, setMode] = useState(null)
+
+ useEffect(() => {
+ const storedMode = storage.getItem(STORAGE_KEYS.getForTab({ site }))
+ // updates current mode when available modes change (if needed), loads user's stored mode
+ setMode((currentMode) =>
+ getFirstPreferenceFromEnabledModes(
+ [currentMode, storedMode],
+ enabledModes
+ )
+ )
+ }, [enabledModes, site])
+
+ return enabledModes.length && mode ? (
+ <Behaviours
+ importedDataInView={importedDataInView}
+ mode={mode}
+ setMode={setMode}
+ />
+ ) : null
+}
+
+export default function BehavioursWrapped({ importedDataInView }) {
+ return (
+ <ModesContextProvider>
+ <BehavioursOuter importedDataInView={importedDataInView} />
+ </ModesContextProvider>
+ )
+}
diff --git a/assets/js/dashboard/stats/behaviours/modes-context.tsx b/assets/js/dashboard/stats/behaviours/modes-context.tsx
new file mode 100644
index 0000000000..5daf6c93ff
--- /dev/null
+++ b/assets/js/dashboard/stats/behaviours/modes-context.tsx
@@ -0,0 +1,95 @@
+import React, { useCallback, useContext, useState } from 'react'
+import { PlausibleSite, useSiteContext } from '../../site-context'
+import { UserContextValue, useUserContext } from '../../user-context'
+
+export enum Mode {
+ CONVERSIONS = 'conversions',
+ PROPS = 'props',
+ FUNNELS = 'funnels'
+}
+
+export const MODES = {
+ [Mode.CONVERSIONS]: {
+ title: 'Goal conversions',
+ isAvailableKey: null, // always available
+ optedOutKey: `${Mode.CONVERSIONS}OptedOut`
+ },
+ [Mode.PROPS]: {
+ title: 'Custom properties',
+ isAvailableKey: `${Mode.PROPS}Available`,
+ optedOutKey: `${Mode.PROPS}OptedOut`
+ },
+ [Mode.FUNNELS]: {
+ title: 'Funnels',
+ isAvailableKey: `${Mode.FUNNELS}Available`,
+ optedOutKey: `${Mode.FUNNELS}OptedOut`
+ }
+} as const
+
+export const getFirstPreferenceFromEnabledModes = (
+ preferredModes: Mode[],
+ enabledModes: Mode[]
+): Mode | null => {
+ const defaultPreferenceOrder = [Mode.CONVERSIONS, Mode.PROPS, Mode.FUNNELS]
+ for (const mode of [...preferredModes, ...defaultPreferenceOrder]) {
+ if (enabledModes.includes(mode)) {
+ return mode
+ }
+ }
+ return null
+}
+
+function getInitiallyAvailableModes({
+ site,
+ user
+}: {
+ site: PlausibleSite
+ user: UserContextValue
+}): Mode[] {
+ return Object.entries(MODES)
+ .filter(([_, { isAvailableKey, optedOutKey }]) => {
+ const isOptedOut = site[optedOutKey]
+ const isAvailable = isAvailableKey ? site[isAvailableKey] : true
+
+ // If the feature is not supported by the site owner's subscription,
+ // it only makes sense to display the feature tab to the owner itself
+ // as only they can upgrade to make the feature available.
+ const callToActionIsMissing = !isAvailable && user.role !== 'owner'
+ if (!isOptedOut && !callToActionIsMissing) {
+ return true
+ }
+ return false
+ })
+ .map(([mode, _]) => mode as Mode)
+}
+
+const modesContextDefaultValue = {
+ enabledModes: [] as Mode[],
+ disableMode: (() => {}) as (mode: Mode) => void
+}
+const ModesContext = React.createContext(modesContextDefaultValue)
+export const useModesContext = () => {
+ return useContext(ModesContext)
+}
+
+export const ModesContextProvider = ({
+ children
+}: {
+ children: React.ReactNode
+}) => {
+ const site = useSiteContext()
+ const user = useUserContext()
+ const [enabledModes, setEnabledModes] = useState(
+ getInitiallyAvailableModes({ site, user })
+ )
+
+ const disableMode = useCallback((mode: Mode) => {
+ setEnabledModes((modes) => modes.filter((m) => m !== mode))
+ }, [])
+
+ return (
+ <ModesContext.Provider value={{ enabledModes, disableMode }}>
+ {children}
+ </ModesContext.Provider>
+ )
+}
diff --git a/assets/js/dashboard/stats/behaviours/goal-conversions.js b/assets/js/dashboard/stats/behaviours/special-goal-prop-breakdown.js
similarity index 51%
rename from assets/js/dashboard/stats/behaviours/goal-conversions.js
rename to assets/js/dashboard/stats/behaviours/special-goal-prop-breakdown.js
index 64925b6f6b..2301ad2608 100644
--- a/assets/js/dashboard/stats/behaviours/goal-conversions.js
+++ b/assets/js/dashboard/stats/behaviours/special-goal-prop-breakdown.js
@@ -1,46 +1,13 @@
import React from 'react'
-import Conversions from './conversions'
import ListReport from '../reports/list'
import * as metrics from '../reports/metrics'
import * as url from '../../util/url'
import * as api from '../../api'
-import {
- EVENT_PROPS_PREFIX,
- getGoalFilter,
- FILTER_OPERATIONS
-} from '../../util/filters'
+import { EVENT_PROPS_PREFIX } from '../../util/filters'
import { useSiteContext } from '../../site-context'
import { useQueryContext } from '../../query-context'
-export const SPECIAL_GOALS = {
- 404: { title: '404 Pages', prop: 'path' },
- 'Outbound Link: Click': { title: 'Outbound Links', prop: 'url' },
- 'Cloaked Link: Click': { title: 'Cloaked Links', prop: 'url' },
- 'File Download': { title: 'File Downloads', prop: 'url' },
- 'WP Search Queries': {
- title: 'WordPress Search Queries',
- prop: 'search_query'
- },
- 'WP Form Completions': { title: 'WordPress Form Completions', prop: 'path' }
-}
-
-function getSpecialGoal(query) {
- const goalFilter = getGoalFilter(query)
- if (!goalFilter) {
- return null
- }
- const [operation, _filterKey, clauses] = goalFilter
- if (operation === FILTER_OPERATIONS.is && clauses.length == 1) {
- return SPECIAL_GOALS[clauses[0]] || null
- }
- return null
-}
-
-export function specialTitleWhenGoalFilter(query, defaultTitle) {
- return getSpecialGoal(query)?.title || defaultTitle
-}
-
-function SpecialPropBreakdown({ prop, afterFetchData }) {
+export function SpecialGoalPropBreakdown({ prop, afterFetchData }) {
const site = useSiteContext()
const { query } = useQueryContext()
@@ -92,24 +59,3 @@ function SpecialPropBreakdown({ prop, afterFetchData }) {
/>
)
}
-
-export default function GoalConversions({ afterFetchData, onGoalFilterClick }) {
- const { query } = useQueryContext()
-
- const specialGoal = getSpecialGoal(query)
- if (specialGoal) {
- return (
- <SpecialPropBreakdown
- prop={specialGoal.prop}
- afterFetchData={afterFetchData}
- />
- )
- } else {
- return (
- <Conversions
- onGoalFilterClick={onGoalFilterClick}
- afterFetchData={afterFetchData}
- />
- )
- }
-}
diff --git a/assets/js/dashboard/stats/modals/props.js b/assets/js/dashboard/stats/modals/props.js
index 7400c5f6ab..452506f46c 100644
--- a/assets/js/dashboard/stats/modals/props.js
+++ b/assets/js/dashboard/stats/modals/props.js
@@ -3,8 +3,12 @@ import { useParams } from 'react-router-dom'
import Modal from './modal'
import { addFilter, revenueAvailable } from '../../query'
-import { specialTitleWhenGoalFilter } from '../behaviours/goal-conversions'
-import { EVENT_PROPS_PREFIX, hasConversionGoalFilter } from '../../util/filters'
+import { getSpecialGoal } from '../../util/goals'
+import {
+ EVENT_PROPS_PREFIX,
+ getGoalFilter,
+ hasConversionGoalFilter
+} from '../../util/filters'
import BreakdownModal from './breakdown-modal'
import * as metrics from '../reports/metrics'
import * as url from '../../util/url'
@@ -20,8 +24,11 @@ function PropsModal() {
/*global BUILD_EXTRA*/
const showRevenueMetrics = BUILD_EXTRA && revenueAvailable(query, site)
+ const goalFilter = getGoalFilter(query)
+ const specialGoal = goalFilter ? getSpecialGoal(goalFilter) : null
+
const reportInfo = {
- title: specialTitleWhenGoalFilter(query, 'Custom property breakdown'),
+ title: specialGoal ? specialGoal.title : 'Custom property breakdown',
dimension: propKey,
endpoint: url.apiPath(
site,
diff --git a/assets/js/dashboard/util/goals.ts b/assets/js/dashboard/util/goals.ts
new file mode 100644
index 0000000000..47608351ff
--- /dev/null
+++ b/assets/js/dashboard/util/goals.ts
@@ -0,0 +1,33 @@
+import { Filter } from '../query'
+import { FILTER_OPERATIONS } from './filters'
+
+export const isPageViewGoal = (goalName: string) => {
+ goalName.startsWith('Visit ')
+}
+
+export const SPECIAL_GOALS = {
+ '404': { title: '404 Pages', prop: 'path' },
+ 'Outbound Link: Click': { title: 'Outbound Links', prop: 'url' },
+ 'Cloaked Link: Click': { title: 'Cloaked Links', prop: 'url' },
+ 'File Download': { title: 'File Downloads', prop: 'url' },
+ 'WP Search Queries': {
+ title: 'WordPress Search Queries',
+ prop: 'search_query'
+ },
+ 'WP Form Completions': { title: 'WordPress Form Completions', prop: 'path' }
+}
+
+export function isSpecialGoal(
+ goalName: string | number
+): goalName is keyof typeof SPECIAL_GOALS {
+ return goalName in SPECIAL_GOALS
+}
+
+export function getSpecialGoal(goalFilter: Filter) {
+ const [operation, _filterKey, clauses] = goalFilter
+ if (operation === FILTER_OPERATIONS.is && clauses.length == 1) {
+ const goalName = clauses[0]
+ return isSpecialGoal(goalName) ? SPECIAL_GOALS[goalName] : null
+ }
+ return null
+}