aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/style/media.ts
blob: bbf3766942c468c98e0423462996a6398555ddef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { InterpolationValue } from 'styled-components';

import { css } from './theme';

export enum ScreenWidths {
    Sm = 40,
    Md = 52,
    Lg = 64,
}

export const generateMediaWrapper = (screenWidth: ScreenWidths) => (...args: any[]) => css`
    @media (max-width: ${screenWidth}em) {
        ${css.apply(css, args)};
    }
`;

export const media = {
    small: generateMediaWrapper(ScreenWidths.Sm),
    medium: generateMediaWrapper(ScreenWidths.Md),
    large: generateMediaWrapper(ScreenWidths.Lg),
};

export interface ScreenSpecification<T> {
    default: T;
    sm?: T;
    md?: T;
    lg?: T;
}
export type OptionallyScreenSpecific<T> = T | ScreenSpecification<T>;
export type MediaChoice = OptionallyScreenSpecific<string>;
/**
 * Given a css property name and a OptionallyScreenSpecific value,
 * generates css properties with screen-specific viewport styling
 */
export function stylesForMedia<T extends string | number>(
    cssPropertyName: string,
    choice: OptionallyScreenSpecific<T>,
): InterpolationValue[] {
    if (typeof choice === 'object') {
        return css`
        ${cssPropertyName}: ${choice.default};
        ${choice.lg && media.large`${cssPropertyName}: ${choice.lg}`}
        ${choice.md && media.medium`${cssPropertyName}: ${choice.md}`}
        ${choice.sm && media.small`${cssPropertyName}: ${choice.sm}`}
    `;
    } else {
        return css`
            ${cssPropertyName}: ${choice};
        `;
    }
}