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

styles.ts

49 lines1.9 KB

1import cssText from './styles.css?inline'
2import type { Accessor } from 'solid-js'
3​
4/**
5 * Creates a function that adds the `-dark` modifier of a styles.css class in
6 * the dark theme.
7 * @param theme - The devtools theme.
8 * @returns A function that takes a class name and returns the class names.
9 */
10export const createThemed =
11 (theme: Accessor<'light' | 'dark'>) => (name: string) =>
12 theme() === 'dark' ? `${name} ${name}-dark` : name
13​
14// One constructed stylesheet per document: a constructed stylesheet can only
15// be adopted by the document that created it and that document's shadow roots.
16const sheets = new WeakMap<Document, CSSStyleSheet>()
17​
18/**
19 * Adopts the devtools stylesheet where `el` renders: the given
20 * `shadowDOMTarget`, else the shadow root that contains `el`, else the
21 * document that owns `el`. Adopted stylesheets are not `<style>` elements, so
22 * they need no CSP nonce and no Trusted Types policy.
23 * @param el - A connected element of the devtools.
24 * @param shadowDOMTarget - The shadow root to add the styles to.
25 */
26export function attachStyles(el: Element, shadowDOMTarget?: ShadowRoot) {
27 const root = el.getRootNode()
28 const container: Document | ShadowRoot =
29 shadowDOMTarget ??
30 // A shadow root is a document fragment with a host. `instanceof ShadowRoot`
31 // would miss shadow roots from other windows, e.g. picture-in-picture.
32 (root.nodeType === 11 && 'host' in root
33 ? (root as ShadowRoot)
34 : el.ownerDocument)
35 // Not supported before Safari 16.4 and Firefox 101, nor in jsdom.
36 if (!('adoptedStyleSheets' in (container as object))) return
37​
38 const doc = container.ownerDocument ?? container
39 let sheet = sheets.get(doc)
40 if (!sheet) {
41 sheet = new (doc.defaultView ?? window).CSSStyleSheet()
42 sheet.replaceSync(cssText)
43 sheets.set(doc, sheet)
44 }
45​
46 if (!container.adoptedStyleSheets.includes(sheet)) {
47 container.adoptedStyleSheets = [...container.adoptedStyleSheets, sheet]
48 }