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