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.

8.6 KB
Raw Blame
import '~/styles'
import '~/toolbar/shared/styles.scss'

import { Meta, StoryObj } from '@storybook/react'
import { useActions, useMountedLogic } from 'kea'
import { useEffect } from 'react'

import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'

import { useStorybookMocks } from '~/mocks/browser'
import { ToolbarApp } from '~/toolbar/floating/components/ToolbarApp'
import { ToolbarParams } from '~/types'

import { MenuState, toolbarLogic } from '../../shared/bar/toolbarLogic'
import { toolbarConfigLogic } from '../../shared/toolbarConfigLogic'
import { toolbarPosthogJS } from '../../shared/toolbarPosthogJS'
import { TOOLBAR_ID } from '../../shared/utils'
import { listActionsAPIResponse } from './__mocks__/list-actions-response'
import { listHeatmapStatsAPIResponse } from './__mocks__/list-heatmap-stats-response'
import { listMyFlagsAPIResponse } from './__mocks__/list-my-flags-response'
import { listExperimentsAPIResponse } from './__mocks__/list-web-experiments-response'
import { listWebVitalsAPIResponse } from './__mocks__/list-web-vitals-response'

function useToolbarStyles(): void {
    useOnMountEffect(() => {
        const shadowRoot = window.document.getElementById(TOOLBAR_ID)?.shadowRoot
        if (!shadowRoot) {
            return
        }
        // Mirror the document's CSS into the toolbar's isolated shadow root *synchronously*,
        // by serializing the already-loaded stylesheet rules into a single <style>. The
        // toolbar measures its size/position (and which way to open menus) on render, so the
        // styles must be applied before that — cloning <link> tags would load async and the
        // toolbar would measure an unstyled bar, misplacing it and its panels. Inline <style>
        // (webpack, vite dev) and extracted <link> CSS (vite build) both surface here as
        // CSSStyleSheets. Same-origin sheets are readable; clone any that aren't as a fallback.
        const cssChunks: string[] = []
        for (const sheet of Array.from(document.styleSheets)) {
            try {
                cssChunks.push(
                    Array.from(sheet.cssRules)
                        .map((rule) => rule.cssText)
                        .join('\n')
                )
            } catch {
                if (sheet.ownerNode instanceof Element) {
                    shadowRoot.appendChild(sheet.ownerNode.cloneNode(true))
                }
            }
        }
        const style = document.createElement('style')
        style.appendChild(document.createTextNode(cssChunks.join('\n')))
        shadowRoot.appendChild(style)
    })
}

type StoryArgs = {
    menu?: MenuState
    minimized?: boolean
    unauthenticated?: boolean
    theme?: 'light' | 'dark'
    heatmapLocked?: boolean
    entitlementsState?: 'loading' | 'error'
}

const meta: Meta<StoryArgs> = {
    title: 'Scenes-Other/Toolbar',
    tags: ['test-skip-webkit'],
    parameters: {
        layout: 'fullscreen',
        viewMode: 'story',
    },
    render: (props, { parameters }) => {
        const toolbarParams: ToolbarParams = {
            accessToken: props.unauthenticated ? undefined : 'UExb1dCsoqBtrhrZYxzmxXQ7XdjVH5Ea_zbQjTFuJqk',
            actionId: undefined,
            userIntent: undefined,
            dataAttributes: ['data-attr'],
            apiURL: '/',
            userEmail: '[email protected]',
        }
        useToolbarStyles()

        useStorybookMocks({
            get: {
                '/decide': {
                    config: {
                        enable_collect_everything: true,
                    },
                    toolbarParams: {
                        toolbarVersion: 'toolbar',
                    },
                    isAuthenticated: props.unauthenticated ?? true,
                    supportedCompression: ['gzip', 'gzip-js', 'lz64'],
                    featureFlags: {
                        'web-vitals': true,
                        'web-vitals-toolbar': true,
                        'toolbar-paid-heatmaps': props.heatmapLocked ?? false,
                    },
                    sessionRecording: {
                        endpoint: '/s/',
                    },
                },
                '/api/element/stats/': listHeatmapStatsAPIResponse,
                '/api/heatmap/': { results: [] },
                '/api/user/toolbar_entitlements': () => {
                    if (props.entitlementsState === 'loading') {
                        return new Promise(() => {})
                    }
                    if (props.entitlementsState === 'error') {
                        return [500, {}]
                    }
                    return { entitlements: { toolbar_heatmaps: !props.heatmapLocked } }
                },
                '/api/projects/@current/feature_flags/my_flags': listMyFlagsAPIResponse,
                '/api/projects/@current/actions/': listActionsAPIResponse,
                '/api/projects/@current/web_experiments/': listExperimentsAPIResponse,
                '/api/environments/@current/web_vitals/': listWebVitalsAPIResponse,
                '/api/users/@me/hedgehog_config/': {},
            },
        })

        useMountedLogic(toolbarConfigLogic(toolbarParams))
        const theToolbarLogic = toolbarLogic()

        const { setVisibleMenu, setDragPosition, toggleMinimized, toggleTheme } = useActions(theToolbarLogic)

        useEffect(() => {
            // The toolbar uses its own SDK instance, so the app's Storybook flag overrides do not reach it.
            toolbarPosthogJS.featureFlags.overrideFeatureFlags({ flags: parameters.featureFlags ?? {} })
            setDragPosition(50, 50)
            setVisibleMenu(props.menu || 'none')
            toggleMinimized(props.minimized ?? false)
            toggleTheme(props.theme || 'light')
            return () => toolbarPosthogJS.featureFlags.overrideFeatureFlags(false)
        }, [Object.values(props)]) // oxlint-disable-line react-hooks/exhaustive-deps

        return (
            <div className="min-h-[32rem]">
                <div>The toolbar should show up now! Click it to open.</div>
                <button>Click Me</button>
                <ToolbarApp {...toolbarParams} disableExternalStyles />
            </div>
        )
    },
}
export default meta

type Story = StoryObj<StoryArgs>

export const Default: Story = {}

export const Unauthenticated: Story = {
    args: { unauthenticated: true },
}

export const Minimized: Story = {
    args: { minimized: true },
}

export const Heatmap: Story = {
    args: { menu: 'heatmap' },
}

export const HeatmapLocked: Story = {
    parameters: { featureFlags: { 'toolbar-paid-heatmaps': true } },
    args: { menu: 'heatmap', heatmapLocked: true },
}

export const HeatmapEntitlementsLoading: Story = {
    parameters: {
        featureFlags: { 'toolbar-paid-heatmaps': true },
        testOptions: {
            waitForLoadersToDisappear: false,
            waitForSelector: 'text=Checking plan access…',
        },
    },
    args: { menu: 'heatmap', heatmapLocked: true, entitlementsState: 'loading' },
}

export const HeatmapEntitlementsError: Story = {
    parameters: { featureFlags: { 'toolbar-paid-heatmaps': true } },
    args: { menu: 'heatmap', heatmapLocked: true, entitlementsState: 'error' },
}

export const Inspect: Story = {
    args: { menu: 'inspect' },
}

export const Actions: Story = {
    args: { menu: 'actions' },
}

export const FeatureFlags: Story = {
    args: { menu: 'flags' },
}

export const EventsDebuggerEmpty: Story = {
    args: { menu: 'debugger' },
}

export const Experiments: Story = {
    args: { menu: 'experiments' },
}

export const ExperimentsDisabledInParent: Story = {
    args: { menu: 'experiments' },
    decorators: [
        (Story) => {
            // fake that the host site posthog config disables web experiments
            window.parent.posthog = { config: { disable_web_experiments: true } }
            return <Story />
        },
    ],
}

export const WebVitals: Story = {
    args: { menu: 'web-vitals' },
}

// Dark theme
export const DefaultDark: Story = {
    args: { theme: 'dark' },
}

export const MinimizedDark: Story = {
    args: { theme: 'dark', minimized: true },
}

export const HeatmapDark: Story = {
    args: { theme: 'dark', menu: 'heatmap' },
}

export const InspectDark: Story = {
    args: { theme: 'dark', menu: 'inspect' },
}

export const ActionsDark: Story = {
    args: { theme: 'dark', menu: 'actions' },
}

export const FeatureFlagsDark: Story = {
    args: { theme: 'dark', menu: 'flags' },
}

export const EventsDebuggerEmptyDark: Story = {
    args: { theme: 'dark', menu: 'debugger' },
}

export const WebVitalsDark: Story = {
    args: { theme: 'dark', menu: 'web-vitals' },
}