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.

17.3 KB
Raw Blame
import '@testing-library/jest-dom'

import { cleanup, render, screen } from '@testing-library/react'

import { ScheduledChangeOperationType } from '~/types'

import { makeScheduledChange } from './makeScheduledChange'
import { ScheduleOccurrence } from './scheduleOccurrences'
import { ScheduleTimeline } from './ScheduleTimeline'

function occurrence(overrides: Partial<ScheduleOccurrence> = {}): ScheduleOccurrence {
    return {
        timestamp: '2099-08-26T10:22:00Z',
        operation: ScheduledChangeOperationType.UpdateStatus,
        schedule: makeScheduledChange({ scheduled_at: '2099-08-26T10:22:00Z' }),
        projected: { active: true, rolloutPercentage: 50, variantCount: null },
        addedRolloutPercentage: null,
        rolloutUnchanged: false,
        needsApproval: false,
        ...overrides,
    }
}

function coveredStep(
    active: boolean,
    addedRolloutPercentage: number,
    overrides: Partial<ScheduleOccurrence> = {}
): ScheduleOccurrence {
    return occurrence({
        operation: ScheduledChangeOperationType.AddReleaseCondition,
        addedRolloutPercentage,
        rolloutUnchanged: true,
        projected: { active, rolloutPercentage: 100, variantCount: null },
        ...overrides,
    })
}

