Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(insights): add date range exclusions to the insight date filter (#75398)

Sam Pennington484cbbe0eaad
diff --git a/frontend/src/lib/components/DateFilter/DateFilter.tsx b/frontend/src/lib/components/DateFilter/DateFilter.tsx
index 3e366da2224b..e8c6fa3c8801 100644
--- a/frontend/src/lib/components/DateFilter/DateFilter.tsx
+++ b/frontend/src/lib/components/DateFilter/DateFilter.tsx
@@ -13,6 +13,7 @@ import {
DateFilterView,
NO_OVERRIDE_RANGE_PLACEHOLDER,
} from 'lib/components/DateFilter/types'
+import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
import { dayjs } from 'lib/dayjs'
import { LemonCalendarSelect, LemonCalendarSelectProps } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
import { LemonCalendarRange } from 'lib/lemon-ui/LemonCalendarRange/LemonCalendarRange'
@@ -26,9 +27,11 @@ import { ResolvedDateRangeResponse } from '~/queries/schema/schema-general'
import { DateMappingOption, PropertyOperator } from '~/types'
import { PropertyFilterDatePicker } from '../PropertyFilters/components/PropertyFilterDatePicker'
+import type { DateFilterExclusions } from './DateFilterExclusionsControl'
import { dateFilterLogic } from './dateFilterLogic'
import { FixedRangeWithTimePicker } from './FixedRangeWithTimePicker'
import { JumpToTimestampPicker } from './JumpToTimestampPicker'
+import { LemonDateFilterExclusions } from './LemonDateFilterExclusions'
import { RelativeDateRangeSelector } from './RelativeDateRangeSelector'
import { RollingDateRangeFilter } from './RollingDateRangeFilter'
import { DateOption } from './rollingDateRangeFilterLogic'
@@ -81,6 +84,11 @@ interface RawDateFilterProps extends DateFilterProps {
use24HourFormat?: boolean
explicitDate?: boolean
showExplicitDateToggle?: boolean
+ exclusions?: DateFilterExclusions
+ onExclusionsChange?: (exclusions: DateFilterExclusions) => void
+ showIncompletePeriodExclusion?: boolean
+ showDaysOfWeekExclusions?: boolean
+ optionsSize?: 'small' | 'medium'
}
export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(function DateFilter(
@@ -109,6 +117,11 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func
use24HourFormat = false,
explicitDate,
showExplicitDateToggle = false,
+ exclusions,
+ onExclusionsChange,
+ showIncompletePeriodExclusion = false,
+ showDaysOfWeekExclusions = false,
+ optionsSize,
resolvedDateRange,
showJumpToTimestamp = false,
showCustomRelativeRange = false,
@@ -185,6 +198,8 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func
)
const showFixedRangeTimeToggle = allowTimePrecision || allowFixedRangeWithTime
+ const showExclusions =
+ (showIncompletePeriodExclusion || showDaysOfWeekExclusions) && !!exclusions && !!onExclusionsChange
const popoverOverlay =
view === DateFilterView.FixedRange ? (
@@ -260,109 +275,132 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func
initialTo={typeof dateTo === 'string' ? dateTo : null}
/>
) : (
- <div className="deprecated-space-y-px" ref={optionsRef} onClick={(e) => e.stopPropagation()}>
- {dateOptions.map(({ key, values, inactive }) => {
- if (key === CUSTOM_OPTION_KEY && !showCustom) {
- return null
- }
+ <div className="flex max-h-full min-h-0 flex-col" ref={optionsRef} onClick={(e) => e.stopPropagation()}>
+ <ScrollableShadows
+ direction="vertical"
+ hideScrollbars
+ // max-h-80 shows ~9 preset rows with a sliver of the tenth as a scroll hint
+ className={clsx('min-h-0 flex-1 border-b', optionsSize === 'small' && 'max-h-80')}
+ innerClassName="deprecated-space-y-px p-1"
+ >
+ {dateOptions.map(({ key, values, inactive }) => {
+ if (key === CUSTOM_OPTION_KEY && !showCustom) {
+ return null
+ }
- if (inactive && label !== key) {
- return null
- }
+ if (inactive && label !== key) {
+ return null
+ }
- const isActive =
- (dateFrom ?? null) === (values[0] ?? null) && (dateTo ?? null) === (values[1] ?? null)
- const dateValue = dateFilterToText(
- values[0],
- values[1],
- CUSTOM_OPTION_DESCRIPTION,
- dateOptions,
- isDateFormatted,
- undefined,
- undefined,
- weekStartDay
- )
- const startOfRangeDateValue = dateFilterToText(
- values[0],
- undefined,
- '',
- [],
- false,
- 'MMMM D, YYYY',
- true
- )
- const endOfRangeDateValue = values[1]
- ? dateFilterToText(values[1], undefined, '', [], false, 'MMMM D, YYYY', true)
- : undefined
+ const isActive =
+ (dateFrom ?? null) === (values[0] ?? null) && (dateTo ?? null) === (values[1] ?? null)
+ const dateValue = dateFilterToText(
+ values[0],
+ values[1],
+ CUSTOM_OPTION_DESCRIPTION,
+ dateOptions,
+ isDateFormatted,
+ undefined,
+ undefined,
+ weekStartDay
+ )
+ const startOfRangeDateValue = dateFilterToText(
+ values[0],
+ undefined,
+ '',
+ [],
+ false,
+ 'MMMM D, YYYY',
+ true
+ )
+ const endOfRangeDateValue = values[1]
+ ? dateFilterToText(values[1], undefined, '', [], false, 'MMMM D, YYYY', true)
+ : undefined
- return (
- <Tooltip
- key={key}
- title={
- makeLabel ? makeLabel(dateValue, startOfRangeDateValue, endOfRangeDateValue) : undefined
- }
- >
- <LemonButton
+ return (
+ <Tooltip
key={key}
- data-attr={`date-filter-${key.toLowerCase().replace(/\s+/g, '-')}`}
- onClick={() => setDate(values[0] || null, values[1] || null, false, explicitDate)}
- active={isActive}
- fullWidth
+ title={
+ makeLabel
+ ? makeLabel(dateValue, startOfRangeDateValue, endOfRangeDateValue)
+ : undefined
+ }
>
- {key === CUSTOM_OPTION_KEY ? NO_OVERRIDE_RANGE_PLACEHOLDER : key}
- </LemonButton>
- </Tooltip>
- )
- })}
- {showRollingRangePicker && (
- <RollingDateRangeFilter
- pageKey={key}
- dateFrom={dateFrom}
- dateRangeFilterLabel={isFixedDateMode ? 'Last' : undefined}
- selected={isRollingDateRange}
- onChange={(fromDate) => {
- setDate(fromDate, '', true, explicitDate)
- }}
- makeLabel={makeLabel}
- popover={{
- ref: rollingDateRangeRef,
- }}
- max={max}
- allowedDateOptions={
- isFixedDateMode && !allowedRollingDateOptions
- ? ['hours', 'days', 'weeks', 'months', 'years']
- : allowedRollingDateOptions
- }
- fullWidth
- />
- )}
- <LemonDivider />
- {(isFixedDateMode || allowSingleAndRange) && (
- <LemonButton onClick={openFixedDate} active={isFixedDate} fullWidth>
- Custom date...
- </LemonButton>
- )}
- {(!isFixedDateMode || allowSingleAndRange) && (
- <>
- {!allowSingleAndRange && (
- <LemonButton onClick={openDateToNow} active={isDateToNow} fullWidth>
- From custom date until now…
- </LemonButton>
- )}
- <LemonButton onClick={openFixedRange} active={isFixedRange} fullWidth>
- Custom fixed date range…
+ <LemonButton
+ key={key}
+ data-attr={`date-filter-${key.toLowerCase().replace(/\s+/g, '-')}`}
+ onClick={() => setDate(values[0] || null, values[1] || null, false, explicitDate)}
+ active={isActive}
+ size={optionsSize}
+ fullWidth
+ >
+ {key === CUSTOM_OPTION_KEY ? NO_OVERRIDE_RANGE_PLACEHOLDER : key}
+ </LemonButton>
+ </Tooltip>
+ )
+ })}
+ {showRollingRangePicker && (
+ <RollingDateRangeFilter
+ pageKey={key}
+ size={optionsSize}
+ dateFrom={dateFrom}
+ dateRangeFilterLabel={isFixedDateMode ? 'Last' : undefined}
+ selected={isRollingDateRange}
+ onChange={(fromDate) => {
+ setDate(fromDate, '', true, explicitDate)
+ }}
+ makeLabel={makeLabel}
+ popover={{
+ ref: rollingDateRangeRef,
+ }}
+ max={max}
+ allowedDateOptions={
+ isFixedDateMode && !allowedRollingDateOptions
+ ? ['hours', 'days', 'weeks', 'months', 'years']
+ : allowedRollingDateOptions
+ }
+ fullWidth
+ />
+ )}
+ </ScrollableShadows>
+ <div className="shrink-0 deprecated-space-y-px p-1">
+ {(isFixedDateMode || allowSingleAndRange) && (
+ <LemonButton onClick={openFixedDate} active={isFixedDate} size={optionsSize} fullWidth>
+ Custom date...
</LemonButton>
- {effectiveShowCustomRelativeRange && (
- <LemonButton onClick={openCustomRelativeRange} active={isCustomRelativeRange} fullWidth>
- Custom relative range…
+ )}
+ {(!isFixedDateMode || allowSingleAndRange) && (
+ <>
+ {!allowSingleAndRange && (
+ <LemonButton onClick={openDateToNow} active={isDateToNow} size={optionsSize} fullWidth>
+ From custom date until now…
+ </LemonButton>
+ )}
+ <LemonButton onClick={openFixedRange} active={isFixedRange} size={optionsSize} fullWidth>
+ Custom fixed date range…
</LemonButton>
- )}
- </>
- )}
- {showExplicitDateToggle && (
- <>
- <LemonDivider />
- <div className="LemonSwitch pb-2 pt-2 LemonSwitch--medium LemonSwitch--full-width">
+ {effectiveShowCustomRelativeRange && (
+ <LemonButton
+ onClick={openCustomRelativeRange}
+ active={isCustomRelativeRange}
+ size={optionsSize}
+ fullWidth
+ >
+ Custom relative range…
+ </LemonButton>
+ )}
+ </>
+ )}
+ {(showExplicitDateToggle || showExclusions) && <LemonDivider />}
+ {showExplicitDateToggle && (
+ <div
+ className={clsx(
+ // Deliberately medium at every optionsSize: LemonButton--small keeps the default
+ // 14px font, while LemonSwitch--small would drop the label to 12px
+ 'LemonSwitch LemonSwitch--full-width LemonSwitch--medium',
+ optionsSize === 'small' ? 'pb-1 pt-1' : 'pb-2 pt-2'
+ )}
+ >
<label className="flex items-center gap-1">
<span>Exact time range</span>
<Tooltip
@@ -387,16 +425,30 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func
}}
/>
</div>
- </>
- )}
- {showJumpToTimestamp && (
- <>
- <LemonDivider />
- <LemonButton onClick={openJumpToTimestamp} fullWidth data-attr="jump-to-timestamp-option">
- Jump to timestamp…
- </LemonButton>
- </>
- )}
+ )}
+ {showExclusions && (
+ <LemonDateFilterExclusions
+ exclusions={exclusions}
+ onChange={onExclusionsChange}
+ showDays={showDaysOfWeekExclusions}
+ showIncomplete={showIncompletePeriodExclusion}
+ size={optionsSize}
+ />
+ )}
+ {showJumpToTimestamp && (
+ <>
+ <LemonDivider />
+ <LemonButton
+ onClick={openJumpToTimestamp}
+ size={optionsSize}
+ fullWidth
+ data-attr="jump-to-timestamp-option"
+ >
+ Jump to timestamp…
+ </LemonButton>
+ </>
+ )}
+ </div>
</div>
)
@@ -409,6 +461,7 @@ export const DateFilter = forwardRef<HTMLButtonElement, RawDateFilterProps>(func
additionalRefs={[rollingDateRangeRef]}
onClickOutside={close}
closeParentPopoverOnClickInside={false}
+ overflowHidden={view === DateFilterView.QuickList}
>
<LemonButton
ref={ref}
diff --git a/frontend/src/lib/components/DateFilter/LemonDateFilterExclusions.tsx b/frontend/src/lib/components/DateFilter/LemonDateFilterExclusions.tsx
new file mode 100644
index 000000000000..026749c19b75
--- /dev/null
+++ b/frontend/src/lib/components/DateFilter/LemonDateFilterExclusions.tsx
@@ -0,0 +1,125 @@
+import clsx from 'clsx'
+import { useState } from 'react'
+
+import { IconChevronRight } from '@posthog/icons'
+import { LemonButton, LemonDivider, LemonSwitch, Popover } from '@posthog/lemon-ui'
+
+import {
+ type DateFilterExclusions,
+ dateFilterExclusionsSummary,
+} from 'lib/components/DateFilter/DateFilterExclusionsControl'
+
+const DAYS_OF_WEEK: { day: string; label: string; name: string }[] = [
+ { day: '1', label: 'M', name: 'Monday' },
+ { day: '2', label: 'T', name: 'Tuesday' },
+ { day: '3', label: 'W', name: 'Wednesday' },
+ { day: '4', label: 'T', name: 'Thursday' },
+ { day: '5', label: 'F', name: 'Friday' },
+ { day: '6', label: 'S', name: 'Saturday' },
+ { day: '7', label: 'S', name: 'Sunday' },
+]
+
+export function LemonDateFilterExclusions({
+ exclusions,
+ onChange,
+ showDays,
+ showIncomplete,
+ size,
+}: {
+ exclusions: DateFilterExclusions
+ onChange: (exclusions: DateFilterExclusions) => void
+ showDays: boolean
+ showIncomplete: boolean
+ size?: 'small' | 'medium'
+}): JSX.Element {
+ const [visible, setVisible] = useState(false)
+ const summary = dateFilterExclusionsSummary(exclusions)
+ return (
+ <Popover
+ visible={visible}
+ onClickOutside={() => setVisible(false)}
+ placement="right-end"
+ // side fallbacks only, so collision handling keeps the flyout beside the row instead of flipping above/below
+ fallbackPlacements={['left-end']}
+ padded={false}
+ overlay={
+ <div className="w-64">
+ {showIncomplete && (
+ <div className="px-3 py-2.5">
+ <LemonSwitch
+ fullWidth
+ label="Incomplete period"
+ checked={exclusions.incomplete}
+ onChange={(incomplete) => onChange({ ...exclusions, incomplete })}
+ data-attr="date-filter-exclude-incomplete-periods"
+ />
+ </div>
+ )}
+ {showIncomplete && showDays && <LemonDivider className="my-0" />}
+ {showDays && (
+ <div className="flex flex-col gap-2 px-3 py-2.5">
+ <div className="flex gap-1">
+ {DAYS_OF_WEEK.map(({ day, label, name }) => {
+ const selected = exclusions.days.includes(day)
+ return (
+ <LemonButton
+ key={day}
+ size="xsmall"
+ type="secondary"
+ center
+ className={clsx(
+ 'flex-1',
+ selected && 'border-accent bg-accent-highlight-secondary text-accent'
+ )}
+ onClick={() =>
+ onChange({
+ ...exclusions,
+ days: selected
+ ? exclusions.days.filter((d) => d !== day)
+ : [...exclusions.days, day],
+ })
+ }
+ tooltip={name}
+ aria-label={`Exclude ${name}`}
+ aria-pressed={selected}
+ >
+ {label}
+ </LemonButton>
+ )
+ })}
+ </div>
+ <div className="flex items-center justify-center gap-3">
+ <LemonButton
+ size="xsmall"
+ onClick={() => onChange({ ...exclusions, days: ['6', '7'] })}
+ >
+ Weekends
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ onClick={() => onChange({ ...exclusions, days: ['1', '2', '3', '4', '5'] })}
+ >
+ Weekdays
+ </LemonButton>
+ <LemonButton size="xsmall" onClick={() => onChange({ ...exclusions, days: [] })}>
+ Clear
+ </LemonButton>
+ </div>
+ </div>
+ )}
+ </div>
+ }
+ >
+ <LemonButton
+ fullWidth
+ onClick={() => setVisible(!visible)}
+ active={visible}
+ size={size}
+ sideIcon={<IconChevronRight />}
+ data-attr="date-filter-exclusions"
+ >
+ {summary || 'Exclude'}
+ </LemonButton>
+ </Popover>
+ )
+}
diff --git a/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.scss b/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.scss
index 43d0c3d259c1..e3379b35c3f4 100644
--- a/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.scss
+++ b/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.scss
@@ -1,10 +1,6 @@
.RollingDateRangeFilter {
display: flex;
align-items: center;
- height: 1.6875rem;
- min-height: 2rem;
- padding: 1.25rem 0;
- font-size: 0.875rem;
font-weight: normal;
line-height: 1.375em;
color: var(--text-3000);
diff --git a/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx b/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx
index 7f68fed7c429..fde734fffe83 100644
--- a/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx
+++ b/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx
@@ -38,6 +38,7 @@ type RollingDateRangeFilterProps = {
dateRangeFilterSuffixLabel?: string
allowedDateOptions?: DateOption[]
fullWidth?: LemonButtonProps['fullWidth']
+ size?: 'small' | 'medium'
}
export function RollingDateRangeFilter({
@@ -54,6 +55,7 @@ export function RollingDateRangeFilter({
pageKey,
allowedDateOptions = ['days', 'weeks', 'months', 'years'],
fullWidth,
+ size,
}: RollingDateRangeFilterProps): JSX.Element {
const logicProps = { onChange, dateFrom, inUse: selected || inUse, max, pageKey }
const { increaseCounter, decreaseCounter, setCounter, setDateOption, toggleDateOptionsSelector, select } =
@@ -119,6 +121,7 @@ export function RollingDateRangeFilter({
data-attr="rolling-date-range-filter"
onClick={select}
active={selected}
+ size={size}
fullWidth={fullWidth}
>
{contents}
diff --git a/frontend/src/lib/lemon-ui/Tooltip/Tooltip.test.tsx b/frontend/src/lib/lemon-ui/Tooltip/Tooltip.test.tsx
index a0eccb35d5ae..8f6a4c650884 100644
--- a/frontend/src/lib/lemon-ui/Tooltip/Tooltip.test.tsx
+++ b/frontend/src/lib/lemon-ui/Tooltip/Tooltip.test.tsx
@@ -80,4 +80,44 @@ describe('Tooltip', () => {
await waitFor(() => expect(screen.queryByText(TITLE)).toBeNull())
})
+
+ it('dismisses on scroll outside the tooltip', async () => {
+ renderTooltip()
+
+ fireEvent.pointerEnter(screen.getByText('Outdated'), { pointerType: 'mouse' })
+ fireEvent.mouseEnter(screen.getByText('Outdated'))
+ expect(await screen.findByText(TITLE)).toBeTruthy()
+
+ fireEvent.scroll(window)
+
+ await waitFor(() => expect(screen.queryByText(TITLE)).toBeNull())
+ })
+
+ it('does not dismiss on scroll inside the tooltip', async () => {
+ renderTooltip()
+
+ fireEvent.pointerEnter(screen.getByText('Outdated'), { pointerType: 'mouse' })
+ fireEvent.mouseEnter(screen.getByText('Outdated'))
+ const title = await screen.findByText(TITLE)
+
+ fireEvent.scroll(title)
+
+ expect(screen.getByText(TITLE)).toBeTruthy()
+ })
+
+ it('does not dismiss a controlled tooltip on scroll', async () => {
+ render(
+ <div>
+ <Tooltip title={TITLE} visible>
+ <span>Outdated</span>
+ </Tooltip>
+ </div>
+ )
+
+ expect(await screen.findByText(TITLE)).toBeTruthy()
+
+ fireEvent.scroll(window)
+
+ expect(screen.getByText(TITLE)).toBeTruthy()
+ })
})
diff --git a/frontend/src/lib/lemon-ui/Tooltip/Tooltip.tsx b/frontend/src/lib/lemon-ui/Tooltip/Tooltip.tsx
index b03893318ab4..851de17de4d3 100644
--- a/frontend/src/lib/lemon-ui/Tooltip/Tooltip.tsx
+++ b/frontend/src/lib/lemon-ui/Tooltip/Tooltip.tsx
@@ -127,6 +127,21 @@ export function Tooltip({
}
}, [open, onOpen])
+ // Dismiss on scroll, otherwise the tooltip lingers detached after its trigger scrolls away
+ useEffect(() => {
+ if (!open || controlledOpen !== undefined) {
+ return
+ }
+ const handleScroll = (event: Event): void => {
+ if (event.target instanceof Element && event.target.closest('.Tooltip')) {
+ return
+ }
+ setUncontrolledOpen(false)
+ }
+ window.addEventListener('scroll', handleScroll, { capture: true, passive: true })
+ return () => window.removeEventListener('scroll', handleScroll, { capture: true })
+ }, [open, controlledOpen])
+
const child = React.isValidElement(children) ? children : <span>{children}</span>
if (!title && !docLink) {
diff --git a/frontend/src/scenes/insights/filters/InsightDateFilter/InsightDateFilter.tsx b/frontend/src/scenes/insights/filters/InsightDateFilter/InsightDateFilter.tsx
index fbc5e5eb0b3e..60d5f8cb3314 100644
--- a/frontend/src/scenes/insights/filters/InsightDateFilter/InsightDateFilter.tsx
+++ b/frontend/src/scenes/insights/filters/InsightDateFilter/InsightDateFilter.tsx
@@ -1,31 +1,83 @@
import { useActions, useValues } from 'kea'
+import { useEffect, useRef } from 'react'
import { IconCalendar } from '@posthog/icons'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { type DateFilterExclusions } from 'lib/components/DateFilter/DateFilterExclusionsControl'
import { dateMapping } from 'lib/utils/dateFilters'
import { alignResolvedDateRangeToInterval } from 'lib/utils/datetime'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { FunnelVizType } from '~/types'
+
+import {
+ computeDaysOfWeekUpdate,
+ daysOfWeekSetsEqual,
+ getExcludedDaysOfWeek,
+ parseIsoDaysOfWeek,
+} from './daysOfWeekFilterUtils'
+
type InsightDateFilterProps = {
disabled: boolean
}
export function InsightDateFilter({ disabled }: InsightDateFilterProps): JSX.Element {
const { insightProps, editingDisabledReason } = useValues(insightLogic)
- const { dateRange, interval, querySource } = useValues(insightVizDataLogic(insightProps))
- const { updateDateRange } = useActions(insightVizDataLogic(insightProps))
+ const { dateRange, interval, querySource, trendsFilter, funnelsFilter, isTrends, isFunnels, isLifecycle } =
+ useValues(insightVizDataLogic(insightProps))
+ const { updateDateRange, updateQuerySource } = useActions(insightVizDataLogic(insightProps))
const { insightData } = useValues(insightVizDataLogic(insightProps))
const { reportInsightDatePickerOpened } = useActions(eventUsageLogic)
+ // The picker speaks excluded days; the query schema stores included days
+ const excludedDaysOfWeek = getExcludedDaysOfWeek(dateRange)
+ // Funnel steps and time-to-convert deliberately lack backend daysOfWeek support: dropping
+ // mid-sequence events has ambiguous semantics (see funnel_event_query.py)
+ const supportsDaysOfWeek =
+ isTrends || isLifecycle || (isFunnels && funnelsFilter?.funnelVizType === FunnelVizType.Trends)
+ // The backend rejects daysOfWeek together with smoothing, so don't offer it
+ const smoothingActive = isTrends && (trendsFilter?.smoothingIntervals ?? 1) > 1
+ const showDaysOfWeekExclusions = supportsDaysOfWeek && !smoothingActive
+
+ // Enabling smoothing hides the control, so clear daysOfWeek on that transition (never on
+ // mount): the backend rejects the combination and there'd be no UI left to remove it
+ const prevShowDaysOfWeekExclusions = useRef(showDaysOfWeekExclusions)
+ useEffect(() => {
+ const wasShown = prevShowDaysOfWeekExclusions.current
+ prevShowDaysOfWeekExclusions.current = showDaysOfWeekExclusions
+ if (wasShown && !showDaysOfWeekExclusions && smoothingActive && dateRange?.daysOfWeek?.length) {
+ updateQuerySource(computeDaysOfWeekUpdate([], dateRange))
+ }
+ }, [showDaysOfWeekExclusions, smoothingActive, dateRange, updateQuerySource])
+
+ const exclusions: DateFilterExclusions = {
+ days: showDaysOfWeekExclusions ? excludedDaysOfWeek.map(String) : [],
+ incomplete: !!dateRange?.excludeIncompletePeriods,
+ }
+ const handleExclusionsChange = (next: DateFilterExclusions): void => {
+ const nextExcludedDaysOfWeek = parseIsoDaysOfWeek(next.days)
+ if (showDaysOfWeekExclusions && !daysOfWeekSetsEqual(nextExcludedDaysOfWeek, excludedDaysOfWeek)) {
+ updateQuerySource(computeDaysOfWeekUpdate(nextExcludedDaysOfWeek, dateRange))
+ }
+ if (next.incomplete !== exclusions.incomplete) {
+ updateDateRange({ excludeIncompletePeriods: next.incomplete ? true : null }, true)
+ }
+ }
+
return (
<DateFilter
showExplicitDateToggle
dateTo={dateRange?.date_to ?? undefined}
dateFrom={dateRange?.date_from ?? '-7d'}
explicitDate={dateRange?.explicitDate ?? false}
+ exclusions={exclusions}
+ onExclusionsChange={handleExclusionsChange}
+ showIncompletePeriodExclusion
+ showDaysOfWeekExclusions={showDaysOfWeekExclusions}
+ optionsSize="small"
allowTimePrecision
allowFixedRangeWithTime
disabled={disabled}
diff --git a/frontend/src/scenes/insights/filters/InsightDateFilter/daysOfWeekFilterUtils.test.ts b/frontend/src/scenes/insights/filters/InsightDateFilter/daysOfWeekFilterUtils.test.ts
new file mode 100644
index 000000000000..ff99a8e67893
--- /dev/null
+++ b/frontend/src/scenes/insights/filters/InsightDateFilter/daysOfWeekFilterUtils.test.ts
@@ -0,0 +1,64 @@
+import type { DateRange } from '~/queries/schema/schema-general'
+
+import {
+ computeDaysOfWeekUpdate,
+ getExcludedDaysOfWeek,
+ invertDaysOfWeek,
+ type IsoDayOfWeek,
+} from './daysOfWeekFilterUtils'
+
+describe('daysOfWeekFilterUtils', () => {
+ it.each([
+ [[], []],
+ [[1, 2, 3, 4, 5, 6, 7], []],
+ [
+ [6, 7],
+ [1, 2, 3, 4, 5],
+ ],
+ [
+ [1, 2, 3, 4, 5],
+ [6, 7],
+ ],
+ [[3], [1, 2, 4, 5, 6, 7]],
+ ] as [IsoDayOfWeek[], IsoDayOfWeek[]][])('inverts %j to %j', (days, expected) => {
+ expect(invertDaysOfWeek(days)).toEqual(expected)
+ })
+
+ it.each([
+ [undefined, []],
+ [null, []],
+ [{ daysOfWeek: null }, []],
+ [{ daysOfWeek: [] }, []],
+ [{ daysOfWeek: [6, 7] }, [1, 2, 3, 4, 5]],
+ [{ daysOfWeek: [5, 1, 3] }, [2, 4, 6, 7]],
+ ] as [DateRange | null | undefined, IsoDayOfWeek[]][])(
+ 'reads excluded days from dateRange %j as %j',
+ (dateRange, expected) => {
+ expect(getExcludedDaysOfWeek(dateRange)).toEqual(expected)
+ }
+ )
+
+ it.each([
+ [[], null],
+ [[1, 2, 3, 4, 5, 6, 7], null],
+ [
+ [6, 7],
+ [1, 2, 3, 4, 5],
+ ],
+ [
+ [1, 2, 3, 4, 5],
+ [6, 7],
+ ],
+ ] as [IsoDayOfWeek[], number[] | null][])(
+ 'computes a daysOfWeek update excluding %j as %j, normalizing none/all excluded to null',
+ (excludedDays, expectedDaysOfWeek) => {
+ const update = computeDaysOfWeekUpdate(excludedDays, { date_from: '-7d' })
+ expect(update.dateRange?.daysOfWeek ?? null).toEqual(expectedDaysOfWeek)
+ }
+ )
+
+ it('preserves the rest of the dateRange when computing an update', () => {
+ const update = computeDaysOfWeekUpdate([6, 7], { date_from: '-7d', date_to: null })
+ expect(update.dateRange).toEqual({ date_from: '-7d', date_to: null, daysOfWeek: [1, 2, 3, 4, 5] })
+ })
+})
diff --git a/frontend/src/scenes/insights/filters/InsightDateFilter/daysOfWeekFilterUtils.ts b/frontend/src/scenes/insights/filters/InsightDateFilter/daysOfWeekFilterUtils.ts
index 71e183327133..da8b8f9e597e 100644
--- a/frontend/src/scenes/insights/filters/InsightDateFilter/daysOfWeekFilterUtils.ts
+++ b/frontend/src/scenes/insights/filters/InsightDateFilter/daysOfWeekFilterUtils.ts
@@ -1,4 +1,4 @@
-import { DateRange, TrendsQuery } from '~/queries/schema/schema-general'
+import { DateRange } from '~/queries/schema/schema-general'
export type IsoDayOfWeek = NonNullable<DateRange['daysOfWeek']>[number]
@@ -31,6 +31,23 @@ export function getExcludedDaysOfWeek(dateRange: DateRange | null | undefined):
return dateRange?.daysOfWeek?.length ? invertDaysOfWeek(sortDays(dateRange.daysOfWeek)) : []
}
+/** Parses the day picker's string values, dropping anything outside 1-7 rather than casting. */
+export function parseIsoDaysOfWeek(days: string[]): IsoDayOfWeek[] {
+ return days
+ .map((day) => parseInt(day, 10))
+ .filter((day): day is IsoDayOfWeek => (ALL_DAY_NUMBERS as number[]).includes(day))
+}
+
+/** Order-insensitive equality, so re-picking the same days in a different order isn't a change. */
+export function daysOfWeekSetsEqual(a: IsoDayOfWeek[], b: IsoDayOfWeek[]): boolean {
+ if (a.length !== b.length) {
+ return false
+ }
+ const sortedA = sortDays(a)
+ const sortedB = sortDays(b)
+ return sortedA.every((day, i) => day === sortedB[i])
+}
+
export function daysOfWeekLabel(days: IsoDayOfWeek[]): string {
if (days.length === 0 || days.length === DAYS_IN_WEEK) {
return 'All days'
@@ -50,7 +67,7 @@ export function daysOfWeekLabel(days: IsoDayOfWeek[]): string {
export function computeDaysOfWeekUpdate(
excludedDays: IsoDayOfWeek[],
dateRange: DateRange | null | undefined
-): Partial<TrendsQuery> {
+): { dateRange: DateRange } {
const included = invertDaysOfWeek(excludedDays)
const daysOfWeek = included.length === 0 || included.length === DAYS_IN_WEEK ? null : sortDays(included)
return { dateRange: { ...dateRange, daysOfWeek } }