diff --git a/src/lib/merge-classlist.ts b/src/lib/merge-classlist.ts index 099f9e9..c2def03 100644 --- a/src/lib/merge-classlist.ts +++ b/src/lib/merge-classlist.ts @@ -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) diff --git a/tests/wonky-inputs.test.ts b/tests/wonky-inputs.test.ts new file mode 100644 index 0000000..afd16fd --- /dev/null +++ b/tests/wonky-inputs.test.ts @@ -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') +})