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

PiPContext.tsx

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