describe('ScheduleTimeline', () => {
    // The component reads the wall clock to place marks, so an unpinned clock leaves the fixed
    // fixture dates decades away and squashes every x onto the right edge.
    beforeAll(() => {
        jest.useFakeTimers()
        jest.setSystemTime(new Date('2099-08-25T10:22:00Z'))
    })

    afterAll(() => {
        jest.useRealTimers()
    })

    afterEach(() => {
        cleanup()
    })

    it('renders nothing for zero occurrences', () => {
        const { container } = render(<ScheduleTimeline occurrences={[]} currentRolloutPercentage={10} timezone="UTC" />)

        expect(container).toBeEmptyDOMElement()
    })

    it.each([
        { name: 'this year, without the year', overrides: {}, expected: 'Next: enabled on Aug 26, 10:22 AM' },
        {
            name: 'a later year, with the year',
            overrides: { timestamp: '2100-08-26T10:22:00Z' },
            expected: 'Next: enabled on Aug 26, 2100 10:22 AM',
        },
        {
            name: 'a variant change, with a verb',
            overrides: {
                operation: ScheduledChangeOperationType.UpdateVariants,
                projected: { active: true, rolloutPercentage: 50, variantCount: 3 },
            },
            expected: 'Next: switch to 3 variants on Aug 26, 10:22 AM',
        },
    ])('summarizes one occurrence without a chart: $name', ({ overrides, expected }) => {
        const { container } = render(
            <ScheduleTimeline occurrences={[occurrence(overrides)]} currentRolloutPercentage={10} timezone="UTC" />
        )

        expect(screen.getByText(expected)).toBeInTheDocument()
        expect(container.querySelector('svg')).not.toBeInTheDocument()
    })

    it('summarizes an added condition by its own rollout, not the projected max', () => {
        const addCondition = occurrence({
            operation: ScheduledChangeOperationType.AddReleaseCondition,
            addedRolloutPercentage: 10,
            // Projected max stays at an existing 100% condition set; the summary must not report it.
            projected: { active: true, rolloutPercentage: 100, variantCount: null },
        })
        render(<ScheduleTimeline occurrences={[addCondition]} currentRolloutPercentage={100} timezone="UTC" />)

        expect(screen.getByText('Next: add a condition at 10% rollout on Aug 26, 10:22 AM')).toBeInTheDocument()
    })

    it.each([
        {
            name: 'a flag that serves the level',
            active: true,
            expected:
                'Next: add a condition at 25% rollout, no change from the 100% the flag already serves on Aug 26, 10:22 AM',
        },
        {
            name: 'a flag that is off',
            active: false,
            expected:
                'Next: add a condition at 25% rollout, no change from the 100% set on this disabled flag on Aug 26, 10:22 AM',
        },
    ])('summarizes a covered condition add as no change on $name', ({ active, expected }) => {
        render(
            <ScheduleTimeline occurrences={[coveredStep(active, 25)]} currentRolloutPercentage={100} timezone="UTC" />
        )

        expect(screen.getByText(expected)).toBeInTheDocument()
    })

    it.each([
        {
            name: 'a flag that serves the level',
            active: true,
            expectedTitle: 'This condition sits at 25%, at or below the 100% the flag already serves',
        },
        {
            name: 'a flag that is off',
            active: false,
            expectedTitle: 'This condition sits at 25%, at or below the 100% set on this disabled flag',
        },
    ])(
        'labels a step that holds its level, so a flat line does not read as broken: $name',
        ({ active, expectedTitle }) => {
            const { container } = render(
                <ScheduleTimeline
                    occurrences={[
                        coveredStep(active, 25),
                        coveredStep(active, 50, { timestamp: '2099-08-28T10:22:00Z' }),
                    ]}
                    currentRolloutPercentage={100}
                    timezone="UTC"
                />
            )

            expect(screen.getAllByText('still 100%')).toHaveLength(2)
            expect(container.querySelector('g > title')?.textContent).toEqual(expectedTitle)
        }
    )

    it('drops a step label that would overlap an earlier one on the same level', () => {
        render(
            <ScheduleTimeline
                occurrences={[
                    coveredStep(true, 25),
                    coveredStep(true, 50, { timestamp: '2099-08-27T10:22:00Z' }),
                    coveredStep(true, 75, { timestamp: '2099-09-24T10:22:00Z' }),
                ]}
                currentRolloutPercentage={100}
                timezone="UTC"
            />
        )

        expect(screen.getAllByText('still 100%')).toHaveLength(2)
    })

    it('keeps a dropped step label reachable as the mark title', () => {
        // The drop rule reaches any two levels within about 10 points, not only equal ones: one font
        // size is 9 units and the plot spends 0.9 units per point. These two land 4.5 units apart
        // vertically and overlap horizontally, so the 100% label is dropped. Neither step needs
        // approval or holds its level, so without the title its mark carries no text at all.
        const step = (timestamp: string, rollout: number): ScheduleOccurrence =>
            occurrence({
                timestamp,
                operation: ScheduledChangeOperationType.AddReleaseCondition,
                addedRolloutPercentage: rollout,
                projected: { active: true, rolloutPercentage: rollout, variantCount: null },
            })
        const { container } = render(
            <ScheduleTimeline
                occurrences={[
                    step('2099-08-25T11:22:00Z', 95),
                    step('2099-08-25T12:22:00Z', 100),
                    step('2099-09-24T10:22:00Z', 100),
                ]}
                currentRolloutPercentage={90}
                timezone="UTC"
            />
        )

        expect(screen.getByText('95%')).toBeInTheDocument()
        expect(Array.from(container.querySelectorAll('g > title')).map((node) => node.textContent)).toEqual([
            '100% rollout',
        ])
    })

    it.each([
        {
            name: 'a full-rollout step label',
            earlier: coveredStep(true, 25),
            earlierText: 'still 100%',
            offAt: '2099-08-27T10:22:00Z',
        },
        {
            // The two estimated label boxes sit about two units apart. Only the minimum space that the
            // layout keeps between labels sends "Off" up a lane.
            name: 'a marker label just before it',
            earlier: occurrence({
                timestamp: '2099-09-04T10:22:00Z',
                projected: { active: true, rolloutPercentage: 100, variantCount: null },
            }),
            earlierText: 'On',
            offAt: '2099-09-05T03:22:00Z',
        },
        {
            // Digits and "%" draw wider than the average character. At the average width the two boxes
            // clear the minimum space, but the app font draws the labels as "99.99%Off".
            name: 'a bare percentage step label',
            earlier: occurrence({
                operation: ScheduledChangeOperationType.AddReleaseCondition,
                addedRolloutPercentage: 99.99,
                projected: { active: true, rolloutPercentage: 99.99, variantCount: null },
            }),
            earlierText: '99.99%',
            offAt: '2099-08-28T05:22:00Z',
        },
    ])('lifts a marker label clear of $name in the same row', ({ earlier, earlierText, offAt }) => {
        render(
            <ScheduleTimeline
                occurrences={[
                    earlier,
                    occurrence({
                        timestamp: offAt,
                        projected: { active: false, rolloutPercentage: 100, variantCount: null },
                    }),
                    occurrence({
                        timestamp: '2099-09-24T10:22:00Z',
                        operation: ScheduledChangeOperationType.UpdateVariants,
                        projected: { active: false, rolloutPercentage: 100, variantCount: 3 },
                    }),
                ]}
                currentRolloutPercentage={100}
                timezone="UTC"
            />
        )

        const baseline = (text: string): number => Number(screen.getByText(text).getAttribute('y'))
        expect(baseline(earlierText) - baseline('Off')).toBeGreaterThanOrEqual(9)
    })

    it('anchors a step label at its mark near either edge, so the text stays in the plot', () => {
        const step = (timestamp: string, rollout: number): ScheduleOccurrence =>
            occurrence({
                timestamp,
                operation: ScheduledChangeOperationType.AddReleaseCondition,
                addedRolloutPercentage: rollout,
                projected: { active: true, rolloutPercentage: rollout, variantCount: null },
                needsApproval: true,
            })
        const { container } = render(
            <ScheduleTimeline
                occurrences={[
                    step('2099-08-25T11:22:00Z', 25),
                    step('2099-08-27T12:22:00Z', 50),
                    // 90 of the plan's 100 hours, so x is 530.8. That sits inside the end band at the
                    // current pad and outside it at the old 30, which is what pins the constant.
                    step('2099-08-29T04:22:00Z', 75),
                    step('2099-08-29T14:22:00Z', 100),
                ]}
                currentRolloutPercentage={10}
                timezone="UTC"
            />
        )

        const anchors = Array.from(container.querySelectorAll('text'))
            .filter((node) => node.textContent?.includes('needs approval'))
            .map((node) => node.getAttribute('text-anchor'))
        expect(anchors).toEqual(['start', 'middle', 'end', 'end'])
    })

    it('renders the step chart for two or more occurrences', () => {
        const { container } = render(
            <ScheduleTimeline
                occurrences={[
                    occurrence(),
                    occurrence({
                        timestamp: '2099-08-28T10:22:00Z',
                        operation: ScheduledChangeOperationType.AddReleaseCondition,
                        projected: { active: true, rolloutPercentage: 75, variantCount: null },
                    }),
                ]}
                currentRolloutPercentage={10}
                timezone="UTC"
            />
        )

        expect(container.querySelector('svg')).toBeInTheDocument()
        expect(screen.queryByText(/^Next:/)).not.toBeInTheDocument()
        expect(screen.getByText(/^The line shows/)).toBeInTheDocument()
    })

    it('dashes the jump of an approval-blocked step, and not the level before it', () => {
        const { container } = render(
            <ScheduleTimeline
                occurrences={[
                    occurrence({
                        operation: ScheduledChangeOperationType.AddReleaseCondition,
                        projected: { active: true, rolloutPercentage: 50, variantCount: null },
                    }),
                    occurrence({
                        timestamp: '2099-08-28T10:22:00Z',
                        operation: ScheduledChangeOperationType.AddReleaseCondition,
                        projected: { active: true, rolloutPercentage: 75, variantCount: null },
                        needsApproval: true,
                    }),
                ]}
                currentRolloutPercentage={25}
                timezone="UTC"
            />
        )

        const dashed = Array.from(container.querySelectorAll('path[stroke-dasharray]'))
        expect(dashed).toHaveLength(1)
        // A vertical jump only. A dashed horizontal run would claim the flag is not yet at the
        // level it already serves.
        expect(dashed[0].getAttribute('d')).toMatch(/^M [\d.]+ [\d.]+ V [\d.]+$/)
        expect(dashed[0].getAttribute('opacity')).toEqual('0.5')
        // Dash and opacity alone leave a touch user with no way to read the blocked state.
        expect(screen.getByText('75% (needs approval)')).toBeInTheDocument()
        // Nested in the marker's <g>, so RTL's ByTitle query does not reach it.
        expect(container.querySelector('g > title')?.textContent).toEqual('Needs approval')
    })

    it('labels a condition change whose projected rollout is unknown', () => {
        // A flag with no condition sets, and a payload that carries none either, leaves the
        // projection null. The step line cannot plot that, so the marker falls back to a label.
        render(
            <ScheduleTimeline
                occurrences={[
                    occurrence({ projected: { active: true, rolloutPercentage: null, variantCount: null } }),
                    occurrence({
                        timestamp: '2099-08-28T10:22:00Z',
                        operation: ScheduledChangeOperationType.AddReleaseCondition,
                        projected: { active: true, rolloutPercentage: null, variantCount: null },
                    }),
                ]}
                currentRolloutPercentage={null}
                timezone="UTC"
            />
        )

        expect(screen.getByText('Condition')).toBeInTheDocument()
        expect(screen.queryByText('0 variants')).not.toBeInTheDocument()
        expect(screen.getByText(/^No rollout line is shown/)).toBeInTheDocument()
        // The last occurrence always maps to the plot edge, where a centered label leaves the
        // viewBox. Anchoring is what keeps it readable, so pin it here.
        expect(screen.getByText('Condition')).toHaveAttribute('text-anchor', 'end')
    })

    it('says the line counts reach when the only plottable step is the last occurrence', () => {
        // The step has no level before it to run from, and the trailing run stops at the plot edge
        // this mark already sits on, so the chart draws a labelled mark and no segment.
        render(
            <ScheduleTimeline
                occurrences={[
                    occurrence({ projected: { active: true, rolloutPercentage: null, variantCount: null } }),
                    occurrence({
                        timestamp: '2099-08-28T10:22:00Z',
                        operation: ScheduledChangeOperationType.AddReleaseCondition,
                        addedRolloutPercentage: 25,
                        projected: { active: true, rolloutPercentage: 25, variantCount: null },
                    }),
                ]}
                currentRolloutPercentage={null}
                timezone="UTC"
            />
        )

        expect(screen.getByText('25%')).toBeInTheDocument()
        expect(screen.getByText(/^The line shows/)).toBeInTheDocument()
        expect(screen.queryByText(/^No rollout line is shown/)).not.toBeInTheDocument()
    })

    it('exposes the plan and a focus stop for a user without a mouse', () => {
        const { container } = render(
            <ScheduleTimeline
                occurrences={[
                    occurrence(),
                    occurrence({
                        timestamp: '2099-08-28T10:22:00Z',
                        operation: ScheduledChangeOperationType.AddReleaseCondition,
                        addedRolloutPercentage: 75,
                        projected: { active: true, rolloutPercentage: 75, variantCount: null },
                        needsApproval: true,
                    }),
                ]}
                currentRolloutPercentage={25}
                timezone="UTC"
            />
        )

        // The region scrolls below 600px, and a plain div with overflow takes no arrow keys.
        expect(container.querySelector('[data-attr="feature-flag-schedule-timeline"]')).toHaveAttribute('tabindex', '0')
        // role="img" hides every mark inside the chart, so this label is all a screen reader gets.
        expect(container.querySelector('svg')).toHaveAttribute(
            'aria-label',
            'Timeline of 2 upcoming scheduled changes: enabled on Aug 26, 10:22 AM, then add a condition at 75% rollout on Aug 28, 10:22 AM (needs approval)'
        )
    })
})