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.

refactor(lemon-ui): decouple LemonCalendar per-cell hooks from LemonButton (#65056)

Paul D'Ambrae877a6e9d259
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 76d2701152c0..89e95f12f74f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3004,10 +3004,6 @@ snapshots:
hash: v1.k794b7964.aaac7f23f9a219a36fe552eeb2ce78db7a6a4e888c3d784c906ee625f08551b2.ble3WT6n9mE7ijlFM6k-RZ1RY3zyNZRNQqYvyTSMuYg
lemon-ui-lemon-button--with-very-long-popover-to-the-bottom--light:
hash: v1.k794b7964.22bf3aff2387bc9fe0be60368f2dbaf387ac90e9d7e50da67b105a2a262919e2.Z9B3MO0-PGXtKS6u9b2m2Meb0HPHYlCtXtojeaKl_DU
- lemon-ui-lemon-calendar-lemon-calendar--custom-styles--dark:
- hash: v1.k794b7964.baca44acec1f2e9e1cef89dcf75bc6edc6a54c67060fc1cbb76c225a24d92893.GRhAG2QB3ezEo6BL7PNwpbrB5zYYsCb44VqdofLXNic
- lemon-ui-lemon-calendar-lemon-calendar--custom-styles--light:
- hash: v1.k794b7964.bbfe74c90d40f40a776d8192e3801359674a53f1b8edc7ca5b938a9ad017e8ba.fxdqMLzFdeHLIybSbYCrKDeWzzzIudUtwjmI0aDuxL0
lemon-ui-lemon-calendar-lemon-calendar--default--dark:
hash: v1.k794b7964.5cc5655547a3c164875acb55eced294598821b81155445536c69bafdfe84bab5.dqIgEZe6tvm57LKOGn33UqlK-CdtktCizCihcYbgXPA
lemon-ui-lemon-calendar-lemon-calendar--default--light:
@@ -3036,10 +3032,18 @@ snapshots:
hash: v1.k794b7964.5b7f8fc424da29131233d304afcd8c418f79386cf590c98490e76ef1619fb45a.25TRqcaXkkpvNx6CJobzTR07FkZEGqOxkJSsCfuYHyE
lemon-ui-lemon-calendar-lemon-calendar--multiple-months--light:
hash: v1.k794b7964.e846f27f1e6699e58149f39e333b5191f0c1dd7bfd466d6efd66c7b5510a69e5.861M9fa7ItLq-GPkUx5uoMzNyrs1rIEWsMrXyw6GAXA
+ lemon-ui-lemon-calendar-lemon-calendar--range-selection--dark:
+ hash: v1.k794b7964.1706853c2e36898d55307af95c50ab517bbb8c0f79c29318a803f9f384057f59.ougW9eZ3tW9JoShtLQERoIq2Cmx2qhONV9wW_a4rfUw
+ lemon-ui-lemon-calendar-lemon-calendar--range-selection--light:
+ hash: v1.k794b7964.dfa6345f2507f5ecc54088d26b9ec299622c504ac4891f64ccd99e0a3235e72f.fyH8Og_JDhY-zvDVolJP27FzVnUmiT5bsFSH8YNFQ_s
lemon-ui-lemon-calendar-lemon-calendar--saturday-first--dark:
hash: v1.k794b7964.17911f2bb2e5d81ca3e5874bbc2984a88e1d365dff1bdabae00c7462b1a1a7df.7itKfZmIgJiL7PLLxt4Y7xvWcwakalUY4jKn0MSkTco
lemon-ui-lemon-calendar-lemon-calendar--saturday-first--light:
hash: v1.k794b7964.c2f367de16677442b5cb270a612045666a223ec9cca01b5e4f37db1741116daf.LMw8G6RfZMS2P6r0A1shod7CYpz_ELPjlClafd4giGY
+ lemon-ui-lemon-calendar-lemon-calendar--single-selection--dark:
+ hash: v1.k794b7964.ce1fbe645a41122cc1feb73d05d30d87a1f8a02f849c7d3c23454e82a6639d8b.CvqJIO8nA_wGVzUo6eVL6K6DJZQo8wQ32nBaan1fxDU
+ lemon-ui-lemon-calendar-lemon-calendar--single-selection--light:
+ hash: v1.k794b7964.59c783c66d128b6b515ee6e287e3b14c2ba244922213ca835ecd8a5331af72aa.FYhmDqtiHQPwAJqEcN-Vff1CVt1QoSzpfVL8kelImAo
lemon-ui-lemon-calendar-lemon-calendar--sunday-first--dark:
hash: v1.k794b7964.5cc5655547a3c164875acb55eced294598821b81155445536c69bafdfe84bab5.Ff1kUDrm3_vPzAwk01tdDz7s5uHOMfaM-4uCP0YXl4A
lemon-ui-lemon-calendar-lemon-calendar--sunday-first--light:
diff --git a/frontend/src/lib/components/DateFilter/FixedRangeWithTimePicker.tsx b/frontend/src/lib/components/DateFilter/FixedRangeWithTimePicker.tsx
index 02ace9c16c10..1d77bc61a344 100644
--- a/frontend/src/lib/components/DateFilter/FixedRangeWithTimePicker.tsx
+++ b/frontend/src/lib/components/DateFilter/FixedRangeWithTimePicker.tsx
@@ -98,47 +98,17 @@ export function FixedRangeWithTimePicker({
}
}}
leftmostMonth={(selectingStart ? localFrom : localTo)?.startOf('month')}
- getLemonButtonProps={({ date, props, dayIndex }) => {
- if ((localFrom && date.isSame(localFrom, 'd')) || (localTo && date.isSame(localTo, 'd'))) {
- const isStart = localFrom && date.isSame(localFrom, 'd')
- const isEnd = localTo && date.isSame(localTo, 'd')
- return {
- ...props,
- className:
- isStart && isEnd
- ? props.className
- : clsx(
- props.className,
- {
- 'rounded-r-none': isStart && dayIndex < 6,
- 'rounded-l-none': isEnd && dayIndex > 0,
- },
- 'LemonCalendar__range--boundary'
- ),
- type: 'primary',
- }
- } else if (
+ getDateState={({ date }) => ({
+ isStart: !!(localFrom && date.isSame(localFrom, 'd')),
+ isEnd: !!(localTo && date.isSame(localTo, 'd')),
+ isBetween: !!(
localFrom &&
localTo &&
date.isAfter(localFrom, 'd') &&
date.isBefore(localTo, 'd')
- ) {
- return {
- ...props,
- className: clsx(
- props.className,
- dayIndex === 0
- ? 'rounded-r-none'
- : dayIndex === 6
- ? 'rounded-l-none'
- : 'rounded-none'
- ),
- active: true,
- }
- }
- return props
- }}
- getLemonButtonTimeProps={(timeProps) => {
+ ),
+ })}
+ getTimeState={(timeProps) => {
const currentValue = selectingStart ? localFrom : localTo
const selected = currentValue
? timeProps.unit === 'h' && use24HourFormat
@@ -148,8 +118,6 @@ export function FixedRangeWithTimePicker({
return {
active: selected === String(timeProps.value),
- className: 'rounded-none',
- 'data-attr': `${timeProps.value}-${timeProps.unit}`,
onClick: () => {
// Fall back to today so the user can set the time
// before picking a date — otherwise clicking time
diff --git a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.stories.tsx b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.stories.tsx
index 9eef2adaf7fd..72cd503f6805 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.stories.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.stories.tsx
@@ -25,15 +25,22 @@ export const Default: Story = { args: {} }
export const MultipleMonths: Story = { args: { months: 3 } }
-export const CustomStyles: Story = {
+export const RangeSelection: Story = {
args: {
- getLemonButtonProps: ({ date, props }) => {
- return {
- ...props,
- active: date.day() % 2 === 0,
- type: date.date() % 10 === 0 ? 'primary' : undefined,
- }
- },
+ getDateState: ({ date }) => ({
+ isStart: date.date() === 10,
+ isEnd: date.date() === 20,
+ isBetween: date.date() > 10 && date.date() < 20,
+ }),
+ },
+}
+
+export const SingleSelection: Story = {
+ args: {
+ getDateState: ({ date }) => ({
+ selected: date.date() === 15,
+ disabledReason: date.date() > 20 ? 'Cannot select dates after the 20th' : undefined,
+ }),
},
}
diff --git a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.test.tsx b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.test.tsx
index d0250342d08e..375e470f4950 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.test.tsx
@@ -127,70 +127,106 @@ describe('LemonCalendar', () => {
expect(await within(calendar).findByText(thisMonth)).toBeTruthy()
})
- test('calls getLemonButtonProps for each day', async () => {
- const calls: any = []
- const { container } = render(
+ test('calls getDateState for each day with its date', async () => {
+ const dates: dayjs.Dayjs[] = []
+ render(
<LemonCalendar
leftmostMonth={dayjs('2020-02-20')}
- getLemonButtonProps={({ date, props: defaultProps }) => {
- const props = { ...defaultProps }
- if (date.isSame('2020-02-14')) {
- props['data-attr'] = 's6brap2ev'
- props['className'] = 'yolo'
- }
- calls.push([date, props])
- return props
+ getDateState={({ date }) => {
+ dates.push(date)
+ return {}
}}
/>
)
- expect(calls.length).toBe(35)
- expect(calls).toEqual([
- [dayjs('2020-01-26'), { className: 'flex-col opacity-25' }],
- [dayjs('2020-01-27'), { className: 'flex-col opacity-25' }],
- [dayjs('2020-01-28'), { className: 'flex-col opacity-25' }],
- [dayjs('2020-01-29'), { className: 'flex-col opacity-25' }],
- [dayjs('2020-01-30'), { className: 'flex-col opacity-25' }],
- [dayjs('2020-01-31'), { className: 'flex-col opacity-25' }],
- [dayjs('2020-02-01'), { className: 'flex-col' }],
- [dayjs('2020-02-02'), { className: 'flex-col' }],
- [dayjs('2020-02-03'), { className: 'flex-col' }],
- [dayjs('2020-02-04'), { className: 'flex-col' }],
- [dayjs('2020-02-05'), { className: 'flex-col' }],
- [dayjs('2020-02-06'), { className: 'flex-col' }],
- [dayjs('2020-02-07'), { className: 'flex-col' }],
- [dayjs('2020-02-08'), { className: 'flex-col' }],
- [dayjs('2020-02-09'), { className: 'flex-col' }],
- [dayjs('2020-02-10'), { className: 'flex-col' }],
- [dayjs('2020-02-11'), { className: 'flex-col' }],
- [dayjs('2020-02-12'), { className: 'flex-col' }],
- [dayjs('2020-02-13'), { className: 'flex-col' }],
- [dayjs('2020-02-14'), { className: 'yolo', 'data-attr': 's6brap2ev' }],
- [dayjs('2020-02-15'), { className: 'flex-col' }],
- [dayjs('2020-02-16'), { className: 'flex-col' }],
- [dayjs('2020-02-17'), { className: 'flex-col' }],
- [dayjs('2020-02-18'), { className: 'flex-col' }],
- [dayjs('2020-02-19'), { className: 'flex-col' }],
- [dayjs('2020-02-20'), { className: 'flex-col' }],
- [dayjs('2020-02-21'), { className: 'flex-col' }],
- [dayjs('2020-02-22'), { className: 'flex-col' }],
- [dayjs('2020-02-23'), { className: 'flex-col' }],
- [dayjs('2020-02-24'), { className: 'flex-col' }],
- [dayjs('2020-02-25'), { className: 'flex-col' }],
- [dayjs('2020-02-26'), { className: 'flex-col' }],
- [dayjs('2020-02-27'), { className: 'flex-col' }],
- [dayjs('2020-02-28'), { className: 'flex-col' }],
- [dayjs('2020-02-29'), { className: 'flex-col' }],
+ expect(dates.length).toBe(35)
+ expect(dates).toEqual([
+ dayjs('2020-01-26'),
+ dayjs('2020-01-27'),
+ dayjs('2020-01-28'),
+ dayjs('2020-01-29'),
+ dayjs('2020-01-30'),
+ dayjs('2020-01-31'),
+ dayjs('2020-02-01'),
+ dayjs('2020-02-02'),
+ dayjs('2020-02-03'),
+ dayjs('2020-02-04'),
+ dayjs('2020-02-05'),
+ dayjs('2020-02-06'),
+ dayjs('2020-02-07'),
+ dayjs('2020-02-08'),
+ dayjs('2020-02-09'),
+ dayjs('2020-02-10'),
+ dayjs('2020-02-11'),
+ dayjs('2020-02-12'),
+ dayjs('2020-02-13'),
+ dayjs('2020-02-14'),
+ dayjs('2020-02-15'),
+ dayjs('2020-02-16'),
+ dayjs('2020-02-17'),
+ dayjs('2020-02-18'),
+ dayjs('2020-02-19'),
+ dayjs('2020-02-20'),
+ dayjs('2020-02-21'),
+ dayjs('2020-02-22'),
+ dayjs('2020-02-23'),
+ dayjs('2020-02-24'),
+ dayjs('2020-02-25'),
+ dayjs('2020-02-26'),
+ dayjs('2020-02-27'),
+ dayjs('2020-02-28'),
+ dayjs('2020-02-29'),
])
- const fourteen = getByDataAttr(container, 's6brap2ev')
- expect(fourteen).toBeTruthy()
- expect(fourteen.className.split(' ')).toContain('yolo')
})
- test('calls getLemonButtonTimeProps for each time', async () => {
+ test.each([
+ ['selected', { selected: true }, 'LemonButton--primary'],
+ ['range start', { isStart: true }, 'LemonCalendar__range--boundary'],
+ ['range end', { isEnd: true }, 'LemonCalendar__range--boundary'],
+ ['in range', { isBetween: true }, 'LemonButton--active'],
+ ])('renders the %s date state as %j', async (_name, state, expectedClass) => {
+ const { container } = render(
+ <LemonCalendar
+ leftmostMonth={dayjs('2020-02-01')}
+ months={1}
+ getDateState={({ date }) => (date.isSame('2020-02-14', 'd') ? state : {})}
+ />
+ )
+ const fourteen = within(container).getByText('14').closest('[data-attr="lemon-calendar-day"]')
+ expect(fourteen?.className.split(' ')).toContain(expectedClass)
+ })
+
+ test('disables a date when getDateState returns a disabledReason', async () => {
+ const { container } = render(
+ <LemonCalendar
+ leftmostMonth={dayjs('2020-02-01')}
+ months={1}
+ getDateState={({ date }) => (date.isSame('2020-02-14', 'd') ? { disabledReason: 'nope' } : {})}
+ />
+ )
+ const fourteen = within(container).getByText('14').closest('[data-attr="lemon-calendar-day"]')
+ expect(fourteen?.getAttribute('aria-disabled')).toBe('true')
+ })
+
+ test('renders the default cell styling when no getDateState is given', async () => {
+ const { container } = render(<LemonCalendar leftmostMonth={dayjs('2020-02-01')} months={1} />)
+ // 30 only exists as a faded out-of-month (January) cell in the February grid
+ const outOfMonth = within(container).getByText('30').closest('[data-attr="lemon-calendar-day"]')
+ expect(outOfMonth?.className.split(' ')).toContain('opacity-25')
+ const inMonth = within(container).getByText('15').closest('[data-attr="lemon-calendar-day"]')
+ expect(inMonth?.className.split(' ')).toContain('flex-col')
+ expect(inMonth?.className.split(' ')).not.toContain('opacity-25')
+ })
+
+ test('marks today with the today class', async () => {
+ const { container } = render(<LemonCalendar />)
+ expect(container.querySelector('.LemonCalendar__today')).toBeTruthy()
+ })
+
+ test('calls getTimeState for each time', async () => {
const calls: any = []
render(
<LemonCalendar
- getLemonButtonTimeProps={({ unit, value }) => {
+ getTimeState={({ unit, value }) => {
calls.push([unit, value])
return {}
}}
@@ -222,7 +258,7 @@ describe('LemonCalendar', () => {
const calls: any = []
render(
<LemonCalendar
- getLemonButtonTimeProps={({ unit, value }) => {
+ getTimeState={({ unit, value }) => {
calls.push([unit, value])
return {}
}}
diff --git a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.tsx b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.tsx
index bd2dd3adb168..f7a8cddb7d3a 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendar.tsx
@@ -19,10 +19,10 @@ export interface LemonCalendarProps {
leftmostMonth?: dayjs.Dayjs
/** Called if the user changed the month in the calendar */
onLeftmostMonthChanged?: (date: dayjs.Dayjs) => void
- /** Use custom LemonButton properties for each date */
- getLemonButtonProps?: (opts: GetLemonButtonPropsOpts) => LemonButtonProps
- /** Use custom LemonButton properties for each date */
- getLemonButtonTimeProps?: (opts: GetLemonButtonTimePropsOpts) => LemonButtonProps
+ /** Describe the selection state of each date; the calendar owns the resulting styling */
+ getDateState?: (opts: GetDateStateOpts) => LemonCalendarDateState
+ /** Describe the selection state of each time cell; the calendar owns the resulting styling */
+ getTimeState?: (opts: GetTimeStateOpts) => LemonCalendarTimeState
/** Number of months */
months?: number
/** 0 or unset for Sunday, 1 for Monday. */
@@ -33,17 +33,100 @@ export interface LemonCalendarProps {
use24HourFormat?: boolean
}
-export interface GetLemonButtonPropsOpts {
+export interface GetDateStateOpts {
date: dayjs.Dayjs
- props: LemonButtonProps
dayIndex: number
weekIndex: number
}
-export interface GetLemonButtonTimePropsOpts {
+
+/**
+ * A decoupled description of how a single date should render, mirroring Quill's calendar vocabulary.
+ * `selected` takes precedence: when set, the range flags (`isStart`/`isEnd`/`isBetween`) are ignored.
+ */
+export interface LemonCalendarDateState {
+ /** Disable the date and explain why on hover */
+ disabledReason?: string
+ /** Render as a selected single date; wins over the range flags below */
+ selected?: boolean
+ /** Render as the start boundary of a range */
+ isStart?: boolean
+ /** Render as the end boundary of a range */
+ isEnd?: boolean
+ /** Render as a date sitting between the range boundaries */
+ isBetween?: boolean
+}
+
+export interface GetTimeStateOpts {
unit: 'h' | 'm' | 'a'
value: number | string
}
+/** A decoupled description of how a single time cell should render. */
+export interface LemonCalendarTimeState {
+ active?: boolean
+ disabledReason?: string
+ onClick?: () => void
+}
+
+export function timeDataAttr({ unit, value }: GetTimeStateOpts): string {
+ return `${value}-${unit}`
+}
+
+function timeStateToButtonProps(state: LemonCalendarTimeState, opts: GetTimeStateOpts): LemonButtonProps {
+ return {
+ active: state.active,
+ disabledReason: state.disabledReason,
+ onClick: state.onClick,
+ className: 'rounded-none',
+ 'data-attr': timeDataAttr(opts),
+ }
+}
+
+function dateStateToButtonProps(
+ state: LemonCalendarDateState,
+ defaultProps: LemonButtonProps,
+ dayIndex: number
+): LemonButtonProps {
+ const props: LemonButtonProps = { ...defaultProps, disabledReason: state.disabledReason }
+ const isFirstDayOfWeek = dayIndex === 0
+ const isLastDayOfWeek = dayIndex === 6
+
+ if (state.selected) {
+ return { ...props, status: 'default', type: 'primary' }
+ }
+
+ if (state.isStart || state.isEnd) {
+ return {
+ ...props,
+ className:
+ state.isStart && state.isEnd
+ ? props.className
+ : clsx(
+ props.className,
+ {
+ 'rounded-r-none': state.isStart && !isLastDayOfWeek,
+ 'rounded-l-none': state.isEnd && !isFirstDayOfWeek,
+ },
+ 'LemonCalendar__range--boundary'
+ ),
+ type: 'primary',
+ }
+ }
+
+ if (state.isBetween) {
+ return {
+ ...props,
+ className: clsx(
+ props.className,
+ isFirstDayOfWeek ? 'rounded-r-none' : isLastDayOfWeek ? 'rounded-l-none' : 'rounded-none'
+ ),
+ active: true,
+ }
+ }
+
+ return props
+}
+
const dayLabels = ['su', 'mo', 'tu', 'we', 'th', 'fr', 'sa']
export const LemonCalendar = forwardRef(function LemonCalendar(
@@ -65,6 +148,11 @@ export const LemonCalendar = forwardRef(function LemonCalendar(
}
}, [props.leftmostMonth]) // oxlint-disable-line react-hooks/exhaustive-deps
+ const timeButtonProps = (opts: GetTimeStateOpts): LemonButtonProps | undefined => {
+ const timeState = props.getTimeState?.(opts)
+ return timeState ? timeStateToButtonProps(timeState, opts) : undefined
+ }
+
return (
<div
ref={ref}
@@ -147,13 +235,14 @@ export const LemonCalendar = forwardRef(function LemonCalendar(
}),
}
- const buttonProps =
- props.getLemonButtonProps?.({
- dayIndex: day,
- weekIndex: week,
- date,
- props: defaultProps,
- }) ?? defaultProps
+ const dateState = props.getDateState?.({
+ dayIndex: day,
+ weekIndex: week,
+ date,
+ })
+ const buttonProps = dateState
+ ? dateStateToButtonProps(dateState, defaultProps, day)
+ : defaultProps
return (
<td key={day}>
<LemonButton
@@ -178,10 +267,7 @@ export const LemonCalendar = forwardRef(function LemonCalendar(
<div className="LemonCalendar__time absolute top-0 bottom-0 right-0 flex divide-x border-l">
<ScrollableShadows direction="vertical">
{(use24HourFormat ? range(0, 24) : [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]).map((hour) => {
- const buttonProps = props.getLemonButtonTimeProps?.({
- unit: 'h',
- value: hour,
- })
+ const buttonProps = timeButtonProps({ unit: 'h', value: hour })
return (
<LemonButton fullWidth key={hour} {...buttonProps}>
@@ -194,10 +280,7 @@ export const LemonCalendar = forwardRef(function LemonCalendar(
{granularity === 'minute' && (
<ScrollableShadows direction="vertical">
{range(0, 60).map((minute) => {
- const buttonProps = props.getLemonButtonTimeProps?.({
- unit: 'm',
- value: minute,
- })
+ const buttonProps = timeButtonProps({ unit: 'm', value: minute })
return (
<LemonButton fullWidth key={minute} {...buttonProps}>
<span className="w-full text-center px-2">
@@ -211,10 +294,10 @@ export const LemonCalendar = forwardRef(function LemonCalendar(
)}
{!use24HourFormat && (
<div>
- <LemonButton fullWidth {...props.getLemonButtonTimeProps?.({ unit: 'a', value: 'am' })}>
+ <LemonButton fullWidth {...timeButtonProps({ unit: 'a', value: 'am' })}>
<span className="w-full text-center">AM</span>
</LemonButton>
- <LemonButton fullWidth {...props.getLemonButtonTimeProps?.({ unit: 'a', value: 'pm' })}>
+ <LemonButton fullWidth {...timeButtonProps({ unit: 'a', value: 'pm' })}>
<span className="w-full text-center">PM</span>
</LemonButton>
</div>
diff --git a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.test.tsx b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.test.tsx
index f5a9e72937bb..00a57f8ea229 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.test.tsx
@@ -11,13 +11,13 @@ import {
import { getByDataAttr } from '~/test/byDataAttr'
-import { GetLemonButtonTimePropsOpts } from './LemonCalendar'
+import { GetTimeStateOpts } from './LemonCalendar'
const createClickHelpers = (
container: HTMLElement
): {
clickOnDate: (day: string) => Promise<void>
- clickOnTime: (props: GetLemonButtonTimePropsOpts) => Promise<void>
+ clickOnTime: (props: GetTimeStateOpts) => Promise<void>
} => ({
clickOnDate: async (day: string): Promise<void> => {
const element = container.querySelector('.LemonCalendar__month') as HTMLElement
@@ -26,7 +26,7 @@ const createClickHelpers = (
await userEvent.click(getByDataAttr(container, 'lemon-calendar-select-apply'))
}
},
- clickOnTime: async (props: GetLemonButtonTimePropsOpts): Promise<void> => {
+ clickOnTime: async (props: GetTimeStateOpts): Promise<void> => {
const element = getTimeElement(container.querySelector('.LemonCalendar__time'), props)
if (element) {
await userEvent.click(element)
@@ -43,7 +43,7 @@ const renderLemonCalendarSelect = (
onClose: jest.Mock
onChange: jest.Mock
clickOnDate: (day: string) => Promise<void>
- clickOnTime: (props: GetLemonButtonTimePropsOpts) => Promise<void>
+ clickOnTime: (props: GetTimeStateOpts) => Promise<void>
} => {
const onClose = jest.fn()
const onChange = jest.fn()
diff --git a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.tsx b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.tsx
index ed62a94e4900..76bff12615dc 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.tsx
@@ -5,31 +5,21 @@ import { IconX } from '@posthog/icons'
import { dayjs, dayjsNowInTimezone } from 'lib/dayjs'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { LemonButton, LemonButtonProps, LemonButtonWithSideActionProps, SideAction } from 'lib/lemon-ui/LemonButton'
+import { LemonButton, LemonButtonWithSideActionProps, SideAction } from 'lib/lemon-ui/LemonButton'
import {
- GetLemonButtonTimePropsOpts,
+ GetTimeStateOpts,
LemonCalendar,
LemonCalendarProps,
+ timeDataAttr,
} from 'lib/lemon-ui/LemonCalendar/LemonCalendar'
import { LemonSwitch } from '../LemonSwitch'
import { Popover } from '../Popover'
-function timeDataAttr({ unit, value }: GetLemonButtonTimePropsOpts): string {
- return `${value}-${unit}`
-}
-
-export function getTimeElement(
- parent: HTMLElement | null,
- props: GetLemonButtonTimePropsOpts
-): HTMLDivElement | undefined | null {
+export function getTimeElement(parent: HTMLElement | null, props: GetTimeStateOpts): HTMLDivElement | undefined | null {
return parent?.querySelector(`[data-attr="${timeDataAttr(props)}"]`)
}
-function scrollToTimeElement(
- calendarEl: HTMLDivElement | null,
- props: GetLemonButtonTimePropsOpts,
- skipAnimation: boolean
-): void {
+function scrollToTimeElement(calendarEl: HTMLDivElement | null, props: GetTimeStateOpts, skipAnimation: boolean): void {
getTimeElement(calendarEl, props)?.scrollIntoView({
block: 'start',
inline: 'nearest',
@@ -39,7 +29,7 @@ function scrollToTimeElement(
function proposedDate(
target: dayjs.Dayjs | null,
- { value, unit }: GetLemonButtonTimePropsOpts,
+ { value, unit }: GetTimeStateOpts,
use24HourFormat: boolean = false
): dayjs.Dayjs {
let date = target || dayjs().startOf('day')
@@ -163,7 +153,7 @@ export function LemonCalendarSelect({
}
})
- const onTimeClick = (props: GetLemonButtonTimePropsOpts): void => {
+ const onTimeClick = (props: GetTimeStateOpts): void => {
const date = proposedDate(selectValue, props, use24HourFormat)
scrollToTime(date, false)
setSelectValue(date)
@@ -182,38 +172,26 @@ export function LemonCalendarSelect({
onDateClick={onDateClick}
leftmostMonth={selectValue?.startOf('month')}
months={months}
- getLemonButtonProps={({ date, props }) => {
- const modifiedProps: LemonButtonProps = { ...props }
+ getDateState={({ date }) => {
+ let disabledReason: string | undefined
if (selectionPeriod) {
- const isToday = date.isSame(today, 'date')
-
- modifiedProps.disabledReason = getDateDisabledReason(
- selectionPeriod,
- date,
- today,
- selectionPeriodLimit
- )
-
- // select date disabled reason
- if (selectValue && isToday) {
- // select time disabled reason
+ disabledReason = getDateDisabledReason(selectionPeriod, date, today, selectionPeriodLimit)
+
+ if (selectValue && date.isSame(today, 'date')) {
const selectedTimeOnDate = cloneTimeToDate(date, selectValue)
if (selectionPeriod === 'upcoming' && selectedTimeOnDate.isBefore(now)) {
- modifiedProps.disabledReason = 'Pick a time in the future first'
+ disabledReason = 'Pick a time in the future first'
} else if (selectionPeriod === 'past' && selectedTimeOnDate.isAfter(now)) {
- modifiedProps.disabledReason = 'Pick a time in the past first'
+ disabledReason = 'Pick a time in the past first'
}
}
}
- if (date.isSame(selectValue, 'd')) {
- return { ...modifiedProps, status: 'default', type: 'primary' }
- }
- return modifiedProps
+ return { disabledReason, selected: date.isSame(selectValue, 'd') }
}}
- getLemonButtonTimeProps={(props) => {
+ getTimeState={(props) => {
const selected = selectValue
? props.unit === 'h' && use24HourFormat
? String(selectValue.hour())
@@ -231,9 +209,7 @@ export function LemonCalendarSelect({
return {
active: selected === String(props.value),
- className: 'rounded-none',
- 'data-attr': timeDataAttr(props),
- disabledReason: disabledReason,
+ disabledReason,
onClick: () => {
if (selected != props.value) {
onTimeClick(props)
diff --git a/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRangeInline.tsx b/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRangeInline.tsx
index ea59c4f2ce1c..8608df970c6d 100644
--- a/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRangeInline.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCalendarRange/LemonCalendarRangeInline.tsx
@@ -1,4 +1,3 @@
-import clsx from 'clsx'
import { useEffect, useState } from 'react'
import { dayjs } from 'lib/dayjs'
@@ -96,35 +95,11 @@ export function LemonCalendarRangeInline({
leftmostMonth={leftmostMonth}
onLeftmostMonthChanged={setLeftmostMonth}
months={shownMonths}
- getLemonButtonProps={({ date, props, dayIndex }) => {
- if (date.isSame(rangeStart, 'd') || date.isSame(rangeEnd, 'd')) {
- return {
- ...props,
- className:
- date.isSame(rangeStart, 'd') && date.isSame(rangeEnd, 'd')
- ? props.className
- : clsx(
- props.className,
- {
- 'rounded-r-none': date.isSame(rangeStart, 'd') && dayIndex < 6,
- 'rounded-l-none': date.isSame(rangeEnd, 'd') && dayIndex > 0,
- },
- 'LemonCalendar__range--boundary'
- ),
- type: 'primary',
- }
- } else if (rangeStart && rangeEnd && date > rangeStart && date < rangeEnd) {
- return {
- ...props,
- className: clsx(
- props.className,
- dayIndex === 0 ? 'rounded-r-none' : dayIndex === 6 ? 'rounded-l-none' : 'rounded-none'
- ),
- active: true,
- }
- }
- return props
- }}
+ getDateState={({ date }) => ({
+ isStart: date.isSame(rangeStart, 'd'),
+ isEnd: date.isSame(rangeEnd, 'd'),
+ isBetween: !!(rangeStart && rangeEnd && date > rangeStart && date < rangeEnd),
+ })}
/>
)
}