From 14166d306ef01a890bd94d909def801b5946d77a Mon Sep 17 00:00:00 2001 From: Dany Castillo <31006608+dcastil@users.noreply.github.com> Date: Mon, 12 Aug 2024 12:53:59 +0200 Subject: [PATCH 1/2] add test case for spaces at beginning or end of input --- tests/wonky-inputs.test.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 tests/wonky-inputs.test.ts 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') +}) From 400b90d1ff98be49573029e2db849998d512402b Mon Sep 17 00:00:00 2001 From: Dany Castillo <31006608+dcastil@users.noreply.github.com> Date: Mon, 12 Aug 2024 12:55:27 +0200 Subject: [PATCH 2/2] fix space at beginning of input causing infinite loop --- src/lib/merge-classlist.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) 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)