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