material-web/migrations/v2/query-selector-aria.ts
Elizabeth Mitchell 5df9410e60 fix!: aria-labels announcing twice with "group" on components
BREAKING CHANGE: `querySelector` for `[role]` and `[aria-*]` attributes may no longer work. See `@material/web/migrations/v2/README.md` and `@material/web/migrations/v2/query-selector-aria.ts`.

Browser/SR test results (go/mwc-double-aria-test-results)
  -  VoiceOver on Chrome
  -  VoiceOver on iOS Safari
  -  TalkBack on Chrome
  -  ChromeVox on Chrome
  -  NVDA on Chrome
  -  NVDA on Firefox
  -  JAWS on Chrome
  -  JAWS on Firefox
  (Optional)
  -  VoiceOver on Safari
  -  VoiceOver on Firefox

PiperOrigin-RevId: 648859827
2024-07-02 15:22:12 -07:00

36 lines
882 B
TypeScript

/**
* @license
* Copyright 2024 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
const HAS_ARIA_ATTRIBUTE_REGEX = /\[(aria-|role)/g;
/**
* Patches a CSS selector string to include `data-*` shifting `role` and
* `aria-*` attributes. Use this with `querySelector()` and `querySelectorAll()`
* for MWC elements.
*
* @example
* ```ts
* const agreeCheckbox = document.querySelector(
* ariaSelector('md-checkbox[aria-label="Agree"]')
* );
* ```
*
* @param selector A CSS selector string.
* @return A CSS selector string that includes `data-*` shifting aria
* attributes.
*/
export function ariaSelector(selector: string) {
if (!HAS_ARIA_ATTRIBUTE_REGEX.test(selector)) {
return selector;
}
const selectorWithDataShifted = selector.replaceAll(
HAS_ARIA_ATTRIBUTE_REGEX,
'[data-$1',
);
return `${selector},${selectorWithDataShifted}`;
}