Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions .changeset/visible-panel-updates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@github-ui/storybook-addon-performance-panel': minor
---

Pause browser collectors, DOM observation, metric transport, and sparkline sampling while the performance panel is hidden.
6 changes: 6 additions & 0 deletions packages/storybook-addon-performance-panel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,12 @@ import '@github-ui/storybook-addon-performance-panel/preset'

The universal entry collects all browser-level metrics (frame timing, CLS, INP, etc.) but omits React Profiler metrics. The React Performance section is automatically hidden in the panel.

## Collection Lifecycle

Browser performance collection runs automatically while the Performance panel is selected. Closing the panel disconnects browser collectors, DOM observers, and live-update timers to minimize background overhead. Reopening the panel resumes collection without clearing the metrics already gathered for the current story. React Profiler callbacks remain attached so mount and render history is not lost before the panel opens.

Use the reset button to clear accumulated metrics, or set `parameters.performancePanel.disable` to `true` to disable the addon for a story.

## Collectors

The addon uses modular collector classes for metrics gathering. Each collector uses the most accurate available API for its metrics.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,19 +86,48 @@ describe('withPerformanceMonitor (universal / web-component usage)', () => {

expect(mockChannel.on).toHaveBeenCalledWith(PERF_EVENTS.REQUEST_METRICS, expect.any(Function))
expect(mockChannel.on).toHaveBeenCalledWith(PERF_EVENTS.RESET, expect.any(Function))
expect(mockChannel.on).toHaveBeenCalledWith(PERF_EVENTS.PANEL_VISIBILITY, expect.any(Function))
expect(mockChannel.on).toHaveBeenCalledWith(PERF_EVENTS.INSPECT_ELEMENT, expect.any(Function))
expect(mockChannel.emit).toHaveBeenCalledWith(PERF_EVENTS.REQUEST_PANEL_VISIBILITY)
})

