Skip to content

Instantly share code, notes, and snippets.

@cezarneaga
Created October 10, 2023 11:35
Show Gist options
  • Save cezarneaga/3c20e4b8e236c75f5d0c6bcc99f8d3f0 to your computer and use it in GitHub Desktop.
Save cezarneaga/3c20e4b8e236c75f5d0c6bcc99f8d3f0 to your computer and use it in GitHub Desktop.
tailwind utility functions
const plugin = require('tailwindcss/plugin');
/** @type {import('tailwindcss').Config} */
module.exports = {
...
theme: {
extend: {},
...
},
plugins: [
// default utils
plugin(function ({ addVariant }) {
addVariant('default', 'html :where(&)');
}),
// focus utils
plugin(function ({ addBase, theme }) {
const tags = [
'button',
'a',
'input[type="button"]',
'input[type="file"]',
'input[type="reset"]',
];
addBase(
tags.reduce((obj, tag) => {
obj[`${tag}:focus-visible`] = {
'outline-style': 'solid',
'outline-width': theme('outlineWidth.2'),
'outline-color': theme('outlineColor.primary.900'),
};
return obj;
}, {})
);
}),
// mask utils
plugin(function ({ addUtilities, theme }) {
addUtilities({
'.mask-contain': {
'mask-size': 'contain',
},
'.mask-center': {
'mask-position': 'center center',
},
'.mask-no-repeat': {
'mask-repeat': 'no-repeat',
},
});
}),
// line height units as size
plugin(function ({ addUtilities, theme }) {
const sizes = Object.keys(theme('fontSize'));
addUtilities(
sizes.reduce((obj, size) => {
const sizeValue = theme(`lineHeight.${size}`);
obj[`.lh-size-${size}`] = {
width: sizeValue,
height: sizeValue,
};
return obj;
}, {})
);
}),
// type utils
plugin(function ({ addUtilities, theme }) {
const weights = Object.keys(theme('fontWeight'));
const sizes = Object.keys(theme('fontSize'));
const fonts = Object.keys(theme('fontFamily'));
const defaultWeight = 'regular';
const letterSpacingMapping = {
'50': '100',
'75': '100',
'100': '100',
'200': '100',
'300': '100',
'400': '100',
'500': '100',
'600': '50',
'700': '50',
'800': '50',
'900': '50',
};
addUtilities(
fonts.reduce((obj, font) => {
sizes.forEach((size) => {
weights.forEach((weight) => {
const name =
weight === defaultWeight
? `.type-${font}-${size}`
: `.type-${font}-${size}-${weight}`;
obj[name] = {
'font-family': theme(`fontFamily.${font}`),
'font-weight': theme(`fontWeight.${weight}`),
'font-size': theme(`fontSize.${size}`),
'line-height': theme(`lineHeight.${size}`),
'letter-spacing': theme(`letterSpacing.${letterSpacingMapping[size]}`),
};
});
});
return obj;
}, {})
);
}),
// line height units as size
plugin(function ({ addUtilities, theme }) {
const sizes = Object.keys(theme('fontSize'));
addUtilities(
sizes.reduce((obj, size) => {
const sizeValue = theme(`lineHeight.${size}`);
obj[`.lh-size-${size}`] = {
width: sizeValue,
height: sizeValue,
};
return obj;
}, {})
);
}),
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment