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

PiPContext.tsx

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