Skip to content
This repository has been archived by the owner on Nov 29, 2023. It is now read-only.

Commit

Permalink
tailwind: add shortenKeys function
Browse files Browse the repository at this point in the history
  • Loading branch information
arnemolland committed Jul 25, 2022
1 parent eee526b commit 87c03b9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
5 changes: 3 additions & 2 deletions src/tailwind/config.ts
Original file line number Diff line number Diff line change
@@ -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<TailwindConfig> => {
Expand All @@ -16,6 +16,7 @@ export const getConfig = (theme: Theme = gameflowTheme): Partial<TailwindConfig>
} = theme

const { fontSize, fontWeight, typographyComponents } = getTypographyConfig(typography)
const shortenedSpacing = shortenKeys(spacing)

return {
presets: [],
Expand All @@ -26,7 +27,7 @@ export const getConfig = (theme: Theme = gameflowTheme): Partial<TailwindConfig>
},
screens: breakpoints,
colors,
spacing,
spacing: shortenedSpacing,
animation,
boxShadow: shadows,
fontSize,
Expand Down
26 changes: 24 additions & 2 deletions src/tailwind/helpers.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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.
*/
Expand All @@ -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 = <T>(obj: Record<string, T>, 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 }), {})
}

0 comments on commit 87c03b9

Please sign in to comment.