Skip to content

Instantly share code, notes, and snippets.

@giammyisjammy
Last active August 24, 2021 14:15
Show Gist options
  • Save giammyisjammy/b067d43a999aa51060e09a88f7d1a5b3 to your computer and use it in GitHub Desktop.
Save giammyisjammy/b067d43a999aa51060e09a88f7d1a5b3 to your computer and use it in GitHub Desktop.
Draft of types for media query helper
/*
* Media queries utility
*/
import capitalize from '@/helpers/capitalizeString'
import {
css,
DefaultTheme,
FlattenInterpolation,
ThemedCssFunction,
ThemedStyledProps
} from 'styled-components'
/*
* Taken from https://github.com/DefinitelyTyped/DefinitelyTyped/issues/32914
*/
// Update your breakpoints if you want
export const sizes = {
mobile: 375,
tablet: 768,
desktop: 1024,
large: 1560,
} as const
// Iterate through the sizes and create a media template
export const media = (Object.keys(sizes) as Array<keyof typeof sizes>).reduce(
(acc, label) => {
acc[label] = (first: any, ...interpolations: any[]) => css`
@media (min-width: ${sizes[label]}px) {
${css(first, ...interpolations)}
}
`
return acc
},
{} as {
[key in keyof typeof sizes]: ThemedCssFunction<DefaultTheme>
// [key in keyof typeof sizes]: MediaQuery
}
)
export default media
/* Example
const SomeDiv = styled.div`
display: flex;
....
${media.medium`
display: block
`}
`;
*/
/**
* Unfortunately, this type does NOT fix this use case:
*
* ```tsx
* interface Props {
* someProp: boolean
* }
* const Component = styled.div<Props>`
* // ...
* ${media.minTablet`
* // ...
* ${({ someProp, asdrubale = 'false' }) => // Why `var asdrubale: string`? Why TS???
* asdrubale &&
* css`
* // ..
* `}
* `}
* `
* ```
*/
type MediaQuery = <T extends object>(
first: any,
...interpolations: any[]
) => FlattenInterpolation<ThemedStyledProps<T, DefaultTheme>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment