Skip to content

Instantly share code, notes, and snippets.

@ibnlanre
Created September 20, 2023 16:28
Show Gist options
  • Select an option

  • Save ibnlanre/403993196715fd755d0834ca0b83949e to your computer and use it in GitHub Desktop.

Select an option

Save ibnlanre/403993196715fd755d0834ca0b83949e to your computer and use it in GitHub Desktop.
Utility to get the styles assigned to a certain size
import {
MantineTheme,
ButtonStylesParams,
ButtonStylesNames,
CSSObject,
rem,
} from "@mantine/core";
import { getButtonStyles } from "./get-button-styles";
export const Button: MantineTheme["components"]["Button"] = {
styles: (
theme,
{ compact }: ButtonStylesParams,
{ size = "sm" }
): Partial<Record<ButtonStylesNames, CSSObject>> => {
const getStyle = getButtonStyles(compact ? "compact" : size);
return {
inner: {
gap: rem(8),
paddingBlock: getStyle("paddingBlock"),
paddingInline: getStyle("paddingInline"),
},
label: {
lineHeight: getStyle("lineHeight", rem),
textAlign: "center",
},
}
}
}
import { getSizeStyles } from "./get-size-styles";
export const getButtonStyles = getSizeStyles({
xs: {
marginRight: 2,
marginLeft: 2,
paddingInline: 8,
paddingBlock: 12,
lineHeight: 14.25,
fontSize: 10,
},
sm: {
marginRight: 4,
marginLeft: 4,
paddingBlock: 16,
paddingInline: 16,
lineHeight: 14.25,
fontSize: 14,
},
compact: {
marginRight: 0,
marginLeft: 0,
paddingBlock: 8,
paddingInline: 8,
lineHeight: 18.48,
fontSize: 14,
},
});
import { CSSProperties } from "react";
type Size = string | number;
type Property = keyof CSSProperties;
type CSSProps<Type> = Partial<Record<Property, Type>>;
type Transformer<Type, Value> = (value: Type) => Value;
export type Sizes<Type> = Record<Size, CSSProps<Type>>;
export function getSizeStyles<Type>(sizes: Sizes<Type>) {
return function getStyles(size: Size) {
const styles = sizes[size];
if (!styles) return (property: Property) => undefined;
function getStyle(property: Property): Type | undefined;
function getStyle<Type, Value>(
property: Property,
transformer: Transformer<Type, Value>
): Value;
function getStyle<Type, Value>(
property: Property,
transformer?: Transformer<Type, Value>
) {
const value = styles[property];
if (typeof value === "undefined") return undefined;
return transformer ? transformer(value as Type) : value;
}
return getStyle;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment