From 87c03b973ab00afd66afd27e9a6c41547d5f40dc Mon Sep 17 00:00:00 2001 From: Arne Molland Date: Mon, 25 Jul 2022 15:16:44 +0200 Subject: [PATCH] tailwind: add shortenKeys function --- src/tailwind/config.ts | 5 +++-- src/tailwind/helpers.ts | 26 ++++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/tailwind/config.ts b/src/tailwind/config.ts index 3482b09..9e0ed86 100644 --- a/src/tailwind/config.ts +++ b/src/tailwind/config.ts @@ -1,6 +1,6 @@ import { gameflowTheme, Theme } from '~/foundation/index.js' import type { OptionalConfig as TailwindConfig } from 'tailwindcss/types/config.js' -import { getTypographyConfig } from './helpers.js' +import { getTypographyConfig, shortenKeys } from './helpers.js' import plugin from 'tailwindcss/plugin.js' export const getConfig = (theme: Theme = gameflowTheme): Partial => { @@ -16,6 +16,7 @@ export const getConfig = (theme: Theme = gameflowTheme): Partial } = theme const { fontSize, fontWeight, typographyComponents } = getTypographyConfig(typography) + const shortenedSpacing = shortenKeys(spacing) return { presets: [], @@ -26,7 +27,7 @@ export const getConfig = (theme: Theme = gameflowTheme): Partial }, screens: breakpoints, colors, - spacing, + spacing: shortenedSpacing, animation, boxShadow: shadows, fontSize, diff --git a/src/tailwind/helpers.ts b/src/tailwind/helpers.ts index 43777db..be6858e 100644 --- a/src/tailwind/helpers.ts +++ b/src/tailwind/helpers.ts @@ -1,7 +1,6 @@ import { Typography, TypographyData } from '~/foundation/index.js' /** - * * @param typography The typography to be converted to a CSS string. * @param prop The property to be used in the CSS string. * @returns An array of all the given props' values. @@ -13,7 +12,6 @@ const getPropsFromTypography = ( Object.keys(typography).reduce((acc, key) => ({ ...acc, [key]: typography[key][prop] }), {}) /** - * * @param typography The typography object to convert into CSS properties. * @returns All font sizes, font weights and the typography CSS classname keys. */ @@ -34,3 +32,27 @@ export const getTypographyConfig = ( return { fontSize, fontWeight, typographyComponents } } + +/** + * @param obj The spacing object to convert into an object with shorthand keys. + * @returns The spacing object with shorthand keys `(xxxs -> 3xs)`. + */ +export const shortenKeys = (obj: Record, key = 'x'): { [key: string]: T } => { + const values = Object.keys(obj).map((k) => { + let count = 0 + for (let i = 0; i < k.length; i++) { + if (k.charAt(i) === key) { + count++ + } + } + + if (count <= 1) { + return { [`${k}`]: obj[k] } + } + + const stripped = k.replaceAll(key, '') + return { [`${count}${key}${stripped}`]: obj[k] } + }) + + return values.reduce((acc, curr) => ({ ...acc, ...curr }), {}) +}