Open History to see the last commit
1import {
2 createContext,
3 createEffect,
4 createMemo,
5 createSignal,
6 useContext,
7} from 'solid-js'
8import { clearDelegatedEvents, delegateEvents } from 'solid-js/web'
9import { PIP_DEFAULT_HEIGHT } from '../constants'
10import { useQueryDevtoolsContext } from './QueryDevtoolsContext'
11import type { StorageObject, StorageSetter } from '@solid-primitives/storage'
12import type { Accessor, JSX } from 'solid-js'
13β
14interface PiPProviderProps {
15 children: JSX.Element
16 localStore: StorageObject<string>
17 setLocalStore: StorageSetter<string, unknown>
18 disabled?: boolean
19}
20β
21type PiPContextType = {
22 pipWindow: Window | null
23 requestPipWindow: (width: number, height: number) => void
24 closePipWindow: () => void
25 disabled: boolean
26}
27β
28class PipOpenError extends Error {}
29β
30const PiPContext = createContext<Accessor<PiPContextType> | undefined>(
31 undefined,
32)
33β
34/**
35 * Provides the picture-in-picture window of the devtools, and functions to
36 * open and close it.
37 * @param props - The `children` to render, the `localStore` and
38 * `setLocalStore` that persist whether the window is open, and `disabled` to
39 * turn picture-in-picture off.
40 * @returns The context provider.
41 */
42export const PiPProvider = (props: PiPProviderProps) => {
43 // Expose pipWindow that is currently active
44 const [pipWindow, setPipWindow] = createSignal<Window | null>(null)
45β
46 // Close pipWindow programmatically
47 const closePipWindow = () => {
48 const w = pipWindow()
49 if (w != null) {
50 w.close()
51 props.setLocalStore('pip_open', 'false')
52 setPipWindow(null)
53 }
54 }
55β
56 // Open new pipWindow
57 const requestPipWindow = (width: number, height: number) => {
58 // We don't want to allow multiple requests.
59 if (pipWindow() != null) {
60 return
61 }
62β
63 const pip = window.open(
64 '',
65 'TSQD-Devtools-Panel',
66 `width=${width},height=${height},popup`,
67 )
68β
69 if (!pip) {
70 throw new PipOpenError(
71 'Failed to open popup. Please allow popups for this site to view the devtools in picture-in-picture mode.',
72 )
73 }
74β
75 // Remove existing styles and body. `replaceChildren` instead of
76 // `innerHTML = ''`, which Trusted Types block.
77 pip.document.head.replaceChildren()
78 pip.document.body.replaceChildren()
79 // Clear Delegated Events
80 clearDelegatedEvents(pip.document)
81β
82 pip.document.title = 'TanStack Query Devtools'
83 pip.document.body.style.margin = '0'
84β
85 // Detect when window is closed by user
86 pip.addEventListener('pagehide', () => {
87 props.setLocalStore('pip_open', 'false')
88 setPipWindow(null)
89 })
90β
91 // It is important to copy all parent window styles. Otherwise, there would be no CSS available at all
92 // https://developer.chrome.com/docs/web-platform/document-picture-in-picture/#copy-style-sheets-to-the-picture-in-picture-window
93 ;[
94 ...(useQueryDevtoolsContext().shadowDOMTarget || document).styleSheets,
95 ].forEach((styleSheet) => {
96 try {
97 const cssRules = [...styleSheet.cssRules]
98 .map((rule) => rule.cssText)
99 .join('')
100 const style = document.createElement('style')
101 const style_node = styleSheet.ownerNode
102 let style_id = ''
103β
104 if (style_node && 'id' in style_node) {
105 style_id = style_node.id
106 }
107β
108 if (style_id) {
109 style.setAttribute('id', style_id)
110 }
111 style.textContent = cssRules
112 pip.document.head.appendChild(style)
113 } catch (e) {
114 const link = document.createElement('link')
115 if (styleSheet.href == null) {
116 return
117 }
118β
119 link.rel = 'stylesheet'
120 link.type = styleSheet.type
121 link.media = styleSheet.media.toString()
122 link.href = styleSheet.href
123 pip.document.head.appendChild(link)
124 }
125 })
126 delegateEvents(
127 [
128 'focusin',
129 'focusout',
130 'pointermove',
131 'keydown',
132 'pointerdown',
133 'pointerup',
134 'click',
135 'mousedown',
136 'input',
137 ],
138 pip.document,
139 )
140 props.setLocalStore('pip_open', 'true')
141 setPipWindow(pip)
142 }
143β
144 createEffect(() => {
145 const pip_open = (props.localStore.pip_open ?? 'false') as 'true' | 'false'
146 if (pip_open === 'true' && !props.disabled) {
147 try {
148 requestPipWindow(
149 Number(window.innerWidth),
150 Number(props.localStore.height || PIP_DEFAULT_HEIGHT),
151 )
152 } catch (error) {
153 if (error instanceof PipOpenError) {
154 console.error(error.message)
155 props.setLocalStore('pip_open', 'false')
156 props.setLocalStore('open', 'false')
157 return
158 }
159 throw error
160 }
161 }
162 })
163β
164 const value = createMemo(() => ({
165 pipWindow: pipWindow(),
166 requestPipWindow,
167 closePipWindow,
168 disabled: props.disabled ?? false,
169 }))
170β
171 return (
172 <PiPContext.Provider value={value}>{props.children}</PiPContext.Provider>
173 )
174}
175β
176/**
177 * Reads the picture-in-picture context provided by {@link PiPProvider}.
178 * @returns An accessor of the picture-in-picture window and the functions to
179 * open and close it.
180 */
181export const usePiPWindow = () => {
182 const context = createMemo(() => {
183 const ctx = useContext(PiPContext)
184 if (!ctx) {
185 throw new Error('usePiPWindow must be used within a PiPProvider')
186 }
187 return ctx()
188 })
189 return context
190}