Skip to content

Commit

Permalink
Merge pull request #457 from dcastil/bugfix/456/fix-space-at-beginnin…
Browse files Browse the repository at this point in the history
…g-causing-infinite-loop

Fx space at beginning of input causing infinite loop
  • Loading branch information
dcastil committed Aug 12, 2024
2 parents b42e596 + 400b90d commit 80d01a1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/lib/merge-classlist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,21 @@ export const mergeClassList = (classList: string, configUtils: ConfigUtils) => {
const classGroupsInConflict: string[] = []

let result = ''
let index = classList.length - 1

for (let i = classList.length - 1; i >= 0; ) {
while (classList[i] === ' ') {
--i
while (index >= 0) {
while (classList[index] === ' ') {
index -= 1
}
const nextI = classList.lastIndexOf(' ', i)
const originalClassName = classList.slice(nextI === -1 ? 0 : nextI + 1, i + 1)
i = nextI

if (index < 0) {
break
}

const nextIndex = classList.lastIndexOf(' ', index)
const originalClassName = classList.slice(nextIndex + 1, index + 1)

index = nextIndex

const { modifiers, hasImportantModifier, baseClassName, maybePostfixModifierPosition } =
parseClassName(originalClassName)
Expand Down
9 changes: 9 additions & 0 deletions tests/wonky-inputs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { twMerge } from '../src'

test('handles wonky inputs', () => {
expect(twMerge(' block')).toBe('block')
expect(twMerge('block ')).toBe('block')
expect(twMerge(' block ')).toBe('block')
expect(twMerge(' block px-2 py-4 ')).toBe('block px-2 py-4')
expect(twMerge(' block px-2', ' ', ' py-4 ')).toBe('block px-2 py-4')
})

0 comments on commit 80d01a1

Please sign in to comment.