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 redirected: 'gray',
29 } as const
30β
31 return match.isFetching && match.status === 'success'
32 ? match.isFetching === 'beforeLoad'
33 ? 'purple'
34 : 'blue'
35 : colorMap[match.status]
36}
37β
38export function getRouteStatusColor(
39 matches: Array<AnyRouteMatch>,
40 route: AnyRoute,
41) {
42 const found = matches.find((d) => d.routeId === route.id)
43 if (!found) return 'gray'
44 return getStatusColor(found)
45}
46β
47type Styles =
48 | JSX.CSSProperties
49 | ((props: Record<string, any>, theme: Theme) => JSX.CSSProperties)
50β
51export function styled<T extends keyof HTMLElementTagNameMap>(
52 type: T,
53 newStyles: Styles,
54 queries: Record<string, Styles> = {},
55) {
56 return ({
57 ref,
58 style,
59 ...rest
60 }: StyledComponent<T> & {
61 ref?: HTMLElementTagNameMap[T] | undefined
62 }) => {
63 const theme = useTheme()
64β
65 const mediaStyles = Object.entries(queries).reduce(
66 (current, [key, value]) => {
67 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
68 return useMediaQuery(key)
69 ? {
70 ...current,
71 ...(typeof value === 'function' ? value(rest, theme) : value),
72 }
73 : current
74 },
75 {},
76 )
77β
78 const baseStyles =
79 typeof newStyles === 'function' ? newStyles(rest, theme) : newStyles
80β
81 // Handle style being either a string or an object
82 const combinedStyles =
83 typeof style === 'string'
84 ? { ...baseStyles, ...mediaStyles, cssText: style }
85 : { ...baseStyles, ...style, ...mediaStyles }
86β
87 return (
88 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
89 // @ts-ignore
90 <Dynamic component={type} {...rest} style={combinedStyles} ref={ref} />
91 )
92 }
93}
94β
95export function useIsMounted() {
96 const [isMounted, setIsMounted] = createSignal(false)
97β
98 const effect = isServer ? createEffect : createRenderEffect
99β
100 effect(() => {
101 setIsMounted(true)
102 })
103β
104 return isMounted
105}
106β
107/**
108 * Displays a string regardless the type of the data
109 * @param {unknown} value Value to be stringified
110 */
111export const displayValue = (value: unknown) => {
112 const name = Object.getOwnPropertyNames(Object(value))
113 const newValue = typeof value === 'bigint' ? `${value.toString()}n` : value
114 try {
115 return JSON.stringify(newValue, name)
116 } catch (e) {
117 return `unable to stringify`
118 }
119}
120β
121/**
122 * This hook is a safe useState version which schedules state updates in microtasks
123 * to prevent updating a component state while React is rendering different components
124 * or when the component is not mounted anymore.
125 */
126export function useSafeState<T>(initialState: T): [T, (value: T) => void] {
127 const isMounted = useIsMounted()
128 const [state, setState] = createSignal(initialState)
129β
130 const safeSetState = (value: T) => {
131 scheduleMicrotask(() => {
132 if (isMounted()) {
133 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
134 // @ts-ignore
135 setState(value)
136 }
137 })
138 }
139β
140 return [state(), safeSetState]
141}
142β
143/**
144 * Schedules a microtask.
145 * This can be useful to schedule state updates after rendering.
146 */
147function scheduleMicrotask(callback: () => void) {
148 Promise.resolve()
149 .then(callback)
150 .catch((error) =>
151 setTimeout(() => {
152 throw error
153 }),
154 )
155}
156β
157export function multiSortBy<T>(
158 arr: Array<T>,
159 accessors: Array<(item: T) => any> = [(d) => d],
160): Array<T> {
161 return arr
162 .map((d, i) => [d, i] as const)
163 .sort(([a, ai], [b, bi]) => {
164 for (const accessor of accessors) {
165 const ao = accessor(a)
166 const bo = accessor(b)
167β
168 if (typeof ao === 'undefined') {
169 if (typeof bo === 'undefined') {
170 continue
171 }
172 return 1
173 }
174β
175 if (ao === bo) {
176 continue
177 }
178β
179 return ao > bo ? 1 : -1
180 }
181β
182 return ai - bi
183 })
184 .map(([d]) => d)
185}