Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { render } from '@solidjs/testing-library'
3import { createEffect } from 'solid-js'
4import { createLocalStorage } from '@solid-primitives/storage'
5import { PiPProvider, usePiPWindow } from '../../contexts'
6β
7type FakePipWindowOverrides = {
8 document?: Document
9 innerWidth?: number
10 innerHeight?: number
11}
12β
13function stubPipWindow(overrides: FakePipWindowOverrides = {}) {
14 const pipDocument =
15 overrides.document ?? document.implementation.createHTMLDocument('PiP')
16 const fakeWindow = {
17 document: pipDocument,
18 innerWidth: overrides.innerWidth ?? 800,
19 innerHeight: overrides.innerHeight ?? 600,
20 addEventListener: vi.fn(),
21 removeEventListener: vi.fn(),
22 close: vi.fn(),
23 }
24 const open = vi.fn(() => fakeWindow)
25 vi.stubGlobal('open', open)
26 return { pipDocument, fakeWindow, open }
27}
28β
29describe('PiPContext', () => {
30 afterEach(() => {
31 vi.unstubAllGlobals()
32 localStorage.clear()
33 })
34β
35 function renderAndAct(
36 action: (pip: ReturnType<typeof usePiPWindow>) => void,
37 options: {
38 disabled?: boolean
39 initialStorage?: Record<string, string>
40 } = {},
41 ) {
42 Object.entries(options.initialStorage ?? {}).forEach(([key, value]) => {
43 localStorage.setItem(key, value)
44 })
45 render(() => {
46 const [localStore, setLocalStore] = createLocalStorage({
47 prefix: 'TanstackQueryDevtools',
48 })
49 return (
50 <PiPProvider
51 localStore={localStore}
52 setLocalStore={setLocalStore}
53 disabled={options.disabled}
54 >
55 <PiPActor run={action} />
56 </PiPProvider>
57 )
58 })
59 }
60β
61 function PiPActor(props: {
62 run: (pip: ReturnType<typeof usePiPWindow>) => void
63 }) {
64 const pip = usePiPWindow()
65 let hasRun = false
66 createEffect(() => {
67 pip()
68 if (!hasRun) {
69 hasRun = true
70 props.run(pip)
71 }
72 })
73 return null
74 }
75β
76 describe('usePiPWindow', () => {
77 it('should throw when used outside a "PiPProvider"', () => {
78 function PiPProbe() {
79 usePiPWindow()
80 return null
81 }
82β
83 expect(() => render(() => <PiPProbe />)).toThrow(
84 'usePiPWindow must be used within a PiPProvider',
85 )
86 })
87 })
88β
89 describe('"requestPipWindow"', () => {
90 it('should call "window.open" with the expected target and features', () => {
91 const { open } = stubPipWindow()
92β
93 renderAndAct((pip) => pip().requestPipWindow(640, 480))
94β
95 expect(open).toHaveBeenCalledWith(
96 '',
97 'TSQD-Devtools-Panel',
98 'width=640,height=480,popup',
99 )
100 })
101β
102 it('should set the "pipWindow" signal to the opened window', () => {
103 const { fakeWindow } = stubPipWindow()
104 let observed: Window | null = null
105β
106 renderAndAct((pip) => {
107 pip().requestPipWindow(640, 480)
108 observed = pip().pipWindow
109 })
110β
111 expect(observed).toBe(fakeWindow)
112 })
113β
114 it('should persist "pip_open" as "true" to "localStore" after a successful open', () => {
115 stubPipWindow()
116β
117 renderAndAct((pip) => pip().requestPipWindow(640, 480))
118β
119 expect(localStorage.getItem('TanstackQueryDevtools.pip_open')).toBe(
120 'true',
121 )
122 })
123β
124 it('should set the PiP document title to "TanStack Query Devtools"', () => {
125 const { pipDocument } = stubPipWindow()
126β
127 renderAndAct((pip) => pip().requestPipWindow(640, 480))
128β
129 expect(pipDocument.title).toBe('TanStack Query Devtools')
130 })
131β
132 it('should reset the PiP document body margin to "0"', () => {
133 const { pipDocument } = stubPipWindow()
134β
135 renderAndAct((pip) => pip().requestPipWindow(640, 480))
136β
137 expect(pipDocument.body.style.margin).toMatch(/^0(px)?$/)
138 })
139β
140 it('should clear any existing nodes in the PiP document "head"', () => {
141 const { pipDocument } = stubPipWindow()
142 pipDocument.head.appendChild(pipDocument.createElement('meta'))
143β
144 renderAndAct((pip) => pip().requestPipWindow(640, 480))
145β
146 expect(pipDocument.head.querySelector('meta')).toBeNull()
147 })
148β
149 it('should clear any existing nodes in the PiP document "body"', () => {
150 const { pipDocument } = stubPipWindow()
151 const leftover = pipDocument.createElement('div')
152 leftover.id = 'leftover'
153 pipDocument.body.appendChild(leftover)
154β
155 renderAndAct((pip) => pip().requestPipWindow(640, 480))
156β
157 expect(pipDocument.body.querySelector('#leftover')).toBeNull()
158 })
159 })
160β
161 describe('styleSheet propagation', () => {
162 type FakeCssRule = { readonly cssText: string }
163 type FakeStyleSheet = {
164 readonly cssRules?: ArrayLike<FakeCssRule>
165 readonly href?: string | null
166 readonly type?: string
167 readonly media?: { toString: () => string }
168 readonly ownerNode?: Element | null
169 }
170β
171 function makeCssRules(...cssTexts: Array<string>): ArrayLike<FakeCssRule> {
172 return cssTexts.map((cssText) => ({ cssText }))
173 }
174β
175 function stubParentStyleSheet(sheet: FakeStyleSheet) {
176 return vi
177 .spyOn(document, 'styleSheets', 'get')
178 .mockReturnValue([sheet] as unknown as StyleSheetList)
179 }
180β
181 it('should copy parent stylesheets as "<style>" with the same id into the PiP document head', () => {
182 const sourceStyle = document.createElement('style')
183 sourceStyle.id = 'tsqd-source'
184 const sheetSpy = stubParentStyleSheet({
185 cssRules: makeCssRules('.tsqd { color: red; }'),
186 ownerNode: sourceStyle,
187 })
188 const { pipDocument } = stubPipWindow()
189β
190 try {
191 renderAndAct((pip) => pip().requestPipWindow(640, 480))
192β
193 const copied = pipDocument.head.querySelector('style#tsqd-source')
194 expect(copied).not.toBeNull()
195 expect(copied?.textContent).toBe('.tsqd { color: red; }')
196 } finally {
197 sheetSpy.mockRestore()
198 }
199 })
200β
201 it('should fall back to a "<link>" for cross-origin stylesheets whose "cssRules" throw', () => {
202 const sheetSpy = stubParentStyleSheet({
203 get cssRules(): CSSRuleList {
204 throw new DOMException('blocked', 'SecurityError')
205 },
206 href: 'https://example.com/external.css',
207 type: 'text/css',
208 media: { toString: () => 'all' },
209 })
210 const { pipDocument } = stubPipWindow()
211β
212 try {
213 renderAndAct((pip) => pip().requestPipWindow(640, 480))
214β
215 const link = pipDocument.head.querySelector<HTMLLinkElement>(
216 'link[href="https://example.com/external.css"]',
217 )
218 expect(link).not.toBeNull()
219 expect(link?.rel).toBe('stylesheet')
220 } finally {
221 sheetSpy.mockRestore()
222 }
223 })
224β
225 it('should skip the "<link>" fallback when the cross-origin stylesheet has no "href"', () => {
226 const sheetSpy = stubParentStyleSheet({
227 get cssRules(): CSSRuleList {
228 throw new DOMException('blocked', 'SecurityError')
229 },
230 href: null,
231 type: 'text/css',
232 media: { toString: () => 'all' },
233 })
234 const { pipDocument } = stubPipWindow()
235β
236 try {
237 renderAndAct((pip) => pip().requestPipWindow(640, 480))
238β
239 expect(pipDocument.head.querySelector('link')).toBeNull()
240 expect(pipDocument.head.querySelector('style')).toBeNull()
241 } finally {
242 sheetSpy.mockRestore()
243 }
244 })
245 })
246β
247 describe('"pagehide" lifecycle', () => {
248 it('should reset the "pipWindow" signal and "pip_open" when the "pagehide" event fires on the opened window', () => {
249 const { fakeWindow } = stubPipWindow()
250 const observed: Array<Window | null> = []
251β
252 renderAndAct(
253 (pip) => {
254 pip().requestPipWindow(640, 480)
255 observed.push(pip().pipWindow)
256 const pagehideHandler = fakeWindow.addEventListener.mock.calls.find(
257 ([event]) => event === 'pagehide',
258 )?.[1]
259 pagehideHandler?.()
260 observed.push(pip().pipWindow)
261 },
262 { disabled: true },
263 )
264β
265 expect(observed).toEqual([fakeWindow, null])
266 expect(localStorage.getItem('TanstackQueryDevtools.pip_open')).toBe(
267 'false',
268 )
269 })
270 })
271β
272 describe('"closePipWindow"', () => {
273 it('should be a noop when no window is open', () => {
274 const { fakeWindow } = stubPipWindow()
275β
276 renderAndAct((pip) => {
277 pip().closePipWindow()
278 })
279β
280 expect(fakeWindow.close).not.toHaveBeenCalled()
281 })
282β
283 it('should call "close" on the opened window and reset the "pipWindow" signal', () => {
284 const { fakeWindow } = stubPipWindow()
285 const observed: Array<Window | null> = []
286β
287 renderAndAct(
288 (pip) => {
289 pip().requestPipWindow(640, 480)
290 observed.push(pip().pipWindow)
291 pip().closePipWindow()
292 observed.push(pip().pipWindow)
293 },
294 { disabled: true },
295 )
296β
297 expect(fakeWindow.close).toHaveBeenCalledTimes(1)
298 expect(observed).toEqual([fakeWindow, null])
299 })
300β
301 it('should call "close" only once when "closePipWindow" runs twice in a row', () => {
302 const { fakeWindow } = stubPipWindow()
303β
304 renderAndAct(
305 (pip) => {
306 pip().requestPipWindow(640, 480)
307 pip().closePipWindow()
308 pip().closePipWindow()
309 },
310 { disabled: true },
311 )
312β
313 expect(fakeWindow.close).toHaveBeenCalledTimes(1)
314 })
315β
316 it('should reset "pip_open" in "localStore" so the auto-open createEffect does not reopen the window', () => {
317 stubPipWindow()
318β
319 renderAndAct(
320 (pip) => {
321 pip().requestPipWindow(640, 480)
322 pip().closePipWindow()
323 },
324 { disabled: true },
325 )
326β
327 expect(localStorage.getItem('TanstackQueryDevtools.pip_open')).toBe(
328 'false',
329 )
330 })
331 })
332β
333 describe('"pip_open" auto-open createEffect', () => {
334 it('should auto-open a PiP window when "pip_open" is "true" on mount', () => {
335 const { open } = stubPipWindow()
336β
337 renderAndAct(() => {}, {
338 initialStorage: { 'TanstackQueryDevtools.pip_open': 'true' },
339 })
340β
341 expect(open).toHaveBeenCalled()
342 })
343β
344 it('should not auto-open a PiP window when "disabled" is true', () => {
345 const { open } = stubPipWindow()
346β
347 renderAndAct(() => {}, {
348 disabled: true,
349 initialStorage: { 'TanstackQueryDevtools.pip_open': 'true' },
350 })
351β
352 expect(open).not.toHaveBeenCalled()
353 })
354β
355 it('should reset "pip_open"/"open" and log when "window.open" returns null on auto-open', () => {
356 vi.stubGlobal(
357 'open',
358 vi.fn(() => null),
359 )
360 const consoleErrorMock = vi
361 .spyOn(console, 'error')
362 .mockImplementation(() => {})
363β
364 try {
365 renderAndAct(() => {}, {
366 initialStorage: { 'TanstackQueryDevtools.pip_open': 'true' },
367 })
368β
369 expect(consoleErrorMock).toHaveBeenCalledWith(
370 'Failed to open popup. Please allow popups for this site to view the devtools in picture-in-picture mode.',
371 )
372 expect(localStorage.getItem('TanstackQueryDevtools.pip_open')).toBe(
373 'false',
374 )
375 expect(localStorage.getItem('TanstackQueryDevtools.open')).toBe('false')
376 } finally {
377 consoleErrorMock.mockRestore()
378 }
379 })
380β
381 it('should re-throw non-"PipOpenError" errors from "window.open" on auto-open', () => {
382 vi.stubGlobal(
383 'open',
384 vi.fn(() => {
385 throw new Error('unexpected')
386 }),
387 )
388β
389 expect(() =>
390 renderAndAct(() => {}, {
391 initialStorage: { 'TanstackQueryDevtools.pip_open': 'true' },
392 }),
393 ).toThrow('unexpected')
394 })
395 })
396β
397 describe('"#_goober" MutationObserver', () => {
398 function stubMutationObserver() {
399 let observerCallback: MutationCallback | undefined
400 const observeSpy = vi.fn()
401 const disconnectSpy = vi.fn()
402 class FakeMutationObserver {
403 observe = observeSpy
404 disconnect = disconnectSpy
405 takeRecords = () => []
406 constructor(cb: MutationCallback) {
407 observerCallback = cb
408 }
409 }
410 vi.stubGlobal('MutationObserver', FakeMutationObserver)
411 return {
412 observeSpy,
413 disconnectSpy,
414 fire: () => observerCallback?.([], {} as MutationObserver),
415 }
416 }
417β
418 it('should observe the parent "#_goober" style for childList and subtree mutations', () => {
419 const gooberStyle = document.createElement('style')
420 gooberStyle.id = '_goober'
421 gooberStyle.textContent = '.initial { color: red; }'
422 document.head.appendChild(gooberStyle)
423 const { observeSpy } = stubMutationObserver()
424 stubPipWindow()
425β
426 try {
427 renderAndAct((pip) => pip().requestPipWindow(640, 480), {
428 disabled: true,
429 })
430β
431 expect(observeSpy).toHaveBeenCalledWith(gooberStyle, {
432 childList: true,
433 subtree: true,
434 characterDataOldValue: true,
435 })
436 } finally {
437 gooberStyle.remove()
438 }
439 })
440β
441 it('should copy parent "#_goober" "textContent" into the PiP mirror when the observer fires', () => {
442 const gooberStyle = document.createElement('style')
443 gooberStyle.id = '_goober'
444 gooberStyle.textContent = '.initial { color: red; }'
445 document.head.appendChild(gooberStyle)
446 const { fire } = stubMutationObserver()
447 const { pipDocument } = stubPipWindow()
448β
449 try {
450 const pipGooberStyle = pipDocument.createElement('style')
451 pipGooberStyle.id = '_goober'
452β
453 renderAndAct(
454 (pip) => {
455 pip().requestPipWindow(640, 480)
456 // `requestPipWindow` clears the PiP document head, so install
457 // the goober mirror style after that point.
458 pipDocument.head.appendChild(pipGooberStyle)
459 },
460 { disabled: true },
461 )
462β
463 gooberStyle.textContent = '.next { color: blue; }'
464 fire()
465 expect(pipGooberStyle.textContent).toBe('.next { color: blue; }')
466 } finally {
467 gooberStyle.remove()
468 }
469 })
470 })
471})