Skip to content

Commit

Permalink
add support for arbitrary custom properties (CSS variables) and re-ar…
Browse files Browse the repository at this point in the history
…chitect tailwind-merge config
  • Loading branch information
dcastil committed Jan 26, 2025
1 parent 8992454 commit ddc6ae8
Show file tree
Hide file tree
Showing 9 changed files with 1,015 additions and 702 deletions.
1,178 changes: 657 additions & 521 deletions src/lib/default-config.ts

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion src/lib/parse-class-name.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ export const createParseClassName = (config: AnyConfig) => {
const modifiers = []

let bracketDepth = 0
let parenDepth = 0
let modifierStart = 0
let postfixModifierPosition: number | undefined

for (let index = 0; index < className.length; index++) {
let currentCharacter = className[index]

if (bracketDepth === 0) {
if (bracketDepth === 0 && parenDepth === 0) {
if (
currentCharacter === firstSeparatorCharacter &&
(isSeparatorSingleCharacter ||
Expand All @@ -40,6 +41,10 @@ export const createParseClassName = (config: AnyConfig) => {
bracketDepth++
} else if (currentCharacter === ']') {
bracketDepth--
} else if (currentCharacter === '(') {
parenDepth++
} else if (currentCharacter === ')') {
parenDepth--
}
}

Expand Down
49 changes: 25 additions & 24 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,31 +168,24 @@ export type NoInfer<T> = [T][T extends any ? 0 : never]
* (the list of supported keys may vary between `tailwind-merge` versions)
*/
export type DefaultThemeGroupIds =
| 'animate'
| 'aspect'
| 'blur'
| 'borderColor'
| 'borderRadius'
| 'borderSpacing'
| 'borderWidth'
| 'brightness'
| 'colors'
| 'contrast'
| 'gap'
| 'gradientColorStopPositions'
| 'gradientColorStops'
| 'grayscale'
| 'hueRotate'
| 'inset'
| 'invert'
| 'margin'
| 'opacity'
| 'padding'
| 'saturate'
| 'scale'
| 'sepia'
| 'skew'
| 'space'
| 'breakpoint'
| 'color'
| 'container'
| 'drop-shadow'
| 'ease'
| 'font-weight'
| 'font'
| 'inset-shadow'
| 'leading'
| 'perspective'
| 'radius'
| 'shadow'
| 'spacing'
| 'translate'
| 'text'
| 'tracking'

/**
* Class group IDs included in the default configuration of tailwind-merge.
Expand All @@ -217,6 +210,7 @@ export type DefaultClassGroupIds =
| 'backdrop-opacity'
| 'backdrop-saturate'
| 'backdrop-sepia'
| 'backface'
| 'basis'
| 'bg-attachment'
| 'bg-blend'
Expand Down Expand Up @@ -292,8 +286,8 @@ export type DefaultClassGroupIds =
| 'float'
| 'font-family'
| 'font-size'
| 'font-stretch'
| 'font-smoothing'
| 'font-stretch'
| 'font-style'
| 'font-weight'
| 'forced-color-adjust'
Expand Down Expand Up @@ -414,8 +408,10 @@ export type DefaultClassGroupIds =
| 'row-start-end'
| 'row-start'
| 'saturate'
| 'scale-3d'
| 'scale-x'
| 'scale-y'
| 'scale-z'
| 'scale'
| 'scroll-behavior'
| 'scroll-m'
Expand Down Expand Up @@ -444,6 +440,7 @@ export type DefaultClassGroupIds =
| 'size'
| 'skew-x'
| 'skew-y'
| 'skew'
| 'snap-align'
| 'snap-stop'
| 'snap-strictness'
Expand Down Expand Up @@ -475,9 +472,13 @@ export type DefaultClassGroupIds =
| 'transform-origin'
| 'transform-style'
| 'transform'
| 'transition-behavior'
| 'transition'
| 'translate-none'
| 'translate-x'
| 'translate-y'
| 'translate-z'
| 'translate'
| 'underline-offset'
| 'vertical-align'
| 'visibility'
Expand Down
113 changes: 85 additions & 28 deletions src/lib/validators.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const arbitraryValueRegex = /^\[(?:([a-z-]+):)?(.+)\]$/i
const arbitraryValueRegex = /^\[(?:(\w[\w-]*):)?(.+)\]$/i
const arbitraryVariableRegex = /^\((?:(\w[\w-]*):)?(.+)\)$/i
const fractionRegex = /^\d+\/\d+$/
const stringLengths = new Set(['px', 'full', 'screen'])
const tshirtUnitRegex = /^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/
const lengthUnitRegex =
/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/
Expand All @@ -10,49 +10,81 @@ const shadowRegex = /^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]
const imageRegex =
/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/

export const isLength = (value: string) =>
isNumber(value) || stringLengths.has(value) || fractionRegex.test(value)

export const isArbitraryLength = (value: string) =>
getIsArbitraryValue(value, 'length', isLengthOnly)
export const isFraction = (value: string) => fractionRegex.test(value)

export const isNumber = (value: string) => Boolean(value) && !Number.isNaN(Number(value))

export const isArbitraryNumber = (value: string) => getIsArbitraryValue(value, 'number', isNumber)

export const isInteger = (value: string) => Boolean(value) && Number.isInteger(Number(value))

export const isPercent = (value: string) => value.endsWith('%') && isNumber(value.slice(0, -1))

export const isArbitraryValue = (value: string) => arbitraryValueRegex.test(value)

export const isTshirtSize = (value: string) => tshirtUnitRegex.test(value)

const sizeLabels = new Set(['length', 'size', 'percentage'])
export const isAny = () => true

const isLengthOnly = (value: string) =>
// `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.
// For example, `hsl(0 0% 0%)` would be classified as a length without this check.
// I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.
lengthUnitRegex.test(value) && !colorFunctionRegex.test(value)

const isNever = () => false

export const isArbitrarySize = (value: string) => getIsArbitraryValue(value, sizeLabels, isNever)
const isShadow = (value: string) => shadowRegex.test(value)

const isImage = (value: string) => imageRegex.test(value)

export const isAnyNonArbitrary = (value: string) =>
!isArbitraryValue(value) && !isArbitraryVariable(value)

export const isArbitrarySize = (value: string) => getIsArbitraryValue(value, isLabelSize, isNever)

export const isArbitraryValue = (value: string) => arbitraryValueRegex.test(value)

export const isArbitraryLength = (value: string) =>
getIsArbitraryValue(value, isLabelLength, isLengthOnly)

export const isArbitraryNumber = (value: string) =>
getIsArbitraryValue(value, isLabelNumber, isNumber)

export const isArbitraryPosition = (value: string) =>
getIsArbitraryValue(value, 'position', isNever)
getIsArbitraryValue(value, isLabelPosition, isNever)

const imageLabels = new Set(['image', 'url'])
export const isArbitraryImage = (value: string) => getIsArbitraryValue(value, isLabelImage, isImage)

export const isArbitraryImage = (value: string) => getIsArbitraryValue(value, imageLabels, isImage)
export const isArbitraryShadow = (value: string) => getIsArbitraryValue(value, isNever, isShadow)

export const isArbitraryShadow = (value: string) => getIsArbitraryValue(value, '', isShadow)
export const isArbitraryVariable = (value: string) => arbitraryVariableRegex.test(value)

export const isAny = () => true
export const isArbitraryVariableLength = (value: string) =>
getIsArbitraryVariable(value, isLabelLength)

export const isArbitraryVariableFamilyName = (value: string) =>
getIsArbitraryVariable(value, isLabelFamilyName)

export const isArbitraryVariablePosition = (value: string) =>
getIsArbitraryVariable(value, isLabelPosition)

export const isArbitraryVariableSize = (value: string) => getIsArbitraryVariable(value, isLabelSize)

export const isArbitraryVariableImage = (value: string) =>
getIsArbitraryVariable(value, isLabelImage)

export const isArbitraryVariableShadow = (value: string) =>
getIsArbitraryVariable(value, isLabelShadow, true)

// Helpers

const getIsArbitraryValue = (
value: string,
label: string | Set<string>,
testLabel: (label: string) => boolean,
testValue: (value: string) => boolean,
) => {
const result = arbitraryValueRegex.exec(value)

if (result) {
if (result[1]) {
return typeof label === 'string' ? result[1] === label : label.has(result[1])
return testLabel(result[1])
}

return testValue(result[2]!)
Expand All @@ -61,14 +93,39 @@ const getIsArbitraryValue = (
return false
}

const isLengthOnly = (value: string) =>
// `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.
// For example, `hsl(0 0% 0%)` would be classified as a length without this check.
// I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.
lengthUnitRegex.test(value) && !colorFunctionRegex.test(value)
const getIsArbitraryVariable = (
value: string,
testLabel: (label: string) => boolean,
shouldMatchNoLabel = false,
) => {
const result = arbitraryVariableRegex.exec(value)

const isNever = () => false
if (result) {
if (result[1]) {
return testLabel(result[1])
}
return shouldMatchNoLabel
}

const isShadow = (value: string) => shadowRegex.test(value)
return false
}

const isImage = (value: string) => imageRegex.test(value)
// Labels

const isLabelPosition = (label: string) => label === 'position'

const imageLabels = new Set(['image', 'url'])

const isLabelImage = (label: string) => imageLabels.has(label)

const sizeLabels = new Set(['length', 'size', 'percentage'])

const isLabelSize = (label: string) => sizeLabels.has(label)

const isLabelLength = (label: string) => label === 'length'

const isLabelNumber = (label: string) => label === 'number'

const isLabelFamilyName = (label: string) => label === 'family-name'

const isLabelShadow = (label: string) => label === 'shadow'
13 changes: 12 additions & 1 deletion tests/arbitrary-values.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ test('handles simple conflicts with arbitrary values correctly', () => {
// Handling of value `0`
expect(twMerge('min-h-[0.5px] min-h-[0]')).toBe('min-h-[0]')
expect(twMerge('text-[0.5px] text-[color:0]')).toBe('text-[0.5px] text-[color:0]')
expect(twMerge('text-[0.5px] text-[--my-0]')).toBe('text-[0.5px] text-[--my-0]')
expect(twMerge('text-[0.5px] text-(--my-0)')).toBe('text-[0.5px] text-(--my-0)')
})

test('handles arbitrary length conflicts with labels and modifiers correctly', () => {
Expand Down Expand Up @@ -76,3 +76,14 @@ test('handles ambiguous arbitrary values correctly', () => {
),
).toBe('bg-linear-to-r')
})

test('handles arbitrary custom properties correctly', () => {
expect(twMerge('bg-red bg-(--other-red) bg-bottom bg-(position:-my-pos)')).toBe(
'bg-(--other-red) bg-(position:-my-pos)',
)
expect(
twMerge(
'shadow-xs shadow-(shadow:--something) shadow-red shadow-(--some-other-shadow) shadow-(color:--some-color)',
),
).toBe('shadow-(--some-other-shadow) shadow-(color:--some-color)')
})
9 changes: 5 additions & 4 deletions tests/class-map.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ test('class map has correct class groups at first part', () => {
'backdrop-saturate',
'backdrop-sepia',
],
backface: ['backface'],
basis: ['basis'],
bg: [
'bg-attachment',
Expand Down Expand Up @@ -211,7 +212,7 @@ test('class map has correct class groups at first part', () => {
],
row: ['row-end', 'row-start', 'row-start-end'],
saturate: ['saturate'],
scale: ['scale', 'scale-x', 'scale-y'],
scale: ['scale', 'scale-3d', 'scale-x', 'scale-y', 'scale-z'],
scheme: ['color-scheme'],
scroll: [
'scroll-behavior',
Expand Down Expand Up @@ -240,7 +241,7 @@ test('class map has correct class groups at first part', () => {
shadow: ['shadow', 'shadow-color'],
shrink: ['shrink'],
size: ['size'],
skew: ['skew-x', 'skew-y'],
skew: ['skew', 'skew-x', 'skew-y'],
slashed: ['fvn-slashed-zero'],
snap: ['snap-align', 'snap-stop', 'snap-strictness', 'snap-type'],
space: ['space-x', 'space-x-reverse', 'space-y', 'space-y-reverse'],
Expand All @@ -259,8 +260,8 @@ test('class map has correct class groups at first part', () => {
touch: ['touch', 'touch-pz', 'touch-x', 'touch-y'],
tracking: ['tracking'],
transform: ['transform', 'transform-style'],
transition: ['transition'],
translate: ['translate-x', 'translate-y'],
transition: ['transition', 'transition-behavior'],
translate: ['translate', 'translate-none', 'translate-x', 'translate-y', 'translate-z'],
truncate: ['text-overflow'],
underline: ['text-decoration', 'underline-offset'],
uppercase: ['text-transform'],
Expand Down
19 changes: 14 additions & 5 deletions tests/public-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,28 @@ test('has correct export types', () => {
expect(getDefaultConfig).toStrictEqual(expect.any(Function))
expect(validators).toMatchObject({
isAny: expect.any(Function),
isAnyNonArbitrary: expect.any(Function),
isArbitraryImage: expect.any(Function),
isArbitraryLength: expect.any(Function),
isArbitraryNumber: expect.any(Function),
isArbitraryPosition: expect.any(Function),
isArbitraryShadow: expect.any(Function),
isArbitrarySize: expect.any(Function),
isArbitraryImage: expect.any(Function),
isArbitraryValue: expect.any(Function),
isArbitraryVariable: expect.any(Function),
isArbitraryVariableFamilyName: expect.any(Function),
isArbitraryVariableImage: expect.any(Function),
isArbitraryVariableLength: expect.any(Function),
isArbitraryVariablePosition: expect.any(Function),
isArbitraryVariableShadow: expect.any(Function),
isArbitraryVariableSize: expect.any(Function),
isFraction: expect.any(Function),
isInteger: expect.any(Function),
isLength: expect.any(Function),
isPercent: expect.any(Function),
isNumber: expect.any(Function),
isPercent: expect.any(Function),
isTshirtSize: expect.any(Function),
})
expect(Object.keys(validators)).toHaveLength(13)
expect(Object.keys(validators)).toHaveLength(21)
expect(mergeConfigs).toStrictEqual(expect.any(Function))
expect(extendTailwindMerge).toStrictEqual(expect.any(Function))
expect(twJoin).toStrictEqual(expect.any(Function))
Expand Down Expand Up @@ -151,10 +159,11 @@ test('createTailwindMerge() has correct inputs and outputs', () => {
})

test('validators have correct inputs and outputs', () => {
expect(validators.isLength('')).toEqual(expect.any(Boolean))
expect(validators.isFraction('')).toEqual(expect.any(Boolean))
expect(validators.isArbitraryLength('')).toEqual(expect.any(Boolean))
expect(validators.isInteger('')).toEqual(expect.any(Boolean))
expect(validators.isArbitraryValue('')).toEqual(expect.any(Boolean))
expect(validators.isArbitraryVariable('')).toEqual(expect.any(Boolean))
expect(validators.isAny()).toEqual(expect.any(Boolean))
expect(validators.isTshirtSize('')).toEqual(expect.any(Boolean))
expect(validators.isArbitrarySize('')).toEqual(expect.any(Boolean))
Expand Down
Loading

0 comments on commit ddc6ae8

Please sign in to comment.