Skip to content
Open
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
9 changes: 9 additions & 0 deletions .changeset/pip-delegated-events.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@tanstack/devtools': patch
---

Delegate the full Solid `DelegatedEvents` set on the picture-in-picture popup
document so delegated handlers rendered into the detached window fire. The
hand-picked nine-event list omitted `dblclick`, so the splitter's double-click
reset (and any other delegated handler outside that list) silently did nothing
in PiP mode.
143 changes: 143 additions & 0 deletions e2e/apps/react-vite/tests/pip-delegated-events.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { expect, test } from '@playwright/test'
import { DevtoolsPage, SELECTORS } from '@tanstack/devtools-e2e'

const DEMO = 'demo'
const PROBE = 'event-probe'

/**
* Devtools PiP mode detaches the whole Solid tree into a popup window opened by
* `window.open('', 'TSDT-Devtools-Panel', ...)`. Solid delegates events through
* a single document-level listener installed by `delegateEvents()` on the
* document the event targets; the main document gets the full set by default,
* but the popup document only gets what `pip-context.tsx` registers.
*
* These tests drive a *real* popup window (not a stubbed `window.open`) so they
* exercise delegated-event dispatch on the popup's own document — the exact
* path that left `onDblClick` dead before the fix.
*/

const unequalRowSplit = (page: import('@playwright/test').Page) =>
page.evaluate(() => {
localStorage.setItem(
'tanstack_devtools_state',
JSON.stringify({
layout: {
kind: 'split',
dir: 'row',
sizes: [0.7, 0.3],
children: [
{ kind: 'group', id: 'g0', tabs: ['demo'], active: 0 },
{ kind: 'group', id: 'g1', tabs: ['event-probe'], active: 0 },
],
},
}),
)
})

// `addInitScript` runs on every navigation, so only seed a clean slate once.
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
if (sessionStorage.getItem('tsd-e2e-started') === null) {
localStorage.clear()
sessionStorage.setItem('tsd-e2e-started', '1')
}
})
})

const enterPip = (page: import('@playwright/test').Page) =>
Promise.all([
page.waitForEvent('popup', { timeout: 15_000 }),
page.getByTestId(SELECTORS.pipButton).click(),
]).then(([popup]) => popup)

test('double-click resets a splitter inside the detached PiP window', async ({
page,
}) => {
// Seed an unequal split so a reset has a visible "from" state.
await page.goto('/')
await unequalRowSplit(page)
await page.reload()

const dt = new DevtoolsPage(page)
await dt.openViaTrigger()
await expect(dt.splitters()).toHaveCount(1)
await expect(dt.pane(DEMO)).toBeVisible()

// Confirm the seeded unequal geometry before detaching.
const mainDemo = (await dt.pane(DEMO).boundingBox())!.width
const mainProbe = (await dt.pane(PROBE).boundingBox())!.width
expect(mainDemo - mainProbe).toBeGreaterThan(80)

const popup = await enterPip(page)
const pdt = new DevtoolsPage(popup)
await expect
.poll(async () => await pdt.splitters().count(), {
timeout: 15_000,
})
.toBe(1)

// The unequal sizes travel with the portaled tree.
const popupDemoBefore = (await pdt.pane(DEMO).boundingBox())!.width
const popupProbeBefore = (await pdt.pane(PROBE).boundingBox())!.width
expect(popupDemoBefore - popupProbeBefore).toBeGreaterThan(80)

// Double-click the splitter *inside the popup*. Before the fix, `dblclick`
// was not delegated on the popup document, so this was a silent no-op.
// A locator-based dblclick auto-scrolls the gutter into the popup's viewport;
// raw mouse coordinates can fall outside the (smaller) popup viewport.
await pdt.splitters().first().dblclick()

// The panes reset to (roughly) equal shares.
await expect
.poll(async () => {
const d = (await pdt.pane(DEMO).boundingBox())!.width
const p = (await pdt.pane(PROBE).boundingBox())!.width
return Math.abs(d - p)
})
.toBeLessThan(6)

// And the persisted layout now records equal sizes.
const layout = (await pdt.storedLayout()) as { sizes?: number[] }
expect(layout.sizes).toBeDefined()
for (const size of layout.sizes!) {
expect(size).toBeCloseTo(1 / layout.sizes!.length, 1)
}
})

test('the detached window delegates the previously-missing events', async ({
page,
}) => {
const dt = new DevtoolsPage(page)
await dt.goto()
await dt.openViaTrigger()
await dt.stripEntry('Event Probe').click()
await expect(dt.splitters()).toHaveCount(1)

const popup = await enterPip(page)
await expect
.poll(async () => await popup.getByTestId(SELECTORS.splitter).count(), {
timeout: 15_000,
})
.toBe(1)

const delegated = await popup.evaluate(() => {
const set = (document as unknown as Record<string, unknown>)[
'_$DX_DELEGATE'
] as Set<string> | undefined
return set ? [...set] : []
})
// The events that were missing from the pre-fix nine-event list must now be
// delegated on the popup document (the report called out `dblclick`; the
// others are the same latent trap).
for (const name of [
'dblclick',
'beforeinput',
'contextmenu',
'keyup',
'mousemove',
'mouseup',
'touchstart',
]) {
expect(delegated).toContain(name)
}
})
115 changes: 115 additions & 0 deletions packages/devtools/src/context/pip-context.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { render } from '@solidjs/testing-library'
import { createEffect } from 'solid-js'
import {
DelegatedEvents,
addEventListener as attachDelegatedHandler,
} from 'solid-js/web'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { PiPProvider, createPiPWindow } from './pip-context'

/**
* The marker Solid stores on a document once it has installed the per-event,
* document-level listener for delegation. Reading it (rather than dispatching)
* is the direct way to ask "is this event delegated on this document?".
*/
const DELEGATE_KEY = '_$DX_DELEGATE'

const delegatedOn = (doc: Document): Set<string> => {
const set = (doc as unknown as Record<string, Set<string> | undefined>)[
DELEGATE_KEY
]
return set ?? new Set<string>()
}

/**
* jsdom blocks `window.open`, so a browser popup window has to be faked. The
* real contract `requestPipWindow` depends on: an EventTarget with its own
* `document` and a `close()` method. `document.implementation.createHTMLDocument`
* yields a fully-formed detached Document (with `<head>`/`<body>`) that
* supports `delegateEvents`, `createElement`, `getElementById`, etc.
*/
const createFakePipWindow = () => {
const pipDocument =
document.implementation.createHTMLDocument('TanStack Devtools')
const win = new EventTarget() as unknown as Window &
typeof globalThis & { document: Document }
Object.assign(win, { document: pipDocument, close: vi.fn() })
return { win, pipDocument }
}

const Harness = (props: {
onContext: (pip: ReturnType<typeof createPiPWindow>) => void
}) => {
// `createPiPWindow` must run during component setup (it calls `useContext`),
// so the consumer is rendered inside the provider and hands the accessor out.
const pip = createPiPWindow()
createEffect(() => props.onContext(pip))
return null
}

/**
* Mount the provider and open a (faked) popup. Returns the captured context
* accessor plus the popup document, wired so effects have flushed.
*/
const openPip = () => {
const { win, pipDocument } = createFakePipWindow()
const openSpy = vi.spyOn(window, 'open').mockReturnValue(win)
let pip: ReturnType<typeof createPiPWindow> | undefined
const result = render(() => (
<PiPProvider>
<Harness onContext={(c) => (pip = c)} />
</PiPProvider>
))
// `requestPipWindow` is a no-op if a window is already open, but tests open
// exactly one, so this always proceeds and installs delegation on the popup.
pip!().requestPipWindow('width=400,height=400')
return {
pipDocument,
pipWindow: win,
context: () => pip!(),
dispose: () => {
result.unmount()
openSpy.mockRestore()
},
}
}

describe('PiP document event delegation', () => {
let dispose: (() => void) | undefined

afterEach(() => {
dispose?.()
dispose = undefined
vi.restoreAllMocks()
})

it('registers the full Solid DelegatedEvents set on the popup document', () => {
const fixture = openPip()
dispose = fixture.dispose

const delegated = delegatedOn(fixture.pipDocument)
expect(delegated).toBeInstanceOf(Set)
// Every event Solid considers delegated must be delegated on the popup
// document, mirroring what the runtime does on the main document by default.
// Guards against regressing to a hand-picked, mode-specific list that leaves
// delegated handlers (e.g. the splitter's `onDblClick`) dead in PiP mode.
for (const name of DelegatedEvents) {
expect(delegated.has(name)).toBe(true)
}
})

it('fires a delegated dblclick handler rendered into the popup document', () => {
const fixture = openPip()
dispose = fixture.dispose

const el = fixture.pipDocument.createElement('button')
fixture.pipDocument.body.appendChild(el)
const handler = vi.fn()
// Attach the way the Solid compiler does for a delegated event: store the
// handler on the node and rely on the document-level listener to fire it.
attachDelegatedHandler(el, 'dblclick', handler, true)

el.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }))
expect(handler).toHaveBeenCalledTimes(1)
})
})
24 changes: 9 additions & 15 deletions packages/devtools/src/context/pip-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
useContext as getContext,
onCleanup,
} from 'solid-js'
import { delegateEvents } from 'solid-js/web'
import { DelegatedEvents, delegateEvents } from 'solid-js/web'
import { ensureDevtoolsStyles } from '@tanstack/devtools-ui/internal'
import type { Accessor, JSX } from 'solid-js'

Expand Down Expand Up @@ -114,20 +114,14 @@ export const PiPProvider = (props: PiPProviderProps) => {
}
})
ensureDevtoolsStyles(pip.document)
delegateEvents(
[
'focusin',
'focusout',
'pointermove',
'keydown',
'pointerdown',
'pointerup',
'click',
'mousedown',
'input',
],
pip.document,
)
// Delegate the full Solid `DelegatedEvents` set on the popup document, so
// every delegated event handler rendered into the PiP window (e.g. the
// splitter's `onDblClick` reset) fires. Solid stores delegated handlers on
// the node (`node.$$<event>`) and dispatches them through a single
// document-level listener installed by `delegateEvents()` on the document
// the event targets — the main document gets the full set by default, but
// the popup document only gets what we register here.
delegateEvents([...DelegatedEvents], pip.document)

setPipWindow(pip)
}
Expand Down