Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with Special Characters in IDs (e.g., from React's useId()) #77

Open
samuelemde opened this issue Nov 25, 2024 · 1 comment
Open

Comments

@samuelemde
Copy link

Issue

The FloatingFocus utility fails to work on elements with IDs containing special characters, such as those generated by React's useId(). This occurs because the current implementation relies on document.querySelector, which does not support special characters in CSS selectors without escaping.

SyntaxError: Failed to execute 'querySelector' on 'Document': '#downshift-:Rjdj4vepjt6:-input' is not a valid selector.

The ids generated by useId() contain special characters (e.g. :r0:), which are valid in HTML but are not valid unescaped CSS selectors.

Suggested Fix

Replace the current document.querySelector call with document.getElementById, which natively supports special characters.

current code:

target = document.querySelector(`#${focusTargetAttribute}`) || target

suggested fix:

target = document.getElementById(focusTargetAttribute) || target;

Potential Test Case

it.each([
    ['colon and numbers', ':r0:'],
    ['periods', 'id.with.period'],
    ['underscores', 'id_with_underscore'],
    ['hyphens', 'id-with-hyphen'],
    ['dollar signs', 'id$with-dollar-sign'],
    ['brackets', 'id([{with-brackets}])'],
    ['at signs', 'id@with-at-sign'],
    ['question marks', 'id?with-question?'],
    ['exclamation marks', 'id!with-exclamation!'],
  ])('Should correctly handle focus target ids with %s ("%s")', (_, id) => {
    const floatingFocus = new FloatingFocus()
    floatingFocus.floater = floatingFocus.constructFloatingElement()

    const target = document.createElement('div')
    const focusTarget = document.createElement('div')

    target.setAttribute('focus-target', id)
    focusTarget.id = id

    document.body.appendChild(target)
    document.body.appendChild(focusTarget)

    floatingFocus.handleFocus({ target })

    expect(floatingFocus.target).toEqual(focusTarget)
    expect(focusTarget.classList.contains('focus')).toBe(true)
  })
@dominik-erni
Copy link

Please fix this issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants