Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: invalid return type of cssVariables function #5

Merged
merged 4 commits into from
May 10, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 23 additions & 6 deletions src/utils/styles.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
import { css } from 'styled-components'
import { SolvedTheme } from '../styles'

export const toCssName = (name: string): string =>
name.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`).replace(/^-/, '')
export type MakeKebabCase<S extends string, ReturnQueue extends string = ''> =
// Separate string into first character T and rest string U, only works if length >= 1
S extends `${infer T}${infer U}`
// If it's the first character of whole string, just lowercase first character
? ReturnQueue extends ''
? MakeKebabCase<U, Lowercase<T>>
// if it's uppercased character, append -${Lowercase<T>} into return queue
: T extends Uppercase<T>
? MakeKebabCase<U, `${ReturnQueue}-${Lowercase<T>}`>
// or, just append itself
: MakeKebabCase<U, `${ReturnQueue}${T}`>
// It's else branch of the first length >= 1 check
: `${ReturnQueue}${S}`

export const toCssName = <S extends string>(name: S): MakeKebabCase<S> =>
name.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`).replace(/^-/, '') as MakeKebabCase<S>

export type VariableName<Prefix extends string, Name> =
`--solvedac-${MakeKebabCase<Prefix>}-${MakeKebabCase<Name extends string ? Name : string>}`

export const cssVariables = <
T extends {
Expand All @@ -13,8 +30,8 @@ export const cssVariables = <
defaults: T,
prefix: P
): {
vars: { [key in keyof T]: `--solvedac-${string}` }
v: { [key in keyof T]: `var(--solvedac-${P}-${string})` }
vars: { [K in keyof T]: VariableName<P, K> }
v: { [K in keyof T]: `var(${VariableName<P, K>})` }
styles: (theme: SolvedTheme) => string
} => {
const names = Object.keys(defaults)
Expand All @@ -24,11 +41,11 @@ export const cssVariables = <
name,
`--solvedac-${toCssName(prefix)}-${toCssName(name)}`,
])
) as { [key in keyof T]: `--solvedac-${string}` }
) as { [K in keyof T]: VariableName<P, K> }

const v = Object.fromEntries(
Object.entries(vars).map(([k, v]) => [k, `var(${v})`])
) as { [key in keyof T]: `var(--solvedac-${P}-${string})` }
) as { [K in keyof T]: `var(${VariableName<P, K>})` }

const styles = (theme: SolvedTheme): string =>
(
Expand Down