Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

PiPContext.tsx

219 lines6.0 KB

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