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

utils.ts

319 lines7.7 KB

1import * as React from 'react'
2import SuperJSON from 'superjson'
3​
4import { useTheme } from './theme'
5import useMediaQuery from './useMediaQuery'
6import type { Theme } from './theme'
7import type { Query } from '@tanstack/react-query'
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 * @param {boolean} beautify Formats json to multiline
121 */
122export const displayValue = (value: unknown, beautify: boolean = false) => {
123 const { json } = SuperJSON.serialize(value)
124​
125 return JSON.stringify(json, null, beautify ? 2 : undefined)
127​
128// Sorting functions
129type SortFn = (a: Query, b: Query) => number
130​
131const getStatusRank = (q: Query) =>
132 q.state.fetchStatus !== 'idle'
133 ? 0
134 : !q.getObserversCount()
135 ? 3
136 : q.isStale()
137 ? 2
138 : 1
139​
140const queryHashSort: SortFn = (a, b) => a.queryHash.localeCompare(b.queryHash)
141​
142const dateSort: SortFn = (a, b) =>
143 a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1
144​
145const statusAndDateSort: SortFn = (a, b) => {
146 if (getStatusRank(a) === getStatusRank(b)) {
147 return dateSort(a, b)
148 }
149​
150 return getStatusRank(a) > getStatusRank(b) ? 1 : -1
152​
153export const sortFns: Record<string, SortFn> = {
154 'Status > Last Updated': statusAndDateSort,
155 'Query Hash': queryHashSort,
156 'Last Updated': dateSort,
158​
159export const minPanelSize = 70
160export const defaultPanelSize = 500
161export const sides: Record<Side, Side> = {
162 top: 'bottom',
163 bottom: 'top',
164 left: 'right',
165 right: 'left',
167​
168export type Corner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
169export type Side = 'left' | 'right' | 'top' | 'bottom'
170/**
171 * Check if the given side is vertical (left/right)
172 */
173export function isVerticalSide(side: Side) {
174 return ['left', 'right'].includes(side)
176/**
177 * Get the opposite side, eg 'left' => 'right'. 'top' => 'bottom', etc
178 */
179export function getOppositeSide(side: Side): Side {
180 return sides[side]
182/**
183 * Given as css prop it will return a sided css prop based on a given side
184 * Example given `border` and `right` it return `borderRight`
185 */
186export function getSidedProp<T extends string>(prop: T, side: Side) {
187 return `${prop}${
188 side.charAt(0).toUpperCase() + side.slice(1)
189 }` as `${T}${Capitalize<Side>}`
191​
192export interface SidePanelStyleOptions {
193 /**
194 * Position of the panel
195 * Defaults to 'bottom'
196 */
197 position?: Side
198 /**
199 * Staring height for the panel, it is set if the position is horizontal eg 'top' or 'bottom'
200 * Defaults to 500
201 */
202 height?: number
203 /**
204 * Staring width for the panel, it is set if the position is vertical eg 'left' or 'right'
205 * Defaults to 500
206 */
207 width?: number
208 /**
209 * RQ devtools theme
210 */
211 devtoolsTheme: Theme
212 /**
213 * Sets the correct transition and visibility styles
214 */
215 isOpen?: boolean
216 /**
217 * If the panel is resizing set to true to apply the correct transition styles
218 */
219 isResizing?: boolean
220 /**
221 * Extra panel style passed by the user
222 */
223 panelStyle?: React.CSSProperties
225​
226export function getSidePanelStyle({
227 position = 'bottom',
228 height,
229 width,
230 devtoolsTheme,
231 isOpen,
232 isResizing,
233 panelStyle,
234}: SidePanelStyleOptions): React.CSSProperties {
235 const oppositeSide = getOppositeSide(position)
236 const borderSide = getSidedProp('border', oppositeSide)
237 const isVertical = isVerticalSide(position)
238​
239 return {
240 ...panelStyle,
241 direction: 'ltr',
242 position: 'fixed',
243 [position]: 0,
244 [borderSide]: `1px solid ${devtoolsTheme.gray}`,
245 transformOrigin: oppositeSide,
246 boxShadow: '0 0 20px rgba(0,0,0,.3)',
247 zIndex: 99999,
248 // visibility will be toggled after transitions, but set initial state here
249 visibility: isOpen ? 'visible' : 'hidden',
250 ...(isResizing
251 ? {
252 transition: `none`,
253 }
254 : { transition: `all .2s ease` }),
255 ...(isOpen
256 ? {
257 opacity: 1,
258 pointerEvents: 'all',
259 transform: isVertical
260 ? `translateX(0) scale(1)`
261 : `translateY(0) scale(1)`,
262 }
263 : {
264 opacity: 0,
265 pointerEvents: 'none',
266 transform: isVertical
267 ? `translateX(15px) scale(1.02)`
268 : `translateY(15px) scale(1.02)`,
269 }),
270 ...(isVertical
271 ? {
272 top: 0,
273 height: '100vh',
274 maxWidth: '90%',
275 width:
276 typeof width === 'number' && width >= minPanelSize
277 ? width
278 : defaultPanelSize,
279 }
280 : {
281 left: 0,
282 width: '100%',
283 maxHeight: '90%',
284 height:
285 typeof height === 'number' && height >= minPanelSize
286 ? height
287 : defaultPanelSize,
288 }),
289 }
291​
292/**
293 * Get resize handle style based on a given side
294 */
295export function getResizeHandleStyle(
296 position: Side = 'bottom',
297): React.CSSProperties {
298 const isVertical = isVerticalSide(position)
299 const oppositeSide = getOppositeSide(position)
300 const marginSide = getSidedProp('margin', oppositeSide)
301​
302 return {
303 position: 'absolute',
304 cursor: isVertical ? 'col-resize' : 'row-resize',
305 zIndex: 100000,
306 [oppositeSide]: 0,
307 [marginSide]: `-4px`,
308 ...(isVertical
309 ? {
310 top: 0,
311 height: '100%',
312 width: '4px',
313 }
314 : {
315 width: '100%',
316 height: '4px',
317 }),
318 }