Skip to content

Commit

Permalink
pref: improve performance of resolveBreakpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
MellowCo committed May 17, 2024
1 parent 5dc9d70 commit 9a623bd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
23 changes: 14 additions & 9 deletions src/utils/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,19 +275,24 @@ export function hasParseableColor(color: string | undefined, theme: Theme, key:
return color != null && !!parseColor(color, theme, key)?.color
}

const reLetters = /[a-z]+/gi
const resolvedBreakpoints = new WeakMap<any, { point: string, size: string }[]>()

export function resolveBreakpoints({ theme, generator }: Readonly<VariantContext<Theme>>, key: 'breakpoints' | 'verticalBreakpoints' = 'breakpoints') {
let breakpoints: Record<string, string> | undefined
if (generator.userConfig && generator.userConfig.theme)
breakpoints = (generator.userConfig.theme as any)[key]
const breakpoints: Record<string, string> | undefined = (generator?.userConfig?.theme as any)?.[key] || theme[key]

if (!breakpoints)
breakpoints = theme[key]
return undefined

if (resolvedBreakpoints.has(theme))
return resolvedBreakpoints.get(theme)

const resolved = Object.entries(breakpoints)
.sort((a, b) => Number.parseInt(a[1].replace(reLetters, '')) - Number.parseInt(b[1].replace(reLetters, '')))
.map(([point, size]) => ({ point, size }))

return breakpoints
? Object.entries(breakpoints)
.sort((a, b) => Number.parseInt(a[1].replace(/[a-z]+/gi, '')) - Number.parseInt(b[1].replace(/[a-z]+/gi, '')))
.map(([point, size]) => ({ point, size }))
: undefined
resolvedBreakpoints.set(theme, resolved)
return resolved
}

export function resolveVerticalBreakpoints(context: Readonly<VariantContext<Theme>>) {
Expand Down
4 changes: 2 additions & 2 deletions src/variants/breakpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export function variantBreakpoints(): VariantObject {
return {
name: 'breakpoints',
match(matcher, context) {
const variantEntries: Array<[string, string, number]>
= (resolveBreakpoints(context) ?? []).map(({ point, size }, idx) => [point, size, idx])
const variantEntries: Array<[string, string, number]> = (resolveBreakpoints(context) ?? [])
.map(({ point, size }, idx) => [point, size, idx])
for (const [point, size, idx] of variantEntries) {
if (!regexCache[point])
regexCache[point] = new RegExp(`^((?:([al]t-|[<~]|max-))?${point}(?:${context.generator.config.separators.join('|')}))`)
Expand Down

0 comments on commit 9a623bd

Please sign in to comment.