it('emits metrics periodically', async () => {
it('does not emit metrics periodically while the panel is hidden', async () => {
withPerformanceMonitor(
vi.fn(() => ''),
makeCtx(),
)
mockChannel.emit.mockClear()

// The core emits every 50ms; wait enough for at least one tick
await new Promise(resolve => setTimeout(resolve, 150))
await new Promise(resolve => setTimeout(resolve, 300))

expect(mockChannel.emit).not.toHaveBeenCalledWith(PERF_EVENTS.METRICS_UPDATE, expect.any(Object))
expect(getActiveCore()?.manager.isRunning).toBe(false)
})

it('emits live metrics only while the panel is visible', async () => {
withPerformanceMonitor(
vi.fn(() => ''),
makeCtx(),
)

const visibilityCall = mockChannel.on.mock.calls.find((call: unknown[]) => call[0] === PERF_EVENTS.PANEL_VISIBILITY)
expect(visibilityCall).toBeDefined()
const handleVisibility = visibilityCall?.[1] as (visible: boolean) => void

mockChannel.emit.mockClear()
handleVisibility(true)
expect(getActiveCore()?.manager.isRunning).toBe(true)
expect(mockChannel.emit).toHaveBeenCalledWith(PERF_EVENTS.METRICS_UPDATE, expect.any(Object))

mockChannel.emit.mockClear()
await new Promise(resolve => setTimeout(resolve, 300))
expect(mockChannel.emit).toHaveBeenCalledWith(PERF_EVENTS.METRICS_UPDATE, expect.any(Object))

handleVisibility(false)
expect(getActiveCore()?.manager.isRunning).toBe(false)
mockChannel.emit.mockClear()
await new Promise(resolve => setTimeout(resolve, 300))
expect(mockChannel.emit).not.toHaveBeenCalledWith(PERF_EVENTS.METRICS_UPDATE, expect.any(Object))
})

it('reuses the same core for repeated renders of the same story', () => {
Expand Down Expand Up @@ -137,6 +166,32 @@ describe('withPerformanceMonitor (universal / web-component usage)', () => {
expect(second?.storyId).toBe('story-b')
})

it('requests visibility again so an open panel resumes after a story change', () => {
withPerformanceMonitor(
vi.fn(() => ''),
makeCtx({id: 'story-a'}),
)
const firstVisibilityCall = mockChannel.on.mock.calls.find(
(call: unknown[]) => call[0] === PERF_EVENTS.PANEL_VISIBILITY,
)
const handleFirstVisibility = firstVisibilityCall?.[1] as (visible: boolean) => void
handleFirstVisibility(true)

mockChannel.emit.mockClear()
withPerformanceMonitor(
vi.fn(() => ''),
makeCtx({id: 'story-b'}),
)

expect(mockChannel.emit).toHaveBeenCalledWith(PERF_EVENTS.REQUEST_PANEL_VISIBILITY)
const visibilityCalls = mockChannel.on.mock.calls.filter(
(call: unknown[]) => call[0] === PERF_EVENTS.PANEL_VISIBILITY,
)
const handleCurrentVisibility = visibilityCalls.at(-1)?.[1] as (visible: boolean) => void
handleCurrentVisibility(true)
expect(mockChannel.emit).toHaveBeenCalledWith(PERF_EVENTS.METRICS_UPDATE, expect.any(Object))
})

it('clears active core when disabled via parameters', () => {
// First enable it
withPerformanceMonitor(
Expand Down Expand Up @@ -191,13 +246,15 @@ describe('withPerformanceMonitor (universal / web-component usage)', () => {
)
})

it('emitted metrics include expected browser-level fields (no React fields populated)', async () => {
it('requested metrics include expected browser-level fields (no React fields populated)', () => {
withPerformanceMonitor(
vi.fn(() => ''),
makeCtx(),
)

await new Promise(resolve => setTimeout(resolve, 150))
const requestCall = mockChannel.on.mock.calls.find((call: unknown[]) => call[0] === PERF_EVENTS.REQUEST_METRICS)
const handleRequest = requestCall?.[1] as () => void
handleRequest()

const metricsCall = mockChannel.emit.mock.calls.find((call: unknown[]) => call[0] === PERF_EVENTS.METRICS_UPDATE)
expect(metricsCall).toBeDefined()
Expand Down Expand Up @@ -239,6 +296,7 @@ describe('withPerformanceMonitor (universal / web-component usage)', () => {

expect(mockChannel.off).toHaveBeenCalledWith(PERF_EVENTS.REQUEST_METRICS, expect.any(Function))
expect(mockChannel.off).toHaveBeenCalledWith(PERF_EVENTS.RESET, expect.any(Function))
expect(mockChannel.off).toHaveBeenCalledWith(PERF_EVENTS.PANEL_VISIBILITY, expect.any(Function))
expect(mockChannel.off).toHaveBeenCalledWith(PERF_EVENTS.INSPECT_ELEMENT, expect.any(Function))
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,33 @@ describe('performance-decorator', () => {
resetSpy.mockRestore()
})

it('emits metrics periodically', async () => {
it('does not emit metrics periodically while the panel is hidden', async () => {
await render(
<PerformanceProvider storyId="test-story">
<div>Test</div>
</PerformanceProvider>,
)
mockChannel.emit.mockClear()

// Wait for real time to pass for metrics emission (50ms interval)
await new Promise(resolve => setTimeout(resolve, 150))
await new Promise(resolve => setTimeout(resolve, 300))

expect(mockChannel.emit).not.toHaveBeenCalledWith(PERF_EVENTS.METRICS_UPDATE, expect.any(Object))
})

it('emits metrics periodically while the panel is visible', async () => {
await render(
<PerformanceProvider storyId="test-story">
<div>Test</div>
</PerformanceProvider>,
)
const visibilityCall = mockChannel.on.mock.calls
.filter((call: unknown[]) => call[0] === PERF_EVENTS.PANEL_VISIBILITY)
.at(-1)
const handleVisibility = visibilityCall?.[1] as (visible: boolean) => void

handleVisibility(true)
mockChannel.emit.mockClear()
await new Promise(resolve => setTimeout(resolve, 300))

expect(mockChannel.emit).toHaveBeenCalledWith(PERF_EVENTS.METRICS_UPDATE, expect.any(Object))
})
Expand Down Expand Up @@ -170,7 +188,9 @@ describe('performance-decorator', () => {
</PerformanceProvider>,
)

await new Promise(resolve => setTimeout(resolve, 150))
const requestCall = mockChannel.on.mock.calls.find((call: unknown[]) => call[0] === PERF_EVENTS.REQUEST_METRICS)
const requestMetrics = requestCall?.[1] as () => void
requestMetrics()

const emittedCall = mockChannel.emit.mock.calls.find((call: unknown[]) => call[0] === PERF_EVENTS.METRICS_UPDATE)

Expand Down Expand Up @@ -329,15 +349,17 @@ describe('performance-decorator', () => {
expect(mockChannel.on).toHaveBeenCalled() // Provider is active
})

it('emits metrics for wrapped story', async () => {
it('responds to metric requests for a wrapped story', async () => {
const Story = () => <div>Story</div>
const context = {id: 'test-story', parameters: {}} as Parameters<typeof withPerformanceMonitor>[1]

const WrappedStory = () => withPerformanceMonitor(Story, context)

await render(<WrappedStory />)

await new Promise(resolve => setTimeout(resolve, 150))
const requestCall = mockChannel.on.mock.calls.find((call: unknown[]) => call[0] === PERF_EVENTS.REQUEST_METRICS)
const requestMetrics = requestCall?.[1] as () => void
requestMetrics()

expect(mockChannel.emit).toHaveBeenCalledWith(PERF_EVENTS.METRICS_UPDATE, expect.any(Object))
})
Expand All @@ -355,8 +377,15 @@ describe('performance-decorator', () => {
</PerformanceProvider>,
)

// Wait for initial count and metrics emission
await new Promise(resolve => setTimeout(resolve, 600))
const visibilityCall = mockChannel.on.mock.calls
.filter((call: unknown[]) => call[0] === PERF_EVENTS.PANEL_VISIBILITY)
.at(-1)
const handleVisibility = visibilityCall?.[1] as (visible: boolean) => void
handleVisibility(true)

const requestCall = mockChannel.on.mock.calls.find((call: unknown[]) => call[0] === PERF_EVENTS.REQUEST_METRICS)
const requestMetrics = requestCall?.[1] as () => void
requestMetrics()

const emittedCall2 = mockChannel.emit.mock.calls.find((call: unknown[]) => call[0] === PERF_EVENTS.METRICS_UPDATE)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import {convert, ThemeProvider, themes} from 'storybook/theming'
import {beforeEach, describe, expect, it, vi} from 'vitest'
import {render} from 'vitest-browser-react'

import {PERF_EVENTS} from '../core/performance-types'
import {PerformancePanel} from '../performance-panel'

type ChannelEventMap = Record<string, (...args: unknown[]) => void>

const channel = vi.hoisted(() => ({
emit: vi.fn(),
registrations: [] as {events: ChannelEventMap; deps?: unknown[]}[],
}))

vi.mock('storybook/manager-api', () => ({
useChannel: (events: ChannelEventMap, deps?: unknown[]) => {
channel.registrations.push({events, deps})
return channel.emit
},
useStorybookState: () => ({
previewInitialized: true,
refId: undefined,
storyId: undefined,
viewMode: 'story',
}),
}))

function renderPanel(active: boolean) {
return (
<ThemeProvider theme={convert(themes.light)}>
<PerformancePanel active={active} />
</ThemeProvider>
)
}

describe('PerformancePanel visibility', () => {
beforeEach(() => {
channel.emit.mockClear()
channel.registrations.length = 0
})

it('reports the latest visibility after AddonPanel freezes its inactive children', async () => {
const {rerender} = await render(renderPanel(true))

await expect
.poll(() =>
channel.emit.mock.calls.some(
([eventName, visible]) => eventName === PERF_EVENTS.PANEL_VISIBILITY && visible === true,
),
)
.toBe(true)

await rerender(renderPanel(false))

await expect
.poll(() =>
channel.emit.mock.calls.some(
([eventName, visible]) => eventName === PERF_EVENTS.PANEL_VISIBILITY && visible === false,
),
)
.toBe(true)

const currentRegistration = channel.registrations
.filter(({events}) => PERF_EVENTS.REQUEST_PANEL_VISIBILITY in events)
.at(-1)

expect(currentRegistration?.deps).toEqual([false])
channel.emit.mockClear()
currentRegistration?.events[PERF_EVENTS.REQUEST_PANEL_VISIBILITY]?.()

expect(channel.emit).toHaveBeenCalledWith(PERF_EVENTS.PANEL_VISIBILITY, false)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ export const PERF_EVENTS = {
RESET: `${ADDON_ID}/reset`,
/** Panel → Decorator: Request immediate metrics update */
REQUEST_METRICS: `${ADDON_ID}/request-metrics`,
/** Panel → Decorator: Start or stop browser collection based on panel visibility */
PANEL_VISIBILITY: `${ADDON_ID}/panel-visibility`,
/** Decorator → Panel: Request the current panel visibility state */
REQUEST_PANEL_VISIBILITY: `${ADDON_ID}/request-panel-visibility`,
/** Panel → Decorator: Highlight/inspect an element by selector */
INSPECT_ELEMENT: `${ADDON_ID}/inspect-element`,
/** Panel → Decorator: Select a specific profiler for display */
Expand Down
Loading