Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: date filter experiment #10462

Merged
merged 24 commits into from
Jul 4, 2022
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions cypress/e2e/insights.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,25 @@ describe('Insights', () => {
cy.get('.insight-description').should('not.exist')
cy.get('[data-attr=insight-tags]').should('not.exist')
})

describe('insights date picker', () => {
it('Can set the date filter and show the right grouping interval', () => {
cy.get('[data-attr=date-filter]').click()
cy.get('div').contains('Yesterday').should('exist').click()
cy.get('[data-attr=interval-filter]').should('contain', 'Hour')
})

it('Can set a custom rolling date range', () => {
cy.get('[data-attr=date-filter]').click()
cy.get('[data-attr=rolling-date-range-input]').type('{selectall}5{enter}')
cy.get('[data-attr=rolling-date-range-date-options-selector]').click()
cy.get('.RollingDateRangeFilter__popup > div').contains('days').should('exist').click()
cy.get('[data-attr=rolling-date-range-filter] > .RollingDateRangeFilter__label')
.should('contain', 'In the last')
.click()

// Test that the button shows the correct formatted range
cy.get('[data-attr=date-filter]').get('span').contains('Last 5 days').should('exist')
})
})
})
4 changes: 1 addition & 3 deletions cypress/e2e/trends.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,7 @@ describe('Trends', () => {

it('Apply date filter', () => {
cy.get('[data-attr=date-filter]').click()
cy.contains('Last 30 days').click()

cy.get('.ant-select-item').contains('Last 30 days')
cy.get('div').contains('Yesterday').should('exist').click()
cy.get('[data-attr=trend-line-graph]', { timeout: 10000 }).should('exist')
})

Expand Down
1 change: 1 addition & 0 deletions cypress/support/e2e.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ beforeEach(() => {
req.reply(
decideResponse({
'toolbar-launch-side-action': true,
'date-filter-experiment': 'test',
})
)
)
Expand Down
170 changes: 158 additions & 12 deletions frontend/src/lib/components/DateFilter/DateFilter.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,41 @@
import React, { useMemo, useState } from 'react'
import React, { useRef, useMemo, useState } from 'react'
import { Select } from 'antd'
import { SelectProps } from 'antd/lib/select'
import { dateMapping, isDate, dateFilterToText } from 'lib/utils'
import { dateMapping, dateMappingExperiment, isDate, dateFilterToText } from 'lib/utils'
import { DateFilterRange } from 'lib/components/DateFilter/DateFilterRange'
import { dayjs } from 'lib/dayjs'
import { DateFilterRangeExperiment } from 'lib/components/DateFilter/DateFilterRangeExperiment'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { dateMappingOption } from '~/types'
import { dayjs } from 'lib/dayjs'
import './DateFilterExperiment.scss'
import { Tooltip } from 'lib/components/Tooltip'
import { dateFilterLogic } from './dateFilterLogic'
import { RollingDateRangeFilter } from './RollingDateRangeFilter'
import { useActions, useValues } from 'kea'
import { LemonButtonWithPopup, LemonDivider, LemonButton } from '@posthog/lemon-ui'
import { CalendarOutlined } from '@ant-design/icons'
import { FEATURE_FLAGS } from 'lib/constants'

export interface DateFilterProps {
defaultValue: string
showCustom?: boolean
bordered?: boolean
bordered?: boolean // remove if experiment is successful
showRollingRangePicker?: boolean // experimental
makeLabel?: (key: React.ReactNode) => React.ReactNode
style?: React.CSSProperties
onChange?: (fromDate: string, toDate: string) => void
disabled?: boolean
getPopupContainer?: (props: any) => HTMLElement
dateOptions?: Record<string, dateMappingOption>
getPopupContainer?: () => HTMLElement
dateOptions?: dateMappingOption[]
isDateFormatted?: boolean
selectProps?: SelectProps<any>
selectProps?: SelectProps<any> // remove if experiment is successful
}

interface RawDateFilterProps extends DateFilterProps {
dateFrom?: string | null | dayjs.Dayjs
dateTo?: string | null | dayjs.Dayjs
}

export function DateFilter({
function _DateFilter({
bordered,
defaultValue,
showCustom,
Expand Down Expand Up @@ -63,7 +73,10 @@ export function DateFilter({
setDateRangeOpen(true)
}
} else {
setDate(dateOptions[v].values[0], dateOptions[v].values[1])
const option = dateOptions.find((option) => !option.inactive && option.key === v)
if (option) {
setDate(option.values[0], option.values[1])
}
}
}

Expand Down Expand Up @@ -104,7 +117,7 @@ export function DateFilter({
bordered={bordered}
id="daterange_selector"
value={
isDateFormatted && !(currKey in dateOptions)
isDateFormatted && !dateOptions.find((option) => option.key === currKey)
? dateFilterToText(dateFrom, dateTo, defaultValue, dateOptions, true)
: currKey
}
Expand Down Expand Up @@ -140,7 +153,7 @@ export function DateFilter({
{...selectProps}
>
{[
...Object.entries(dateOptions).map(([key, { values, inactive }]) => {
...dateOptions.map(({ key, values, inactive }) => {
kappa90 marked this conversation as resolved.
Show resolved Hide resolved
if (key === 'Custom' && !showCustom) {
return null
}
Expand All @@ -165,3 +178,136 @@ export function DateFilter({
</Select>
)
}

function DateFilterExperiment({
defaultValue,
showCustom,
showRollingRangePicker = true,
style,
disabled,
makeLabel,
onChange,
getPopupContainer,
dateFrom,
dateTo,
dateOptions = dateMappingExperiment,
isDateFormatted = true,
}: RawDateFilterProps): JSX.Element {
const logicProps = { dateFrom, dateTo, onChange, defaultValue, dateOptions, isDateFormatted }
const { open, openDateRange, close, setRangeDateFrom, setRangeDateTo, setDate } = useActions(
dateFilterLogic(logicProps)
)
const { isOpen, isDateRangeOpen, rangeDateFrom, rangeDateTo, value, isFixedDateRange, isRollingDateRange } =
useValues(dateFilterLogic(logicProps))

const optionsRef = useRef<HTMLDivElement | null>(null)
const rollingDateRangeRef = useRef<HTMLDivElement | null>(null)

function dropdownOnClick(e: React.MouseEvent): void {
e.preventDefault()
open()
document.getElementById('daterange_selector')?.focus()
}

function onApplyClick(): void {
close()
const formattedRangeDateFrom = dayjs(rangeDateFrom).format('YYYY-MM-DD')
const formattedRangeDateTo = dayjs(rangeDateTo).format('YYYY-MM-DD')
setDate(formattedRangeDateFrom, formattedRangeDateTo)
}

const popupOverlay = isDateRangeOpen ? (
<DateFilterRangeExperiment
getPopupContainer={getPopupContainer}
onClick={dropdownOnClick}
onDateFromChange={(date) => setRangeDateFrom(date)}
onDateToChange={(date) => setRangeDateTo(date)}
onApplyClick={onApplyClick}
onClickOutside={close}
rangeDateFrom={rangeDateFrom}
rangeDateTo={rangeDateTo}
disableBeforeYear={2015}
/>
) : (
<div ref={optionsRef} className="DateFilter" onClick={(e) => e.stopPropagation()}>
{[
benjackwhite marked this conversation as resolved.
Show resolved Hide resolved
dateOptions.map(({ key, values, inactive }) => {
if (key === 'Custom' && !showCustom) {
return null
}

if (inactive && value !== key) {
return null
}

const isHighlighted = dateFrom === values[0] && dateTo === values[1]
const dateValue = dateFilterToText(values[0], values[1], defaultValue, dateOptions, isDateFormatted)

return (
<Tooltip key={key} title={makeLabel ? makeLabel(dateValue) : undefined}>
<LemonButton
key={key}
onClick={() => {
setDate(values[0], values[1])
close()
}}
type={isHighlighted ? 'highlighted' : 'stealth'}
fullWidth
>
{key}
</LemonButton>
</Tooltip>
)
}),
]}
{showRollingRangePicker && (
<RollingDateRangeFilter
dateFrom={dateFrom}
selected={isRollingDateRange}
onChange={(fromDate) => {
setDate(fromDate, '')
close()
}}
makeLabel={makeLabel}
popupRef={rollingDateRangeRef}
/>
)}
<LemonDivider />
<LemonButton onClick={openDateRange} type={isFixedDateRange ? 'highlighted' : 'stealth'} fullWidth>
{'Custom fixed time period'}
</LemonButton>
</div>
)

return (
<LemonButtonWithPopup
data-attr="date-filter"
id="daterange_selector"
onClick={isOpen ? close : open}
value={value}
disabled={disabled}
style={{ ...style, border: '1px solid var(--border)' }} //TODO this is a css hack, so that this button aligns with others on the page which are still on antd
size={'small'}
type={'stealth'}
popup={{
onClickOutside: close,
visible: isOpen || isDateRangeOpen,
overlay: popupOverlay,
placement: 'bottom-start',
actionable: true,
closeOnClickInside: false,
additionalRefs: [rollingDateRangeRef, '.datefilter-datepicker'],
getPopupContainer,
}}
icon={<CalendarOutlined />}
>
{value}
</LemonButtonWithPopup>
)
}

export function DateFilter(props: RawDateFilterProps): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
const experimentEnabled = featureFlags[FEATURE_FLAGS.DATE_FILTER_EXPERIMENT] === 'test'
return experimentEnabled ? <DateFilterExperiment {...props} /> : <_DateFilter {...props} />
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.DateFilter {
padding: 0.5rem;
}
benjackwhite marked this conversation as resolved.
Show resolved Hide resolved
1 change: 0 additions & 1 deletion frontend/src/lib/components/DateFilter/DateFilterRange.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { useEffect, useRef, useState } from 'react'
import { Button } from 'antd'

import { dayjs } from 'lib/dayjs'
import { DatePicker } from '../DatePicker'

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.DateFilterRange__calendartoday {
display: inline-block;
position: relative;
}

.DateFilterRange__calendartoday::before {
content: '•' !important;
top: 0.5rem !important;
border: 0 !important;
font-size: 0.625em;
}
110 changes: 110 additions & 0 deletions frontend/src/lib/components/DateFilter/DateFilterRangeExperiment.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import React, { useState, useRef } from 'react'
import { Button } from 'antd'
import './DateFilterRangeExperiment.scss'
import { dayjs } from 'lib/dayjs'
import { DatePicker } from '../DatePicker'
import clsx from 'clsx'
import { useOutsideClickHandler } from 'lib/hooks/useOutsideClickHandler'

export function DateFilterRangeExperiment(props: {
onClickOutside: () => void
onClick: (e: React.MouseEvent) => void
onDateFromChange: (date?: dayjs.Dayjs) => void
onDateToChange: (date?: dayjs.Dayjs) => void
onApplyClick: () => void
rangeDateFrom?: string | dayjs.Dayjs | null
rangeDateTo?: string | dayjs.Dayjs | null
getPopupContainer?: (props: any) => HTMLElement
disableBeforeYear?: number
}): JSX.Element {
const dropdownRef = useRef<HTMLDivElement | null>(null)
const [calendarOpen, setCalendarOpen] = useState(true)

useOutsideClickHandler(
'.datefilter-datepicker',
() => {
if (calendarOpen) {
setCalendarOpen(false)
}
},
[calendarOpen],
['INPUT']
)

return (
<div ref={dropdownRef}>
<a
style={{
margin: '0 1rem',
color: 'rgba(0, 0, 0, 0.2)',
fontWeight: 700,
}}
href="#"
onClick={props.onClick}
>
&lt;
</a>
<hr style={{ margin: '0.5rem 0' }} />
<div style={{ padding: '0 1rem' }}>
<label className="secondary">From date</label>
<br />
<DatePicker.RangePicker
dropdownClassName="datefilter-datepicker"
getPopupContainer={props.getPopupContainer}
defaultValue={[
props.rangeDateFrom
? dayjs.isDayjs(props.rangeDateFrom)
? props.rangeDateFrom
: dayjs(props.rangeDateFrom)
: null,
props.rangeDateTo
? dayjs.isDayjs(props.rangeDateTo)
? props.rangeDateTo
: dayjs(props.rangeDateTo)
: null,
]}
open={calendarOpen}
onOpenChange={(open) => {
if (open) {
setCalendarOpen(open)
}
}}
onChange={(dates) => {
if (dates && dates.length === 2) {
props.onDateFromChange(dates[0] || undefined)
props.onDateToChange(dates[1] || undefined)
setCalendarOpen(false)
}
}}
popupStyle={{ zIndex: 999999 }}
disabledDate={(date) =>
(!!props.disableBeforeYear && date.year() < props.disableBeforeYear) || date.isAfter(dayjs())
}
dateRender={(current, today) => {
return (
<div
className={clsx('ant-picker-cell-inner', {
['DateFilterRange__calendartoday']:
current.date() === today.date() &&
current.month() === today.month() &&
current.year() === today.year(),
})}
>
{current.date()}
</div>
)
}}
/>
<br />
<Button
type="default"
disabled={!props.rangeDateTo || !props.rangeDateFrom}
style={{ marginTop: '1rem', marginBottom: '1rem' }}
onClick={props.onApplyClick}
>
Apply filter
</Button>
</div>
</div>
)
}
Loading