Skip to content

Commit

Permalink
Fix responsive props sorting for correct css specificity
Browse files Browse the repository at this point in the history
  • Loading branch information
Temzasse committed Nov 14, 2020
1 parent e76cfd7 commit 92e165e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
10 changes: 8 additions & 2 deletions example/components/Main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,15 @@ export default function Main() {
<Divider size="large" color="grey-90" />

<Stack
axis={{ _: 'x', mdDown: 'y' }}
axis={{ _: 'x', sm: 'y', md: 'x', lgUp: 'y', xl: 'x' }}
align="center"
justify={{
_: 'space-between',
sm: 'flex-start',
lgDown: 'space-around',
xl: 'flex-end',
}}
spacing={{ _: 'large', mdDown: 'small' }}
dividers="grey-50"
>
<Box bg="powderblue">1 responsive</Box>
<Box bg="powderblue">2 responsive</Box>
Expand Down
33 changes: 30 additions & 3 deletions src/components/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ export const getImportant = (i: boolean) => (i ? '!important' : '');

const transient = (x: string) => `$${x}`;

// TODO: fix types for helper functions
// These things are so dynamic that typing them might be close to impossible...

export function parseProps<T extends object>(props: T, ownProps: string[]) {
return Object.entries(props).reduce(
(acc, [propKey, propValue]) => {
Expand Down Expand Up @@ -29,17 +32,41 @@ export function parseProps<T extends object>(props: T, ownProps: string[]) {
}
return acc;
},
{ $media: {} } as any // TODO: fix type
{ $media: {} } as any
);
}

// TODO: fix types
// Sort responsive props so that they are applied in correct order for CSS specificity
function getSortedMedia(parsedProps: any) {
const up: any[] = [];
const down: any[] = [];
const between: any[] = [];

Object.entries(parsedProps.$media).forEach(entry => {
const { min, max } = parsedProps.theme.breakpoints[entry[0]];

if (typeof min === 'number' && typeof max === 'number') {
between.push({ entry, min, max });
} else if (typeof min === 'number' && typeof max !== 'number') {
up.push({ entry, min });
} else {
down.push({ entry, max });
}
});

up.sort((a, b) => b.min - a.min);
down.sort((a, b) => a.max - b.max);
between.sort((a, b) => b.min - a.min);

return [...up, ...down, ...between].map(x => x.entry);
}

export function getResponsiveCSS(
parsedProps: any,
getCSS: (p: any, b?: boolean) => any
) {
if (!parsedProps.$media || !parsedProps.theme.media) return '';
return Object.entries(parsedProps.$media).map(([breakpoint, props]: any) => {
return getSortedMedia(parsedProps).map(([breakpoint, props]: any) => {
const breakpointCSS = getCSS({ ...parsedProps, ...props }, true); // true for adding !important
return parsedProps.theme.media[breakpoint]`${breakpointCSS}`;
});
Expand Down

0 comments on commit 92e165e

Please sign in to comment.