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

utils.ts

318 lines7.6 KB

1import * as React from 'react'
2import type { Query } from '@tanstack/react-query'
3import SuperJSON from 'superjson'
4​
5import type { Theme } from './theme'
6import { useTheme } from './theme'
7import useMediaQuery from './useMediaQuery'
8​
9type StyledComponent<T> = T extends 'button'
10 ? React.DetailedHTMLProps<
11 React.ButtonHTMLAttributes<HTMLButtonElement>,
12 HTMLButtonElement
13 >
14 : T extends 'input'
15 ? React.DetailedHTMLProps<
16 React.InputHTMLAttributes<HTMLInputElement>,
17 HTMLInputElement
18 >
19 : T extends 'select'
20 ? React.DetailedHTMLProps<
21 React.SelectHTMLAttributes<HTMLSelectElement>,
22 HTMLSelectElement
23 >
24 : T extends keyof HTMLElementTagNameMap
25 ? React.HTMLAttributes<HTMLElementTagNameMap[T]>
26 : never
27​
28export function getQueryStatusColor({
29 queryState,
30 observerCount,
31 isStale,
32 theme,
33}: {
34 queryState: Query['state']
35 observerCount: number
36 isStale: boolean
37 theme: Theme
38}) {
39 return queryState.fetchStatus === 'fetching'
40 ? theme.active
41 : !observerCount
42 ? theme.gray
43 : queryState.fetchStatus === 'paused'
44 ? theme.paused
45 : isStale
46 ? theme.warning
47 : theme.success
49​
50export function getQueryStatusLabel(query: Query) {
51 return query.state.fetchStatus === 'fetching'
52 ? 'fetching'
53 : !query.getObserversCount()
54 ? 'inactive'
55 : query.state.fetchStatus === 'paused'
56 ? 'paused'
57 : query.isStale()
58 ? 'stale'
59 : 'fresh'
61​
62type Styles =
63 | React.CSSProperties
64 | ((props: Record<string, any>, theme: Theme) => React.CSSProperties)
65​
66export function styled<T extends keyof HTMLElementTagNameMap>(
67 type: T,
68 newStyles: Styles,
69 queries: Record<string, Styles> = {},
70) {
71 return React.forwardRef<HTMLElementTagNameMap[T], StyledComponent<T>>(
72 ({ style, ...rest }, ref) => {
73 const theme = useTheme()
74​
75 const mediaStyles = Object.entries(queries).reduce(
76 (current, [key, value]) => {
77 // eslint-disable-next-line react-hooks/rules-of-hooks
78 return useMediaQuery(key)
79 ? {
80 ...current,
81 ...(typeof value === 'function' ? value(rest, theme) : value),
82 }
83 : current
84 },
85 {},
86 )
87​
88 return React.createElement(type, {
89 ...rest,
90 style: {
91 ...(typeof newStyles === 'function'
92 ? newStyles(rest, theme)
93 : newStyles),
94 ...style,
95 ...mediaStyles,
96 },
97 ref,
98 })
99 },
100 )
102​
103export function useIsMounted() {
104 const mountedRef = React.useRef(false)
105 const isMounted = React.useCallback(() => mountedRef.current, [])
106​
107 React.useEffect(() => {
108 mountedRef.current = true
109 return () => {
110 mountedRef.current = false
111 }
112 }, [])
113​
114 return isMounted
116​
117/**
118 * Displays a string regardless the type of the data
119 * @param {unknown} value Value to be stringified
120 */
121export const displayValue = (value: unknown) => {
122 const { json } = SuperJSON.serialize(value)
123​
124 return JSON.stringify(json)
126​
127// Sorting functions
128type SortFn = (a: Query, b: Query) => number
129​
130const getStatusRank = (q: Query) =>
131 q.state.fetchStatus !== 'idle'
132 ? 0
133 : !q.getObserversCount()
134 ? 3
135 : q.isStale()
136 ? 2
137 : 1
138​
139const queryHashSort: SortFn = (a, b) => a.queryHash.localeCompare(b.queryHash)
140​
141const dateSort: SortFn = (a, b) =>
142 a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1
143​
144const statusAndDateSort: SortFn = (a, b) => {
145 if (getStatusRank(a) === getStatusRank(b)) {
146 return dateSort(a, b)
147 }
148​
149 return getStatusRank(a) > getStatusRank(b) ? 1 : -1
151​
152export const sortFns: Record<string, SortFn> = {
153 'Status > Last Updated': statusAndDateSort,
154 'Query Hash': queryHashSort,
155 'Last Updated': dateSort,
157​
158export const minPanelSize = 70
159export const defaultPanelSize = 500
160export const sides: Record<Side, Side> = {
161 top: 'bottom',
162 bottom: 'top',
163 left: 'right',
164 right: 'left',
166​
167export type Corner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
168export type Side = 'left' | 'right' | 'top' | 'bottom'
169/**
170 * Check if the given side is vertical (left/right)
171 */
172export function isVerticalSide(side: Side) {
173 return ['left', 'right'].includes(side)
175/**
176 * Get the opposite side, eg 'left' => 'right'. 'top' => 'bottom', etc
177 */
178export function getOppositeSide(side: Side): Side {
179 return sides[side]
181/**
182 * Given as css prop it will return a sided css prop based on a given side
183 * Example given `border` and `right` it return `borderRight`
184 */
185export function getSidedProp<T extends string>(prop: T, side: Side) {
186 return `${prop}${
187 side.charAt(0).toUpperCase() + side.slice(1)
188 }` as `${T}${Capitalize<Side>}`
190​
191export interface SidePanelStyleOptions {
192 /**
193 * Position of the panel
194 * Defaults to 'bottom'
195 */
196 position?: Side
197 /**
198 * Staring height for the panel, it is set if the position is horizontal eg 'top' or 'bottom'
199 * Defaults to 500
200 */
201 height?: number
202 /**
203 * Staring width for the panel, it is set if the position is vertical eg 'left' or 'right'
204 * Defaults to 500
205 */
206 width?: number
207 /**
208 * RQ devtools theme
209 */
210 devtoolsTheme: Theme
211 /**
212 * Sets the correct transition and visibility styles
213 */
214 isOpen?: boolean
215 /**
216 * If the panel is resizing set to true to apply the correct transition styles
217 */
218 isResizing?: boolean
219 /**
220 * Extra panel style passed by the user
221 */
222 panelStyle?: React.CSSProperties
224​
225export function getSidePanelStyle({
226 position = 'bottom',
227 height,
228 width,
229 devtoolsTheme,
230 isOpen,
231 isResizing,
232 panelStyle,
233}: SidePanelStyleOptions): React.CSSProperties {
234 const oppositeSide = getOppositeSide(position)
235 const borderSide = getSidedProp('border', oppositeSide)
236 const isVertical = isVerticalSide(position)
237​
238 return {
239 ...panelStyle,
240 direction: 'ltr',
241 position: 'fixed',
242 [position]: 0,
243 [borderSide]: `1px solid ${devtoolsTheme.gray}`,
244 transformOrigin: oppositeSide,
245 boxShadow: '0 0 20px rgba(0,0,0,.3)',
246 zIndex: 99999,
247 // visibility will be toggled after transitions, but set initial state here
248 visibility: isOpen ? 'visible' : 'hidden',
249 ...(isResizing
250 ? {
251 transition: `none`,
252 }
253 : { transition: `all .2s ease` }),
254 ...(isOpen
255 ? {
256 opacity: 1,
257 pointerEvents: 'all',
258 transform: isVertical
259 ? `translateX(0) scale(1)`
260 : `translateY(0) scale(1)`,
261 }
262 : {
263 opacity: 0,
264 pointerEvents: 'none',
265 transform: isVertical
266 ? `translateX(15px) scale(1.02)`
267 : `translateY(15px) scale(1.02)`,
268 }),
269 ...(isVertical
270 ? {
271 top: 0,
272 height: '100vh',
273 maxWidth: '90%',
274 width:
275 typeof width === 'number' && width >= minPanelSize
276 ? width
277 : defaultPanelSize,
278 }
279 : {
280 left: 0,
281 width: '100%',
282 maxHeight: '90%',
283 height:
284 typeof height === 'number' && height >= minPanelSize
285 ? height
286 : defaultPanelSize,
287 }),
288 }
290​
291/**
292 * Get resize handle style based on a given side
293 */
294export function getResizeHandleStyle(
295 position: Side = 'bottom',
296): React.CSSProperties {
297 const isVertical = isVerticalSide(position)
298 const oppositeSide = getOppositeSide(position)
299 const marginSide = getSidedProp('margin', oppositeSide)
300​
301 return {
302 position: 'absolute',
303 cursor: isVertical ? 'col-resize' : 'row-resize',
304 zIndex: 100000,
305 [oppositeSide]: 0,
306 [marginSide]: `-4px`,
307 ...(isVertical
308 ? {
309 top: 0,
310 height: '100%',
311 width: '4px',
312 }
313 : {
314 width: '100%',
315 height: '4px',
316 }),
317 }