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

fix(nuxt): produce valid css selector from useId #25969

Merged
merged 2 commits into from
Feb 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 5 additions & 3 deletions packages/nuxt/src/app/composables/id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useNuxtApp } from '../nuxt'
import { clientOnlySymbol } from '#app/components/client-only'

const ATTR_KEY = 'data-n-ids'
const SEPARATOR = '-'

/**
* Generate an SSR-friendly unique identifier that can be passed to accessibility attributes.
Expand All @@ -13,7 +14,8 @@ export function useId (key?: string): string {
throw new TypeError('[nuxt] [useId] key must be a string.')
}
// TODO: implement in composable-keys
key = key.slice(1)
// Make sure key starts with a letter to be a valid selector
key = `n${key.slice(1)}`
const nuxtApp = useNuxtApp()
const instance = getCurrentInstance()

Expand All @@ -26,11 +28,11 @@ export function useId (key?: string): string {
instance._nuxtIdIndex ||= {}
instance._nuxtIdIndex[key] ||= 0

const instanceIndex = key + ':' + instance._nuxtIdIndex[key]++
const instanceIndex = key + SEPARATOR + instance._nuxtIdIndex[key]++

if (import.meta.server) {
const ids = JSON.parse(instance.attrs[ATTR_KEY] as string | undefined || '{}')
ids[instanceIndex] = key + ':' + nuxtApp._id++
ids[instanceIndex] = key + SEPARATOR + nuxtApp._id++
danielroe marked this conversation as resolved.
Show resolved Hide resolved
instance.attrs[ATTR_KEY] = JSON.stringify(ids)
return ids[instanceIndex]
}
Expand Down