Skip to content

Instantly share code, notes, and snippets.

@sehyunchung
Last active March 25, 2021 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sehyunchung/aa1f259747b73d7684a4e62113ba9eb1 to your computer and use it in GitHub Desktop.
Save sehyunchung/aa1f259747b73d7684a4e62113ba9eb1 to your computer and use it in GitHub Desktop.
// stitches.config.ts
import { createStyled } from '@stitches/react';
export type StitchesConfigsType = Parameters<typeof createStyled>[number];
function getItemOrLastItem<Item extends string | number>(
list: Item[],
itemIndex: number,
): Item | undefined {
if (list.length < 1) {
console.error('list is empty');
return undefined;
}
return list[itemIndex] !== undefined
? list[itemIndex]
: getItemOrLastItem(list, itemIndex - 1);
}
function setBreakpointsUtils<T extends string | number>(
props: T[],
suffix?: string = '$', // optional suffix. default is '$'
): StitchesConfigsType['utils'] {
const utilsAsEntries = props.map((prop) => [
`${prop}${suffix}`,
(config: StitchesConfigsType) => (value: T[]) => {
const breakpoints = config.breakpoints && Object.keys(config.breakpoints);
const propArr = breakpoints?.map((bp, bpIndex) => [
bp,
{ [prop]: getItemOrLastItem(value, bpIndex) },
]);
return propArr && Object.fromEntries(propArr);
},
]);
return Object.fromEntries(utilsAsEntries);
}
/*
1. setup:
export { css, styled } = createStyled({
breakpoints: {
'bp1': '(min-width: 640px)',
'bp2': '(min-width: 768px)',
'bp3': '(min-width: 1024px)',
},
utils: {
...setBreakpointsUtils(['fontSize'])
}
})
2. usage:
css({
...
fontSize$: ['0.4rem', '1rem', '1.2rem'],
...
)}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment