Open History to see the last commit
1import { Dynamic } from 'solid-js/web'
2import { createEffect, createRenderEffect, createSignal } from 'solid-js'
3import { useTheme } from './theme'
4import useMediaQuery from './useMediaQuery'
5import type { AnyRoute, AnyRouteMatch } from '@tanstack/router-core'
6β
7import type { Theme } from './theme'
8import type { JSX } from 'solid-js'
9β
10export const isServer = typeof window === 'undefined'
11β
12type StyledComponent<T> = T extends 'button'
13 ? JSX.ButtonHTMLAttributes<HTMLButtonElement>
14 : T extends 'input'
15 ? JSX.InputHTMLAttributes<HTMLInputElement>
16 : T extends 'select'
17 ? JSX.SelectHTMLAttributes<HTMLSelectElement>
18 : T extends keyof HTMLElementTagNameMap
19 ? JSX.HTMLAttributes<HTMLElementTagNameMap[T]>
20 : never
21β
22export function getStatusColor(match: AnyRouteMatch) {
23 const colorMap = {
24 pending: 'yellow',
25 success: 'green',
26 error: 'red',
27 notFound: 'purple',
28 } as const
29β
30 return match.isFetching && match.status === 'success'
31 ? match.isFetching === 'beforeLoad'
32 ? 'purple'
33 : 'blue'
34 : colorMap[match.status]
35}
36β
37export function getRouteStatusColor(
38 matches: Array<AnyRouteMatch>,
39 route: AnyRoute,
40) {
41 const found = matches.find((d) => d.routeId === route.id)
42 if (!found) return 'gray'
43 return getStatusColor(found)
44}
45β
46type Styles =
47 | JSX.CSSProperties
48 | ((props: Record<string, any>, theme: Theme) => JSX.CSSProperties)
49β
50export function styled<T extends keyof HTMLElementTagNameMap>(
51 type: T,
52 newStyles: Styles,
53 queries: Record<string, Styles> = {},
54) {
55 return ({
56 ref,
57 style,
58 ...rest
59 }: StyledComponent<T> & {
60 ref?: HTMLElementTagNameMap[T] | undefined
61 }) => {
62 const theme = useTheme()
63β
64 const mediaStyles = Object.entries(queries).reduce(
65 (current, [key, value]) => {
66 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
67 return useMediaQuery(key)
68 ? {
69 ...current,
70 ...(typeof value === 'function' ? value(rest, theme) : value),
71 }
72 : current
73 },
74 {},
75 )
76β
77 const baseStyles =
78 typeof newStyles === 'function' ? newStyles(rest, theme) : newStyles
79β
80 // Handle style being either a string or an object
81 const combinedStyles =
82 typeof style === 'string'
83 ? { ...baseStyles, ...mediaStyles, cssText: style }
84 : { ...baseStyles, ...style, ...mediaStyles }
85β
86 return (
87 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
88 // @ts-ignore
89 <Dynamic component={type} {...rest} style={combinedStyles} ref={ref} />
90 )
91 }
92}
93β
94export function useIsMounted() {
95 const [isMounted, setIsMounted] = createSignal(false)
96β
97 const effect = isServer ? createEffect : createRenderEffect
98β
99 effect(() => {
100 setIsMounted(true)
101 })
102β
103 return isMounted
104}
105β
106// Symbols for RSC detection
107const SERVER_COMPONENT_STREAM = Symbol.for('tanstack.rsc.stream')
108const RENDERABLE_RSC = Symbol.for('tanstack.rsc.renderable')
109const RSC_SLOT_USAGES = Symbol.for('tanstack.rsc.slotUsages')
110β
111export type RscSlotUsageEvent = {
112 slot: string
113 args?: Array<any>
114}
115β
116function trimTrailingUndefined<T>(arr: Array<T>): Array<T> {
117 let end = arr.length
118 while (end > 0 && arr[end - 1] === undefined) end--
119 if (end === 0) return arr
120 return end === arr.length ? arr : arr.slice(0, end)
121}
122β
123export type ServerComponentType =
124 | 'compositeSource' // createCompositeComponent result (render via <CompositeComponent src={...} />)
125 | 'renderableValue' // renderServerComponent result (inline renderable value)
126 | null // not a server component
127β
128/**
129 * Checks if a value is any kind of server component
130 */
131export const isServerComponent = (value: unknown): boolean => {
132 return (
133 (typeof value === 'object' || typeof value === 'function') &&
134 value !== null &&
135 SERVER_COMPONENT_STREAM in value
136 )
137}
138β
139/**
140 * Gets the type of server component.
141 * - RENDERABLE_RSC === true β renderable (from renderServerComponent)
142 * - RENDERABLE_RSC === false or not present β composite (from createCompositeComponent)
143 */
144export const getServerComponentType = (value: unknown): ServerComponentType => {
145 if (!isServerComponent(value)) {
146 return null
147 }
148 const v = value as Record<symbol, unknown>
149 if (RENDERABLE_RSC in v && v[RENDERABLE_RSC] === true) {
150 return 'renderableValue'
151 }
152 // RENDERABLE_RSC is false or not present β composite
153 return 'compositeSource'
154}
155β
156/**
157 * Gets the slot names from a composite server component (dev only)
158 */
159export const getServerComponentSlots = (value: unknown): Array<string> => {
160 if (!isServerComponent(value)) {
161 return []
162 }
163β
164 const v = value as Record<symbol, unknown>
165 const out: Array<string> = []
166 // Include any slot names observed via dev-only slot usage events
167 if (RSC_SLOT_USAGES in v) {
168 const usages = v[RSC_SLOT_USAGES]
169 if (Array.isArray(usages)) {
170 for (const evt of usages) {
171 const name = evt?.slot
172 if (typeof name === 'string' && !out.includes(name)) {
173 out.push(name)
174 }
175 }
176 }
177 }
178β
179 return out
180}
181β
182export const getServerComponentSlotUsages = (
183 value: unknown,
184): Array<RscSlotUsageEvent> => {
185 if (!isServerComponent(value)) {
186 return []
187 }
188β
189 const v = value as Record<symbol, unknown>
190 if (!(RSC_SLOT_USAGES in v)) return []
191 const usages = v[RSC_SLOT_USAGES]
192 if (!Array.isArray(usages)) return []
193β
194 return usages.filter((d): d is RscSlotUsageEvent => {
195 return (
196 d &&
197 typeof d === 'object' &&
198 typeof d.slot === 'string' &&
199 (d.args === undefined || Array.isArray(d.args))
200 )
201 })
202}
203β
204export const getServerComponentSlotUsageSummary = (
205 value: unknown,
206): Record<string, { count: number; invocations: Array<Array<any>> }> => {
207 const usages = getServerComponentSlotUsages(value)
208 const out: Record<string, { count: number; invocations: Array<Array<any>> }> =
209 {}
210 for (const evt of usages) {
211 const args = trimTrailingUndefined(evt.args ?? [])
212 const prev =
213 out[evt.slot] ?? (out[evt.slot] = { count: 0, invocations: [] })
214 prev.count++
215 prev.invocations.push(args)
216 }
217 return out
218}
219β
220/**
221 * Displays a string regardless the type of the data
222 * @param {unknown} value Value to be stringified
223 */
224export const displayValue = (value: unknown) => {
225 if (value === 'React element') return 'React element'
226 const componentType = getServerComponentType(value)
227 if (componentType === 'compositeSource') {
228 const slots = getServerComponentSlots(value)
229 if (slots.length > 0) {
230 return `RSC composite source (${slots.length} ${
231 slots.length === 1 ? 'slot' : 'slots'
232 })`
233 }
234 return 'RSC composite source'
235 }
236 if (componentType === 'renderableValue') {
237 return 'RSC renderable value'
238 }
239 const name = Object.getOwnPropertyNames(Object(value))
240 const newValue = typeof value === 'bigint' ? `${value.toString()}n` : value
241 try {
242 return JSON.stringify(newValue, name)
243 } catch {
244 return `unable to stringify`
245 }
246}
247β
248/**
249 * This hook is a safe useState version which schedules state updates in microtasks
250 * to prevent updating a component state while React is rendering different components
251 * or when the component is not mounted anymore.
252 */
253export function useSafeState<T>(initialState: T): [T, (value: T) => void] {
254 const isMounted = useIsMounted()
255 const [state, setState] = createSignal(initialState)
256β
257 const safeSetState = (value: T) => {
258 scheduleMicrotask(() => {
259 if (isMounted()) {
260 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
261 // @ts-ignore
262 setState(value)
263 }
264 })
265 }
266β
267 return [state(), safeSetState]
268}
269β
270/**
271 * Schedules a microtask.
272 * This can be useful to schedule state updates after rendering.
273 */
274function scheduleMicrotask(callback: () => void) {
275 Promise.resolve()
276 .then(callback)
277 .catch((error) =>
278 setTimeout(() => {
279 throw error
280 }),
281 )
282}
283β
284export function multiSortBy<T>(
285 arr: Array<T>,
286 accessors: Array<(item: T) => any> = [(d) => d],
287): Array<T> {
288 return arr
289 .map((d, i) => [d, i] as const)
290 .sort(([a, ai], [b, bi]) => {
291 for (const accessor of accessors) {
292 const ao = accessor(a)
293 const bo = accessor(b)
294β
295 if (typeof ao === 'undefined') {
296 if (typeof bo === 'undefined') {
297 continue
298 }
299 return 1
300 }
301β
302 if (ao === bo) {
303 continue
304 }
305β
306 return ao > bo ? 1 : -1
307 }
308β
309 return ai - bi
310 })
311 .map(([d]) => d)
312}